open-presence 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 481b794cc29eb5471b718099609816afa6e3fd6451fe6c4371f553a98719824f
4
+ data.tar.gz: 26ae208bdf34b8ff671a7148a4ec4c623df0b42151e73671436bac76eae9d803
5
+ SHA512:
6
+ metadata.gz: 3d0c520725e9b454b4428d9d7bdb1d8a87fe8b2f5da916efe6ab472f35f8a9a8b738b5dacc4c37a4995067842c0df32394c2247b2ed4e5f9fcc7eff84de9bb54
7
+ data.tar.gz: ca394a17f97cc5e6cc2a16d17fc67dc62aa557605eac4c2d8cd341310331fc097d9d715ef0d9808fed6651b538f6a30a11ba1455bea487c2301a0b096f138e97
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,146 @@
1
+ # OPP Ruby
2
+
3
+ `opp` implements the Open Presence Protocol (OPP) 0.1 Presence Document
4
+ lifecycle and reusable OPP signing primitives for Ruby 3.2 and newer.
5
+
6
+ ## Installation
7
+
8
+ Add the gem to your bundle:
9
+
10
+ ```ruby
11
+ gem "open-presence", "~> 0.1.0"
12
+ ```
13
+
14
+ Then run `bundle install`. To install it directly, run
15
+ `gem install opp -v "~> 0.1.0"`.
16
+
17
+ ## Presence Documents
18
+
19
+ Generate an Ed25519 key pair and derive its OPP subject:
20
+
21
+ ```ruby
22
+ require "opp"
23
+ require "time"
24
+
25
+ pair = OPP::KeyPair.generate
26
+ subject = OPP::Subject.derive(pair.public_key)
27
+ ```
28
+
29
+ `pair.private_key` is a secret 32-byte seed encoded as unpadded Base64url.
30
+ Do not log, publish, or commit it. Store it with the same protections as any
31
+ other signing credential. The public key and derived subject are safe to
32
+ publish.
33
+
34
+ Sign a Presence Document. Signing returns a new hash and does not mutate the
35
+ input. The public key, subject, and signature are added by the library.
36
+
37
+ ```ruby
38
+ document = {
39
+ "type" => "open-presence",
40
+ "version" => "0.1",
41
+ "issued_at" => "2026-07-12T00:00:00Z",
42
+ "expires_at" => "2026-07-13T00:00:00Z",
43
+ "services" => [
44
+ { "type" => "profile", "url" => "https://example.com/alice" }
45
+ ]
46
+ }
47
+
48
+ signed = OPP::Presence.sign(document, private_key: pair.private_key)
49
+ ```
50
+
51
+ Non-bang verification returns an `OPP::VerificationResult`. Pass `at:` when
52
+ you need a reproducible verification time; otherwise it defaults to the
53
+ current UTC time.
54
+
55
+ ```ruby
56
+ result = OPP::Presence.verify(
57
+ signed,
58
+ at: Time.iso8601("2026-07-12T12:00:00Z")
59
+ )
60
+
61
+ if result.valid?
62
+ puts "valid"
63
+ else
64
+ result.errors.each do |error|
65
+ warn [error.code, error.path, error.message].compact.join(": ")
66
+ end
67
+ end
68
+ ```
69
+
70
+ `OPP::Presence.verify!` returns `true` for a valid document and raises the
71
+ first structured `OPP::Error` for an invalid one:
72
+
73
+ ```ruby
74
+ begin
75
+ OPP::Presence.verify!(signed, at: Time.iso8601("2026-07-12T12:00:00Z"))
76
+ rescue OPP::Error => error
77
+ warn "#{error.code} at #{error.path}: #{error.message}"
78
+ end
79
+ ```
80
+
81
+ Errors expose a machine-readable `code`, an optional field `path`, and a
82
+ human-readable message. Specific failures use subclasses such as
83
+ `OPP::ValidationError`, `OPP::InvalidSignatureError`,
84
+ `OPP::ExpiredDocumentError`, and `OPP::UnsupportedVersionError`.
85
+
86
+ Unknown top-level fields, unknown service fields, and unknown service types
87
+ are accepted. They remain part of the canonical signed payload, so changing
88
+ or removing them invalidates the signature.
89
+
90
+ ## Generic signatures
91
+
92
+ `OPP::Signature` signs any JSON-object-shaped hash without applying Presence
93
+ validation. This is useful for other OPP objects:
94
+
95
+ ```ruby
96
+ registration = {
97
+ "type" => "open-presence-directory-registration",
98
+ "version" => "0.2",
99
+ "sequence" => 7,
100
+ "subject" => subject,
101
+ "extension" => { "enabled" => true }
102
+ }
103
+
104
+ signed_registration = OPP::Signature.sign(
105
+ registration,
106
+ private_key: pair.private_key
107
+ )
108
+ OPP::Signature.verify!(signed_registration, public_key: pair.public_key)
109
+ ```
110
+
111
+ `OPP::Signature.verify!` returns `true` or raises
112
+ `OPP::InvalidSignatureError`. `OPP::Signature.verify` is also available when
113
+ a boolean result is preferable. Both signing APIs return deep copies rather
114
+ than mutating caller-owned hashes, and unknown and nested fields are
115
+ authenticated.
116
+
117
+ The generic API is responsible only for signature structure,
118
+ canonicalization, key handling, and cryptographic verification. In
119
+ particular, it does not validate Directory Registration schemas, sequence
120
+ rules, persistence, networking, or discovery. Applications using generic
121
+ signatures must validate their own object schema and protocol rules.
122
+
123
+ ## Vectors and interoperability
124
+
125
+ The offline conformance suite vendors the language-neutral OPP vectors under
126
+ `spec/fixtures/opp`. Their source repository, exact commit, retrieval date,
127
+ and verification time are recorded in `spec/fixtures/opp/UPSTREAM.yml`; the
128
+ current snapshot comes from `jodydawkins/opp` commit
129
+ `73e4e761ad05ac5b6f4cd7ac3ad7c59842dadeba`.
130
+
131
+ For reciprocal interoperability testing:
132
+
133
+ 1. Use the deterministic private-key seed from the pinned vector snapshot.
134
+ 2. Sign the same document with `OPP::Presence.sign` and serialize the returned
135
+ hash as JSON.
136
+ 3. Add the Ruby-produced JSON to the upstream/Rust interoperability fixtures
137
+ and verify it there at the manifest's fixed verification time.
138
+ 4. Copy the corresponding Rust-produced signed fixture into the pinned Ruby
139
+ snapshot and run `bundle exec rspec spec/opp/conformance_spec.rb` offline.
140
+
141
+ This gem deliberately has no CLI. Use the Ruby API directly or build
142
+ application-specific commands around it.
143
+
144
+ ## License
145
+
146
+ Apache-2.0. See `LICENSE`.
@@ -0,0 +1,27 @@
1
+ require "base64"
2
+
3
+ module OPP
4
+ module Base64URL
5
+ ALPHABET = /\A[A-Za-z0-9_-]*\z/
6
+
7
+ module_function
8
+
9
+ def encode(bytes)
10
+ Base64.urlsafe_encode64(bytes, padding: false)
11
+ end
12
+
13
+ def decode(value, length: nil)
14
+ unless value.is_a?(String) && ALPHABET.match?(value)
15
+ raise InvalidEncodingError, "invalid unpadded Base64url"
16
+ end
17
+
18
+ bytes = Base64.urlsafe_decode64(value.ljust((value.length + 3) / 4 * 4, "="))
19
+ raise InvalidEncodingError, "non-canonical Base64url" unless encode(bytes) == value
20
+ raise InvalidEncodingError, "expected #{length} bytes" if length && bytes.bytesize != length
21
+
22
+ bytes
23
+ rescue ArgumentError => error
24
+ raise InvalidEncodingError, error.message
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,69 @@
1
+ require "json/canonicalization"
2
+
3
+ module OPP
4
+ module Canonicalization
5
+ class NumberAdapter
6
+ def initialize(value)
7
+ @value = value.to_f
8
+ end
9
+
10
+ def to_json_c14n
11
+ Canonicalization.send(:serialize_float, @value)
12
+ end
13
+ end
14
+ private_constant :NumberAdapter
15
+
16
+ module_function
17
+
18
+ def canonicalize(value)
19
+ adapt(value).to_json_c14n.encode(Encoding::UTF_8)
20
+ rescue StandardError => error
21
+ raise if error.is_a?(OPP::Error)
22
+
23
+ raise CanonicalizationError, error.message
24
+ end
25
+
26
+ def adapt(value)
27
+ case value
28
+ when Integer, Float
29
+ NumberAdapter.new(value)
30
+ when Hash
31
+ value.to_h { |key, member| [key, adapt(member)] }
32
+ when Array
33
+ value.map { |member| adapt(member) }
34
+ else
35
+ value
36
+ end
37
+ end
38
+ private_class_method :adapt
39
+
40
+ def serialize_float(value)
41
+ raise RangeError, "non-finite number" unless value.finite?
42
+ return "0" if value.zero?
43
+
44
+ representation = value.to_s
45
+ sign = representation.delete_prefix!("-") ? "-" : ""
46
+ return sign + representation.delete_suffix(".0") unless representation.include?("e")
47
+
48
+ mantissa, exponent_text = representation.split("e")
49
+ exponent = exponent_text.to_i
50
+ digits = mantissa.end_with?(".0") ? mantissa.delete_suffix(".0") : mantissa.delete(".")
51
+
52
+ if exponent.between?(-6, 20)
53
+ decimal_position = exponent + 1
54
+ decimal = if decimal_position <= 0
55
+ "0." + ("0" * -decimal_position) + digits
56
+ elsif decimal_position >= digits.length
57
+ digits + ("0" * (decimal_position - digits.length))
58
+ else
59
+ digits.dup.insert(decimal_position, ".")
60
+ end
61
+ sign + decimal
62
+ else
63
+ coefficient = digits.length == 1 ? digits : digits.dup.insert(1, ".")
64
+ sign + coefficient + "e" + (exponent.positive? ? "+" : "") + exponent.to_s
65
+ end
66
+ end
67
+ private_class_method :serialize_float
68
+ end
69
+ end
data/lib/opp/errors.rb ADDED
@@ -0,0 +1,23 @@
1
+ module OPP
2
+ class Error < StandardError
3
+ attr_reader :code, :path
4
+
5
+ def initialize(message = nil, code: nil, path: nil)
6
+ super(message)
7
+ @code = code || self.class.name.split("::").last
8
+ .gsub(/([a-z\d])([A-Z])/, "\\1_\\2").downcase.delete_suffix("_error")
9
+ @path = path
10
+ end
11
+ end
12
+
13
+ ParseError = Class.new(Error)
14
+ DuplicateMemberError = Class.new(Error)
15
+ ValidationError = Class.new(Error)
16
+ CanonicalizationError = Class.new(Error)
17
+ InvalidEncodingError = Class.new(Error)
18
+ InvalidPublicKeyError = Class.new(Error)
19
+ SubjectMismatchError = Class.new(Error)
20
+ InvalidSignatureError = Class.new(Error)
21
+ ExpiredDocumentError = Class.new(Error)
22
+ UnsupportedVersionError = Class.new(Error)
23
+ end
data/lib/opp/json.rb ADDED
@@ -0,0 +1,43 @@
1
+ require "json"
2
+
3
+ module OPP
4
+ module JSON
5
+ class DuplicateCheckingHash < Hash
6
+ def []=(key, value)
7
+ raise DuplicateMemberError, "duplicate JSON member: #{key}" if key?(key)
8
+
9
+ super
10
+ end
11
+ end
12
+ private_constant :DuplicateCheckingHash
13
+
14
+ module_function
15
+
16
+ def parse(input)
17
+ plain_value(::JSON.parse(input, object_class: DuplicateCheckingHash))
18
+ rescue ::JSON::ParserError, EncodingError => error
19
+ raise ParseError, error.message
20
+ end
21
+
22
+ def plain_value(value)
23
+ case value
24
+ when DuplicateCheckingHash
25
+ value.to_h { |key, member| [valid_string(key), plain_value(member)] }
26
+ when Array
27
+ value.map { |member| plain_value(member) }
28
+ when String
29
+ valid_string(value)
30
+ else
31
+ value
32
+ end
33
+ end
34
+ private_class_method :plain_value
35
+
36
+ def valid_string(value)
37
+ raise EncodingError, "invalid Unicode in JSON string" unless value.valid_encoding?
38
+
39
+ value
40
+ end
41
+ private_class_method :valid_string
42
+ end
43
+ end
@@ -0,0 +1,27 @@
1
+ require "ed25519"
2
+
3
+ module OPP
4
+ class KeyPair
5
+ attr_reader :private_key, :public_key
6
+
7
+ def self.generate
8
+ new(Ed25519::SigningKey.generate)
9
+ end
10
+
11
+ def self.from_private_key(value)
12
+ new(Ed25519::SigningKey.new(Base64URL.decode(value, length: 32)))
13
+ end
14
+
15
+ def initialize(signing_key)
16
+ @signing_key = signing_key
17
+ @private_key = Base64URL.encode(signing_key.to_bytes)
18
+ @public_key = Base64URL.encode(signing_key.verify_key.to_bytes)
19
+ end
20
+
21
+ def sign(bytes)
22
+ @signing_key.sign(bytes)
23
+ end
24
+
25
+ private_class_method :new
26
+ end
27
+ end
@@ -0,0 +1,197 @@
1
+ require "date"
2
+ require "time"
3
+ require "uri"
4
+
5
+ module OPP
6
+ module Presence
7
+ REQUIRED = %w[type version subject public_key issued_at services signature].freeze
8
+ TYPES = {
9
+ "type" => String,
10
+ "version" => String,
11
+ "subject" => String,
12
+ "public_key" => String,
13
+ "issued_at" => String,
14
+ "services" => Array,
15
+ "signature" => Hash,
16
+ "expires_at" => String
17
+ }.freeze
18
+ TIMESTAMP_PATTERN = /\A(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<fraction>\d+))?Z\z/
19
+
20
+ module_function
21
+
22
+ def sign(document, private_key:)
23
+ raise ValidationError, "document must be an object" unless document.is_a?(Hash)
24
+
25
+ pair = KeyPair.from_private_key(private_key)
26
+ unsigned = copy(document).tap { |value| value.delete("signature") }.merge(
27
+ "public_key" => pair.public_key,
28
+ "subject" => Subject.derive(pair.public_key)
29
+ )
30
+ errors = validate(unsigned, at: nil, signature_required: false)
31
+ raise errors.first unless errors.empty?
32
+
33
+ Signature.sign(unsigned, private_key:)
34
+ end
35
+
36
+ def verify(input, at: Time.now.utc)
37
+ document = input.is_a?(String) ? OPP::JSON.parse(input) : copy(input)
38
+ VerificationResult.new(validate(document, at:, signature_required: true))
39
+ rescue OPP::Error => error
40
+ VerificationResult.new([error])
41
+ end
42
+
43
+ def verify!(input, at: Time.now.utc)
44
+ result = verify(input, at:)
45
+ raise result.errors.first unless result.valid?
46
+
47
+ true
48
+ end
49
+
50
+ def validate(document, at:, signature_required:)
51
+ return [ValidationError.new("document must be an object")] unless document.is_a?(Hash)
52
+
53
+ errors = required_errors(document, signature_required:)
54
+ errors.concat(type_errors(document))
55
+ errors << ValidationError.new("type must be open-presence", path: "type") if
56
+ document["type"].is_a?(String) && document["type"] != "open-presence"
57
+ errors << UnsupportedVersionError.new("unsupported version: #{document["version"]}", path: "version") if
58
+ document["version"].is_a?(String) && document["version"] != "0.1"
59
+
60
+ public_key_usable = validate_credentials(document, errors)
61
+ validate_timestamps(document, at:, errors:)
62
+ validate_services(document, errors)
63
+ if signature_required && public_key_usable && document["signature"].is_a?(Hash)
64
+ begin
65
+ Signature.verify!(document, public_key: document["public_key"])
66
+ rescue OPP::Error => error
67
+ errors << error
68
+ end
69
+ end
70
+ errors
71
+ end
72
+ private_class_method :validate
73
+
74
+ def required_errors(document, signature_required:)
75
+ required = signature_required ? REQUIRED : REQUIRED - ["signature"]
76
+ required.filter_map do |field|
77
+ ValidationError.new("missing required field: #{field}", path: field) unless document.key?(field)
78
+ end
79
+ end
80
+ private_class_method :required_errors
81
+
82
+ def type_errors(document)
83
+ TYPES.filter_map do |field, type|
84
+ next unless document.key?(field) && !document[field].is_a?(type)
85
+
86
+ ValidationError.new("#{field} must be #{type.name.downcase}", path: field)
87
+ end
88
+ end
89
+ private_class_method :type_errors
90
+
91
+ def validate_credentials(document, errors)
92
+ return false unless document["public_key"].is_a?(String)
93
+
94
+ begin
95
+ PublicKey.decode(document["public_key"])
96
+ rescue InvalidPublicKeyError => error
97
+ errors << InvalidPublicKeyError.new(error.message, path: "public_key")
98
+ return false
99
+ end
100
+
101
+ if document["subject"].is_a?(String)
102
+ begin
103
+ Subject.verify!(document["subject"], public_key: document["public_key"])
104
+ rescue SubjectMismatchError => error
105
+ errors << SubjectMismatchError.new(error.message, path: "subject")
106
+ end
107
+ end
108
+ true
109
+ end
110
+ private_class_method :validate_credentials
111
+
112
+ def validate_timestamps(document, at:, errors:)
113
+ issued_at = parse_timestamp(document, "issued_at", errors)
114
+ expires_at = parse_timestamp(document, "expires_at", errors) if document.key?("expires_at")
115
+ return unless expires_at
116
+
117
+ if issued_at && expires_at <= issued_at
118
+ errors << ValidationError.new("expires_at must be later than issued_at", path: "expires_at")
119
+ end
120
+ if at && at >= expires_at
121
+ errors << ExpiredDocumentError.new("document has expired", path: "expires_at")
122
+ end
123
+ end
124
+ private_class_method :validate_timestamps
125
+
126
+ def parse_timestamp(document, field, errors)
127
+ value = document[field]
128
+ return unless value.is_a?(String)
129
+
130
+ match = TIMESTAMP_PATTERN.match(value)
131
+ unless match
132
+ errors << ValidationError.new("#{field} must be an RFC 3339 UTC timestamp", path: field)
133
+ return
134
+ end
135
+
136
+ year, month, day, hour, minute, second =
137
+ %i[year month day hour minute second].map { |component| match[component].to_i }
138
+ date = Date.new(year, month, day)
139
+ raise ArgumentError unless hour.between?(0, 23) && minute.between?(0, 59) && second.between?(0, 60)
140
+ raise ArgumentError if second == 60 && (hour != 23 || minute != 59 || date.next_day.day != 1)
141
+
142
+ fraction = match[:fraction] ? Rational(match[:fraction].to_i, 10**match[:fraction].length) : 0
143
+ Time.utc(year, month, day, hour, minute, [second, 59].min) + fraction + (second == 60 ? 1 : 0)
144
+ rescue ArgumentError
145
+ errors << ValidationError.new("#{field} must be a valid timestamp", path: field)
146
+ nil
147
+ end
148
+ private_class_method :parse_timestamp
149
+
150
+ def validate_services(document, errors)
151
+ return unless document["services"].is_a?(Array)
152
+
153
+ document["services"].each_with_index do |service, index|
154
+ base = "services[#{index}]"
155
+ unless service.is_a?(Hash)
156
+ errors << ValidationError.new("#{base} must be an object", path: base)
157
+ next
158
+ end
159
+
160
+ %w[type url].each do |field|
161
+ errors << ValidationError.new("missing required field: #{base}.#{field}", path: "#{base}.#{field}") unless
162
+ service.key?(field)
163
+ end
164
+ %w[type url].each do |field|
165
+ errors << ValidationError.new("#{base}.#{field} must be a string", path: "#{base}.#{field}") if
166
+ service.key?(field) && !service[field].is_a?(String)
167
+ end
168
+ validate_service_url(service["url"], "#{base}.url", errors) if service["url"].is_a?(String)
169
+ end
170
+ end
171
+ private_class_method :validate_services
172
+
173
+ def validate_service_url(value, path, errors)
174
+ uri = ::URI.parse(value)
175
+ return if uri.is_a?(::URI::HTTPS) && !uri.host.to_s.empty? && uri.user.nil? && uri.password.nil?
176
+
177
+ errors << ValidationError.new("#{path} must be an absolute credential-free HTTPS URL", path: path)
178
+ rescue ::URI::InvalidURIError
179
+ errors << ValidationError.new("#{path} must be a valid URL", path: path)
180
+ end
181
+ private_class_method :validate_service_url
182
+
183
+ def copy(value)
184
+ case value
185
+ when Hash
186
+ value.to_h { |key, item| [key, copy(item)] }
187
+ when Array
188
+ value.map { |item| copy(item) }
189
+ when String
190
+ value.dup
191
+ else
192
+ value
193
+ end
194
+ end
195
+ private_class_method :copy
196
+ end
197
+ end
@@ -0,0 +1,15 @@
1
+ require "ed25519"
2
+
3
+ module OPP
4
+ module PublicKey
5
+ module_function
6
+
7
+ def decode(value)
8
+ bytes = Base64URL.decode(value, length: 32)
9
+ Ed25519::VerifyKey.new(bytes)
10
+ bytes
11
+ rescue InvalidEncodingError => error
12
+ raise InvalidPublicKeyError, error.message
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,76 @@
1
+ require "ed25519"
2
+
3
+ module OPP
4
+ module Signature
5
+ module_function
6
+
7
+ def sign(document, private_key:)
8
+ unsigned = unsigned_document(document)
9
+ bytes = KeyPair.from_private_key(private_key)
10
+ .sign(Canonicalization.canonicalize(unsigned))
11
+
12
+ unsigned.merge(
13
+ "signature" => {
14
+ "algorithm" => "ed25519",
15
+ "value" => Base64URL.encode(bytes)
16
+ }
17
+ )
18
+ rescue InvalidEncodingError => error
19
+ raise InvalidSignatureError, error.message
20
+ end
21
+
22
+ def verify(document, public_key:)
23
+ verify!(document, public_key:)
24
+ rescue InvalidSignatureError
25
+ false
26
+ end
27
+
28
+ def verify!(document, public_key:)
29
+ unsigned, signature = split(document)
30
+ unless signature["algorithm"] == "ed25519"
31
+ raise InvalidSignatureError, "unsupported signature algorithm"
32
+ end
33
+
34
+ bytes = Base64URL.decode(signature["value"], length: 64)
35
+ verify_key = Ed25519::VerifyKey.new(PublicKey.decode(public_key))
36
+ verify_key.verify(bytes, Canonicalization.canonicalize(unsigned))
37
+ true
38
+ rescue Ed25519::VerifyError, InvalidEncodingError, InvalidPublicKeyError => error
39
+ raise InvalidSignatureError, error.message
40
+ end
41
+
42
+ def split(document)
43
+ unsigned = unsigned_document(document)
44
+ signature = document["signature"]
45
+ unless signature.is_a?(Hash) &&
46
+ signature["algorithm"].is_a?(String) &&
47
+ signature["value"].is_a?(String)
48
+ raise InvalidSignatureError, "invalid signature object"
49
+ end
50
+
51
+ [unsigned, copy(signature)]
52
+ end
53
+ private_class_method :split
54
+
55
+ def unsigned_document(document)
56
+ raise ValidationError, "document must be an object" unless document.is_a?(Hash)
57
+
58
+ copy(document).tap { |value| value.delete("signature") }
59
+ end
60
+ private_class_method :unsigned_document
61
+
62
+ def copy(value)
63
+ case value
64
+ when Hash
65
+ value.to_h { |key, item| [key, copy(item)] }
66
+ when Array
67
+ value.map { |item| copy(item) }
68
+ when String
69
+ value.dup
70
+ else
71
+ value
72
+ end
73
+ end
74
+ private_class_method :copy
75
+ end
76
+ end
@@ -0,0 +1,26 @@
1
+ require "digest"
2
+
3
+ module OPP
4
+ module Subject
5
+ PREFIX = "key:sha256:"
6
+
7
+ module_function
8
+
9
+ def derive(public_key)
10
+ PREFIX + Base64URL.encode(Digest::SHA256.digest(PublicKey.decode(public_key)))
11
+ end
12
+
13
+ def verify!(subject, public_key:)
14
+ return true if subject.is_a?(String) && secure_equal(subject, derive(public_key))
15
+
16
+ raise SubjectMismatchError, "subject does not match public key"
17
+ end
18
+
19
+ def secure_equal(left, right)
20
+ left.bytesize == right.bytesize && left.bytes.zip(right.bytes).reduce(0) do |difference, (a, b)|
21
+ difference | (a ^ b)
22
+ end.zero?
23
+ end
24
+ private_class_method :secure_equal
25
+ end
26
+ end
@@ -0,0 +1,13 @@
1
+ module OPP
2
+ class VerificationResult
3
+ attr_reader :errors
4
+
5
+ def initialize(errors)
6
+ @errors = errors.freeze
7
+ end
8
+
9
+ def valid?
10
+ errors.empty?
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,3 @@
1
+ module OPP
2
+ VERSION = "0.1.0"
3
+ end
data/lib/opp.rb ADDED
@@ -0,0 +1,11 @@
1
+ require_relative "opp/version"
2
+ require_relative "opp/errors"
3
+ require_relative "opp/base64_url"
4
+ require_relative "opp/public_key"
5
+ require_relative "opp/key_pair"
6
+ require_relative "opp/subject"
7
+ require_relative "opp/json"
8
+ require_relative "opp/canonicalization"
9
+ require_relative "opp/signature"
10
+ require_relative "opp/verification_result"
11
+ require_relative "opp/presence"
metadata ADDED
@@ -0,0 +1,133 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: open-presence
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jody Dawkins
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 2026-07-19 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: ed25519
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '1.4'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '1.4'
26
+ - !ruby/object:Gem::Dependency
27
+ name: base64
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0.2'
33
+ - - "<"
34
+ - !ruby/object:Gem::Version
35
+ version: '1'
36
+ type: :runtime
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: '0.2'
43
+ - - "<"
44
+ - !ruby/object:Gem::Version
45
+ version: '1'
46
+ - !ruby/object:Gem::Dependency
47
+ name: json
48
+ requirement: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '2.6'
53
+ - - "<"
54
+ - !ruby/object:Gem::Version
55
+ version: '2.10'
56
+ type: :runtime
57
+ prerelease: false
58
+ version_requirements: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: '2.6'
63
+ - - "<"
64
+ - !ruby/object:Gem::Version
65
+ version: '2.10'
66
+ - !ruby/object:Gem::Dependency
67
+ name: json-canonicalization
68
+ requirement: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - "~>"
71
+ - !ruby/object:Gem::Version
72
+ version: '0.4'
73
+ type: :runtime
74
+ prerelease: false
75
+ version_requirements: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - "~>"
78
+ - !ruby/object:Gem::Version
79
+ version: '0.4'
80
+ - !ruby/object:Gem::Dependency
81
+ name: rspec
82
+ requirement: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - "~>"
85
+ - !ruby/object:Gem::Version
86
+ version: '3.13'
87
+ type: :development
88
+ prerelease: false
89
+ version_requirements: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - "~>"
92
+ - !ruby/object:Gem::Version
93
+ version: '3.13'
94
+ executables: []
95
+ extensions: []
96
+ extra_rdoc_files: []
97
+ files:
98
+ - LICENSE
99
+ - README.md
100
+ - lib/opp.rb
101
+ - lib/opp/base64_url.rb
102
+ - lib/opp/canonicalization.rb
103
+ - lib/opp/errors.rb
104
+ - lib/opp/json.rb
105
+ - lib/opp/key_pair.rb
106
+ - lib/opp/presence.rb
107
+ - lib/opp/public_key.rb
108
+ - lib/opp/signature.rb
109
+ - lib/opp/subject.rb
110
+ - lib/opp/verification_result.rb
111
+ - lib/opp/version.rb
112
+ homepage: https://github.com/jodydawkins/opp-ruby
113
+ licenses:
114
+ - Apache-2.0
115
+ metadata: {}
116
+ rdoc_options: []
117
+ require_paths:
118
+ - lib
119
+ required_ruby_version: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - ">="
122
+ - !ruby/object:Gem::Version
123
+ version: '3.2'
124
+ required_rubygems_version: !ruby/object:Gem::Requirement
125
+ requirements:
126
+ - - ">="
127
+ - !ruby/object:Gem::Version
128
+ version: '0'
129
+ requirements: []
130
+ rubygems_version: 3.6.2
131
+ specification_version: 4
132
+ summary: Open Presence Protocol for Ruby
133
+ test_files: []