sattleme-checkout 1.0.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.
Files changed (46) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +66 -0
  3. data/LICENSE +21 -0
  4. data/README.md +754 -0
  5. data/SECURITY.md +25 -0
  6. data/lib/sattleme/checkout/cancellation.rb +195 -0
  7. data/lib/sattleme/checkout/client.rb +1438 -0
  8. data/lib/sattleme/checkout/errors.rb +165 -0
  9. data/lib/sattleme/checkout/http_client.rb +294 -0
  10. data/lib/sattleme/checkout/internal/bolt11.rb +187 -0
  11. data/lib/sattleme/checkout/internal/channel.rb +147 -0
  12. data/lib/sattleme/checkout/internal/checkout_link.rb +294 -0
  13. data/lib/sattleme/checkout/internal/concurrency.rb +450 -0
  14. data/lib/sattleme/checkout/internal/crypto.rb +63 -0
  15. data/lib/sattleme/checkout/internal/currencies.rb +47 -0
  16. data/lib/sattleme/checkout/internal/declaration.rb +135 -0
  17. data/lib/sattleme/checkout/internal/derive.rb +153 -0
  18. data/lib/sattleme/checkout/internal/event.rb +110 -0
  19. data/lib/sattleme/checkout/internal/http.rb +129 -0
  20. data/lib/sattleme/checkout/internal/json.rb +457 -0
  21. data/lib/sattleme/checkout/internal/key.rb +116 -0
  22. data/lib/sattleme/checkout/internal/lnurl.rb +238 -0
  23. data/lib/sattleme/checkout/internal/nip44.rb +113 -0
  24. data/lib/sattleme/checkout/internal/onchain/address.rb +58 -0
  25. data/lib/sattleme/checkout/internal/onchain/basics.rb +352 -0
  26. data/lib/sattleme/checkout/internal/onchain/lease.rb +326 -0
  27. data/lib/sattleme/checkout/internal/onchain/merchant_acceptance.rb +168 -0
  28. data/lib/sattleme/checkout/internal/onchain/node.rb +285 -0
  29. data/lib/sattleme/checkout/internal/onchain/payment.rb +345 -0
  30. data/lib/sattleme/checkout/internal/onchain/rest.rb +323 -0
  31. data/lib/sattleme/checkout/internal/onchain/watch.rb +119 -0
  32. data/lib/sattleme/checkout/internal/onchain/witness.rb +260 -0
  33. data/lib/sattleme/checkout/internal/order.rb +228 -0
  34. data/lib/sattleme/checkout/internal/protocol.rb +260 -0
  35. data/lib/sattleme/checkout/internal/rates.rb +373 -0
  36. data/lib/sattleme/checkout/internal/record.rb +179 -0
  37. data/lib/sattleme/checkout/internal/relay_pool.rb +823 -0
  38. data/lib/sattleme/checkout/internal/sales.rb +238 -0
  39. data/lib/sattleme/checkout/internal/secp256k1.rb +234 -0
  40. data/lib/sattleme/checkout/internal/text.rb +144 -0
  41. data/lib/sattleme/checkout/internal/urls.rb +172 -0
  42. data/lib/sattleme/checkout/models.rb +247 -0
  43. data/lib/sattleme/checkout/version.rb +9 -0
  44. data/lib/sattleme/checkout/websocket_client.rb +487 -0
  45. data/lib/sattleme/checkout.rb +72 -0
  46. metadata +112 -0
@@ -0,0 +1,457 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strscan"
4
+
5
+ module Sattleme
6
+ module Checkout
7
+ module Internal
8
+ # JSON as every implementation reads and writes it (SPEC.md §2): as JavaScript does, not as
9
+ # Ruby's `json` does.
10
+ #
11
+ # Reading (RFC 8259, nothing else): of members with one name, the last counts; every number is
12
+ # its IEEE 754 double (a Float), whatever its spelling, so that `500`, `500.0` and `5e2` are
13
+ # one value and a large integer loses what a double cannot hold, as in JavaScript; a string
14
+ # escape of a lone surrogate (`"\ud800"`) is kept, as JavaScript keeps it: as the three bytes
15
+ # that would encode it (WTF-8), which leave the string's UTF-8 invalid, so that a check of a
16
+ # text (Text.well_formed?) refuses it, while the rest of the document reads (Ruby's `json`
17
+ # refuses the whole document). Whitespace is space, tab, line feed and carriage return: a byte
18
+ # order mark is not JSON. A text in which more than MAX_DEPTH arrays and objects nest, one in
19
+ # another, is not JSON (a bound every platform's parser keeps): a scan tells it before the
20
+ # text is read, the same in every implementation. A member's name is any string, U+0000 in it
21
+ # too.
22
+ #
23
+ # Writing: compact, as `JSON.stringify` writes it (its escapes, numbers as JavaScript prints
24
+ # them, names in the order given).
25
+ module Json
26
+ # Not JSON.
27
+ class Invalid < StandardError; end
28
+
29
+ # A JSON text written as it is (tests write escapes no Ruby string holds).
30
+ Raw = Struct.new(:text)
31
+
32
+ UTF_8 = Encoding::UTF_8
33
+ WHITESPACE = /[ \t\n\r]*/
34
+ NUMBER = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/
35
+ STRING = %r{"((?:[^"\\\x00-\x1F]++|\\["\\/bfnrt]|\\u[0-9a-fA-F]{4})*+)"}
36
+ ESCAPE = %r{\\(?:u[0-9a-fA-F]{4}|["\\/bfnrt])}
37
+ # The bytes each escape of a string stands for: a short escape's character; a \u escape's
38
+ # code unit as UTF-8 would encode it, a surrogate's too (WTF-8: SURROGATE_PAIR then joins a
39
+ # pair, a lone one stays as JavaScript keeps it).
40
+ UNESCAPED = Hash.new { |_, escape| Json.wtf8(escape.byteslice(2, 4).to_i(16)) }.update(
41
+ { '\\"' => '"', "\\\\" => "\\", "\\/" => "/", "\\b" => "\b", "\\f" => "\f", "\\n" => "\n", "\\r" => "\r",
42
+ "\\t" => "\t" }.to_h { |escape, char| [escape.b, char.b] }
43
+ ).freeze
44
+ # A high surrogate then a low one, each as Json.wtf8 encodes it: one code point.
45
+ SURROGATE_PAIR = /\xED([\xA0-\xAF])([\x80-\xBF])\xED([\xB0-\xBF])([\x80-\xBF])/n
46
+ # The first byte of a surrogate as Json.wtf8 encodes it (of U+D000 to U+D7FF in UTF-8 too).
47
+ SURROGATE_LEAD = "\xED".b.freeze
48
+ # The largest integer every JSON reader holds exactly: 2^53 − 1.
49
+ MAX_SAFE_INTEGER = (2**53) - 1
50
+ # The most arrays and objects that nest, one in another, in a JSON text (SPEC.md §2).
51
+ MAX_DEPTH = 64
52
+ # The most significant digits a number's double needs: a halfway point between two doubles
53
+ # has at most 767, so those after 800 count only by whether one of them is not zero (as
54
+ # V8 reads them).
55
+ MAX_DIGITS = 800
56
+ NONZERO_DIGIT = /[1-9]/
57
+ # What the depth scan stops at: a bracket, or a string's quote.
58
+ DEPTH_MARK = /[\[\]{}"]/
59
+ # The rest of a string, its closing quote included (a backslash escapes the next character).
60
+ STRING_REST = /(?:[^"\\]++|\\.)*+"/m
61
+
62
+ module_function
63
+
64
+ # The value of the JSON text `text` (a UTF-8 String); Invalid when it is not JSON.
65
+ def parse(text)
66
+ raise Invalid, "not a string" unless text.is_a?(String)
67
+
68
+ text = text.dup.force_encoding(UTF_8) unless text.encoding == UTF_8
69
+ raise Invalid, "not UTF-8" unless text.valid_encoding?
70
+ raise Invalid, "more than #{MAX_DEPTH} arrays and objects nest" if too_deep?(text)
71
+
72
+ Parser.new(text).parse
73
+ end
74
+
75
+ # Whether more than MAX_DEPTH arrays and objects nest in `text`, outside its strings: each
76
+ # `[` or `{` one deeper, each `]` or `}` one less, as every implementation counts them.
77
+ def too_deep?(text)
78
+ scanner = StringScanner.new(text)
79
+ depth = 0
80
+ while scanner.skip_until(DEPTH_MARK)
81
+ case scanner.matched
82
+ when '"'
83
+ # A string not closed holds the rest of the text.
84
+ return false unless scanner.skip(STRING_REST)
85
+ when "[", "{"
86
+ depth += 1
87
+ return true if depth > MAX_DEPTH
88
+ else
89
+ depth -= 1
90
+ end
91
+ end
92
+ false
93
+ end
94
+
95
+ # The value of `text`, or `fallback` when it is not JSON.
96
+ def parse_or(text, fallback = nil)
97
+ parse(text)
98
+ rescue Invalid
99
+ fallback
100
+ end
101
+
102
+ # The compact JSON text of `value` (Hash, Array, String, Integer, Float, true, false, nil,
103
+ # Raw), as `JSON.stringify` writes it.
104
+ def generate(value)
105
+ out = +""
106
+ write(value, out)
107
+ out
108
+ end
109
+
110
+ # Whether `value` is a JSON number (a boolean never is).
111
+ def number?(value)
112
+ value.is_a?(Float) || value.is_a?(Integer)
113
+ end
114
+
115
+ # Whether `value` is a number whose value is an integer (JavaScript's Number.isInteger).
116
+ def integer?(value)
117
+ value.is_a?(Integer) || (value.is_a?(Float) && value.finite? && value == value.truncate)
118
+ end
119
+
120
+ # Whether `value` is an integer of at most 2^53 − 1 either way (Number.isSafeInteger).
121
+ def safe_integer?(value)
122
+ integer?(value) && value.abs <= MAX_SAFE_INTEGER
123
+ end
124
+
125
+ # The Integer of a safe integer, else nil.
126
+ def safe_integer(value)
127
+ safe_integer?(value) ? value.to_i : nil
128
+ end
129
+
130
+ # A JSON object: a Hash (never null, never an array).
131
+ def object?(value)
132
+ value.is_a?(Hash)
133
+ end
134
+
135
+ # Whether the object `hash` holds `name`, as null: absent is not null (JavaScript's
136
+ # `undefined`), wherever a record reads null as a value.
137
+ def null_member?(hash, name)
138
+ hash.key?(name) && hash[name].nil?
139
+ end
140
+
141
+ # The IEEE 754 double nearest the JSON number `text` (correctly rounded, ties to even), as
142
+ # JavaScript reads it, whatever its length: beyond the doubles' range, an infinity or a zero,
143
+ # never an error. Its significant digits are taken once, without the zeros around them, at
144
+ # most MAX_DIGITS of them: Ruby's own conversion misreads a text of some 20 000 digits or
145
+ # more, its zeros included ("1" and 20 000 zeros "e-20000" is 10.0 there). An exponent of
146
+ # more than 18 digits is beyond every range. So the time it takes is linear in its length.
147
+ def double(text)
148
+ match = /\A(-)?(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?)([0-9]+))?\z/.match(text)
149
+ raise Invalid, "not a number" unless match
150
+
151
+ negative = !match[1].nil?
152
+ fraction = match[3] || ""
153
+ written = match[2] + fraction
154
+ first = written.index(NONZERO_DIGIT)
155
+ # A zero, of the number's sign.
156
+ return (negative ? -1.0 : 1.0) * 0.0 if first.nil?
157
+
158
+ last = written.rindex(NONZERO_DIGIT)
159
+ digits = written[first..last]
160
+ # The power of ten of the last significant digit.
161
+ exponent = exponent_of(match[4], match[5]) - fraction.length + (written.length - 1 - last)
162
+ if digits.length > MAX_DIGITS
163
+ # Its last digit is not zero: the digits cut count as one more that is not either.
164
+ exponent += digits.length - MAX_DIGITS - 1
165
+ digits = "#{digits[0, MAX_DIGITS]}1"
166
+ end
167
+ magnitude = digits.length - 1 + exponent
168
+ # Well within the doubles' range: Ruby's own conversion is correctly rounded there.
169
+ value = if magnitude.between?(-300, 300)
170
+ Float("#{digits}e#{exponent}")
171
+ elsif magnitude > 309
172
+ Float::INFINITY
173
+ elsif magnitude < -325
174
+ 0.0
175
+ else
176
+ nearest_double(Integer(digits, 10), exponent)
177
+ end
178
+ negative ? -value.abs : value
179
+ end
180
+
181
+ # The exponent a number writes (`sign` and `digits`, nil without one): beyond 18 digits, a
182
+ # power of ten no text reaches with its own digits (a number of 10^18 characters), so that
183
+ # the number is out of range whatever they are.
184
+ def exponent_of(sign, digits)
185
+ return 0 if digits.nil?
186
+
187
+ significant = digits.sub(/\A0+/, "")
188
+ value = significant.length > 18 ? 10**18 : significant.to_i
189
+ sign == "-" ? -value : value
190
+ end
191
+
192
+ # The double nearest `units` × 10^`exponent` (positive), on integers: for the edges of the
193
+ # doubles' range, where Ruby's conversion warns.
194
+ def nearest_double(units, exponent)
195
+ numerator = exponent.negative? ? units : units * (10**exponent)
196
+ denominator = exponent.negative? ? 10**-exponent : 1
197
+ # 2^bits ≤ value < 2^(bits + 1).
198
+ bits = numerator.bit_length - denominator.bit_length
199
+ bits -= 1 if bits >= 0 ? numerator < denominator << bits : numerator << -bits < denominator
200
+ return Float::INFINITY if bits > 1023
201
+
202
+ # The weight of the last bit of the result: 53 bits, fewer below the normal doubles.
203
+ scale = [bits - 52, -1074].max
204
+ scaled_num = scale.negative? ? numerator << -scale : numerator
205
+ scaled_den = scale.negative? ? denominator : denominator << scale
206
+ quotient, remainder = scaled_num.divmod(scaled_den)
207
+ twice = remainder * 2
208
+ quotient += 1 if twice > scaled_den || (twice == scaled_den && quotient.odd?)
209
+ return Float::INFINITY if quotient.bit_length + scale > 1024
210
+
211
+ Math.ldexp(quotient.to_f, scale)
212
+ end
213
+
214
+ # The text JavaScript gives a finite number (Number::toString): the shortest digits that
215
+ # read back as the same double, in full below 10^21 (1.2345678901234568e20 is
216
+ # 123456789012345680000, not the double's exact 123456789012345683968), else with an
217
+ # exponent. An Integer is written as it is (the gem writes safe integers only).
218
+ def number_text(value)
219
+ raise ArgumentError, "not a finite number" unless value.is_a?(Integer) || value.finite?
220
+ return value.to_s if value.is_a?(Integer)
221
+ return "0" if value.zero?
222
+
223
+ sign = value.negative? ? "-" : ""
224
+ # Ruby's shortest digits (David Gay's), in JavaScript's layout.
225
+ mantissa, exponent = value.abs.to_s.split("e")
226
+ whole, fraction = mantissa.split(".")
227
+ digits = whole + fraction.to_s
228
+ point = whole.length + exponent.to_i
229
+ leading = digits[/\A0*/].length
230
+ digits = digits[leading..]
231
+ point -= leading
232
+ digits = digits.sub(/0+\z/, "")
233
+ sign + layout(digits, point)
234
+ end
235
+
236
+ # ECMAScript's Number::toString of the digits `digits` with the decimal point after
237
+ # `point` of them.
238
+ def layout(digits, point)
239
+ size = digits.length
240
+ if point.between?(size, 21)
241
+ digits + ("0" * (point - size))
242
+ elsif point.positive? && point <= 21
243
+ "#{digits[0, point]}.#{digits[point..]}"
244
+ elsif point > -6 && point <= 0
245
+ "0.#{"0" * -point}#{digits}"
246
+ else
247
+ exponent = point - 1
248
+ mark = exponent.negative? ? "-" : "+"
249
+ head = size == 1 ? digits : "#{digits[0]}.#{digits[1..]}"
250
+ "#{head}e#{mark}#{exponent.abs}"
251
+ end
252
+ end
253
+
254
+ def write(value, out)
255
+ case value
256
+ when nil then out << "null"
257
+ when true then out << "true"
258
+ when false then out << "false"
259
+ when Integer, Float then out << number_text(value)
260
+ when String then write_string(value, out)
261
+ when Symbol then write_string(value.to_s, out)
262
+ when Array
263
+ out << "["
264
+ value.each_with_index do |item, index|
265
+ out << "," if index.positive?
266
+ write(item, out)
267
+ end
268
+ out << "]"
269
+ when Hash
270
+ out << "{"
271
+ value.each_with_index do |(name, item), index|
272
+ out << "," if index.positive?
273
+ write_string(name.to_s, out)
274
+ out << ":"
275
+ write(item, out)
276
+ end
277
+ out << "}"
278
+ when Raw then out << value.text
279
+ else raise ArgumentError, "no JSON for a #{value.class}"
280
+ end
281
+ end
282
+
283
+ # What JSON.stringify writes of each character a string escapes: its short escape, else
284
+ # \u00XX (the other control characters). Complete, so that each is looked up as it comes.
285
+ STRING_ESCAPES = (0x00..0x1F).to_h { |code| [code.chr, format("\\u%04x", code)] }.merge(
286
+ '"' => '\\"', "\\" => "\\\\", "\b" => "\\b", "\f" => "\\f", "\n" => "\\n",
287
+ "\r" => "\\r", "\t" => "\\t"
288
+ ).freeze
289
+ # The characters a string escapes.
290
+ ESCAPED = /["\\\x00-\x1F]/
291
+ # Lone surrogates, as Json.parse keeps them (WTF-8), which JSON.stringify writes as escapes.
292
+ SURROGATE = /\xED[\xA0-\xBF][\x80-\xBF]/n
293
+
294
+ def write_string(text, out)
295
+ text = text.dup.force_encoding(UTF_8) unless text.encoding == UTF_8
296
+ out << '"'
297
+ out << if text.valid_encoding?
298
+ text.gsub(ESCAPED, STRING_ESCAPES)
299
+ else
300
+ wtf8_escaped(text)
301
+ end
302
+ out << '"'
303
+ end
304
+
305
+ # `text`, whose UTF-8 is broken only by lone surrogates, with JSON.stringify's escapes.
306
+ def wtf8_escaped(text)
307
+ bytes = text.b
308
+ parts = []
309
+ rest = bytes
310
+ until rest.empty?
311
+ index = rest =~ SURROGATE
312
+ plain = (index ? rest[0, index] : rest).force_encoding(UTF_8)
313
+ raise ArgumentError, "not a text" unless plain.valid_encoding?
314
+
315
+ parts << plain.gsub(ESCAPED, STRING_ESCAPES)
316
+ break unless index
317
+
318
+ unit = ((rest.getbyte(index) & 0x0F) << 12) | ((rest.getbyte(index + 1) & 0x3F) << 6) |
319
+ (rest.getbyte(index + 2) & 0x3F)
320
+ parts << format("\\u%04x", unit)
321
+ rest = rest[(index + 3)..]
322
+ end
323
+ parts.join
324
+ end
325
+
326
+ # The text of a string's `body` (between its quotes, as RFC 8259 writes it), its escapes
327
+ # read: a surrogate pair joined, a lone surrogate kept (WTF-8). Over its bytes, each escape
328
+ # replaced as it comes: time linear in its length (SPEC.md §13, Limits). Read over its
329
+ # characters, each escape's offset would be counted from the start again: a cost that grows
330
+ # with the square of the length, with which anybody who writes events at a lease's `d` tag
331
+ # would make every read of leases run out of time.
332
+ def unescape(body)
333
+ text = body.b.gsub(ESCAPE, UNESCAPED)
334
+ text = text.gsub(SURROGATE_PAIR) { joined(Regexp.last_match) } if text.include?(SURROGATE_LEAD)
335
+ text.force_encoding(UTF_8)
336
+ end
337
+
338
+ # The bytes of a code unit below U+10000 as UTF-8 would encode it, surrogates included.
339
+ def wtf8(unit)
340
+ if unit < 0x80
341
+ unit.chr
342
+ elsif unit < 0x800
343
+ [0xC0 | (unit >> 6), 0x80 | (unit & 0x3F)].pack("C*")
344
+ else
345
+ [0xE0 | (unit >> 12), 0x80 | ((unit >> 6) & 0x3F), 0x80 | (unit & 0x3F)].pack("C*")
346
+ end
347
+ end
348
+
349
+ # The UTF-8 of the code point of a SURROGATE_PAIR match: its high and its low surrogate, each
350
+ # as wtf8 encodes it (0xED, then its 12 low bits in two bytes).
351
+ def joined(match)
352
+ high = 0xD000 | ((match[1].ord & 0x3F) << 6) | (match[2].ord & 0x3F)
353
+ low = 0xD000 | ((match[3].ord & 0x3F) << 6) | (match[4].ord & 0x3F)
354
+ [0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00)].pack("U").b
355
+ end
356
+
357
+ # An iterative RFC 8259 reader over a StringScanner.
358
+ class Parser
359
+ def initialize(text)
360
+ @scanner = StringScanner.new(text)
361
+ end
362
+
363
+ def parse
364
+ # Each frame: [container, name of the member being read (objects)].
365
+ stack = []
366
+ loop do
367
+ value = read_value(stack)
368
+ next if value.equal?(Parser::OPENED)
369
+
370
+ loop do
371
+ if stack.empty?
372
+ skip_whitespace
373
+ invalid("text after the value") unless @scanner.eos?
374
+ return value
375
+ end
376
+ frame = stack.last
377
+ container = frame[0]
378
+ if container.is_a?(Hash)
379
+ container[frame[1]] = value
380
+ else
381
+ container << value
382
+ end
383
+ skip_whitespace
384
+ if @scanner.skip(/,/)
385
+ frame[1] = read_name if container.is_a?(Hash)
386
+ break
387
+ end
388
+ closing = container.is_a?(Hash) ? /\}/ : /\]/
389
+ invalid("expected , or a closing bracket") unless @scanner.skip(closing)
390
+ stack.pop
391
+ value = container
392
+ end
393
+ end
394
+ end
395
+
396
+ # Marks a container opened: its first member or element is read next.
397
+ OPENED = Object.new.freeze
398
+
399
+ private
400
+
401
+ def read_value(stack)
402
+ skip_whitespace
403
+ if @scanner.skip(/\{/)
404
+ skip_whitespace
405
+ return {} if @scanner.skip(/\}/)
406
+
407
+ stack << [{}, read_name(skip: false)]
408
+ OPENED
409
+ elsif @scanner.skip(/\[/)
410
+ skip_whitespace
411
+ return [] if @scanner.skip(/\]/)
412
+
413
+ stack << [[], nil]
414
+ OPENED
415
+ elsif @scanner.check(/"/)
416
+ read_string
417
+ elsif (number = @scanner.scan(NUMBER))
418
+ Json.double(number)
419
+ elsif @scanner.skip(/true/)
420
+ true
421
+ elsif @scanner.skip(/false/)
422
+ false
423
+ elsif @scanner.skip(/null/)
424
+ nil
425
+ else
426
+ invalid("expected a value")
427
+ end
428
+ end
429
+
430
+ # A member's name and its colon.
431
+ def read_name(skip: true)
432
+ skip_whitespace if skip
433
+ invalid("expected a name") unless @scanner.check(/"/)
434
+ name = read_string
435
+ skip_whitespace
436
+ invalid("expected :") unless @scanner.skip(/:/)
437
+ name
438
+ end
439
+
440
+ def read_string
441
+ invalid("invalid string") unless @scanner.scan(STRING)
442
+ body = @scanner[1]
443
+ body.include?("\\") ? Json.unescape(body) : body
444
+ end
445
+
446
+ def skip_whitespace
447
+ @scanner.skip(WHITESPACE)
448
+ end
449
+
450
+ def invalid(reason)
451
+ raise Invalid, reason
452
+ end
453
+ end
454
+ end
455
+ end
456
+ end
457
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # What an object holding a secret (SPEC.md §27: the integration key, a key derived from it,
7
+ # the merchant's registry key, CoinGecko's key) shows of itself: its `inspect` alone, which
8
+ # leaves the secret out, in `pp` too (whose default shows every member of a Data, every
9
+ # instance variable of an object), and as its JSON (`as_json`, `to_json`: ActiveSupport's
10
+ # default writes every instance variable of an object, every member of a Data, and Rails
11
+ # writes what it logs or renders so); never serialized by Marshal, nor by YAML (Psych), which
12
+ # write its fields otherwise.
13
+ module Redacted
14
+ def pretty_print(printer)
15
+ printer.text(inspect)
16
+ end
17
+
18
+ def as_json(*)
19
+ inspect
20
+ end
21
+
22
+ def to_json(*)
23
+ Json.generate(as_json)
24
+ end
25
+
26
+ def marshal_dump
27
+ raise TypeError, "#{self.class.name} holds a secret: it is never serialized"
28
+ end
29
+
30
+ def _dump(_level)
31
+ raise TypeError, "#{self.class.name} holds a secret: it is never serialized"
32
+ end
33
+
34
+ def encode_with(coder)
35
+ coder.scalar = inspect
36
+ end
37
+ end
38
+
39
+ # Bytes that are a secret (SPEC.md §27): the integration key and the keys derived from it.
40
+ # Never in an inspection, a string, a serialization (Marshal, YAML) nor a message.
41
+ class Secret
42
+ include Redacted
43
+
44
+ def initialize(bytes)
45
+ @bytes = bytes.b.freeze
46
+ freeze
47
+ end
48
+
49
+ # The secret's bytes, for the cryptography that needs them.
50
+ attr_reader :bytes
51
+
52
+ def inspect
53
+ "#<#{self.class.name} [redacted]>"
54
+ end
55
+ alias to_s inspect
56
+ end
57
+
58
+ # What an integration's secret key holds (SPEC.md §8): `sattleme_ck_<team>.<key>.<relays>`,
59
+ # each part in canonical base64url without padding. The key stays on the integrator's server:
60
+ # never in a web page, a repository nor a log.
61
+ class IntegrationKey
62
+ include Redacted
63
+
64
+ # Hex: the team's public key (x only), the author of the integration's channel.
65
+ attr_reader :team_public_key
66
+ # Where its channel was published when the key was given (`wss://` addresses).
67
+ attr_reader :relays
68
+
69
+ # Reads an integration's secret key. Raises InvalidKeyError for anything else: another
70
+ # prefix (a link holding its parts included), a part too many or missing, a part that is
71
+ # not canonical base64url, a length other than 32 bytes, a team key off the curve, an
72
+ # invalid relay list. The message never holds the key.
73
+ def self.parse(value)
74
+ text = Text.caller_text(value)
75
+ raise InvalidKeyError unless text&.start_with?(Protocol::INTEGRATION_KEY_PREFIX)
76
+
77
+ parts = text.delete_prefix(Protocol::INTEGRATION_KEY_PREFIX).split(".", -1)
78
+ raise InvalidKeyError, "Integration key cut short" if parts.size < 3
79
+ raise InvalidKeyError if parts.size > 3
80
+
81
+ team = Base64.decode_url(parts[0])
82
+ key = Base64.decode_url(parts[1])
83
+ relays = Relays.decode_list(parts[2])
84
+ unless team&.bytesize == Protocol::KEY_BYTES && key&.bytesize == Protocol::KEY_BYTES && relays
85
+ raise InvalidKeyError, "Damaged integration key"
86
+ end
87
+ raise InvalidKeyError, "Damaged integration key" unless Secp256k1.xonly?(team)
88
+
89
+ new(Text.hex(team), Secret.new(key), relays)
90
+ end
91
+
92
+ def initialize(team_public_key, key, relays)
93
+ @team_public_key = team_public_key.freeze
94
+ @key = key
95
+ @relays = relays.dup.freeze
96
+ freeze
97
+ end
98
+
99
+ # The integration's key (32 bytes). Never log it.
100
+ def key
101
+ @key.bytes
102
+ end
103
+
104
+ # Its public parts: the team and the relays, never the key.
105
+ def to_h
106
+ { "teamPublicKey" => team_public_key, "relays" => relays }
107
+ end
108
+
109
+ def inspect
110
+ "#<#{self.class.name} team=#{team_public_key} relays=#{relays.inspect}>"
111
+ end
112
+ alias to_s inspect
113
+ end
114
+ end
115
+ end
116
+ end