flex_hold 0.1.0.pre1

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 (115) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +202 -0
  3. data/NOTICE +22 -0
  4. data/README.md +66 -0
  5. data/exe/flexhold +10 -0
  6. data/lib/flex_hold/base58.rb +36 -0
  7. data/lib/flex_hold/binding.rb +175 -0
  8. data/lib/flex_hold/cli.rb +325 -0
  9. data/lib/flex_hold/collector/canonical.rb +22 -0
  10. data/lib/flex_hold/collector/fetcher.rb +58 -0
  11. data/lib/flex_hold/collector/identity_block.rb +110 -0
  12. data/lib/flex_hold/collector/identity_verifier.rb +128 -0
  13. data/lib/flex_hold/collector/mandate_block.rb +131 -0
  14. data/lib/flex_hold/collector/mandate_verifier.rb +114 -0
  15. data/lib/flex_hold/collector/merkle.rb +31 -0
  16. data/lib/flex_hold/collector/record_block.rb +141 -0
  17. data/lib/flex_hold/collector/record_verifier.rb +134 -0
  18. data/lib/flex_hold/collector/sources.rb +116 -0
  19. data/lib/flex_hold/collector.rb +137 -0
  20. data/lib/flex_hold/consent.rb +56 -0
  21. data/lib/flex_hold/consent_log.rb +87 -0
  22. data/lib/flex_hold/eip712.rb +109 -0
  23. data/lib/flex_hold/envelope.rb +113 -0
  24. data/lib/flex_hold/jws.rb +52 -0
  25. data/lib/flex_hold/keys.rb +196 -0
  26. data/lib/flex_hold/mcp_server.rb +296 -0
  27. data/lib/flex_hold/policy/gate-policy-v1.json +1 -0
  28. data/lib/flex_hold/policy.rb +90 -0
  29. data/lib/flex_hold/presenter.rb +101 -0
  30. data/lib/flex_hold/resolvers.rb +56 -0
  31. data/lib/flex_hold/revoker.rb +48 -0
  32. data/lib/flex_hold/secp256k1.rb +115 -0
  33. data/lib/flex_hold/services.rb +231 -0
  34. data/lib/flex_hold/signer.rb +20 -0
  35. data/lib/flex_hold/status_list.rb +115 -0
  36. data/lib/flex_hold/store.rb +224 -0
  37. data/lib/flex_hold/vectors.rb +568 -0
  38. data/lib/flex_hold/verifier.rb +139 -0
  39. data/lib/flex_hold/version.rb +5 -0
  40. data/lib/flex_hold.rb +68 -0
  41. data/vectors/binding-agent-mismatch.json +42 -0
  42. data/vectors/binding-audience-mismatch.json +43 -0
  43. data/vectors/binding-audience-missing.json +42 -0
  44. data/vectors/binding-erc8004-owner-mismatch.json +47 -0
  45. data/vectors/binding-erc8004-registration-unavailable.json +46 -0
  46. data/vectors/binding-erc8004-valid.json +47 -0
  47. data/vectors/binding-expired.json +41 -0
  48. data/vectors/binding-mandate-issuer-mismatch.json +43 -0
  49. data/vectors/binding-mandate-mismatch.json +42 -0
  50. data/vectors/binding-not-yet-valid.json +41 -0
  51. data/vectors/binding-pkh-door-bound.json +43 -0
  52. data/vectors/binding-pkh-erc8004-valid.json +47 -0
  53. data/vectors/binding-pkh-valid.json +41 -0
  54. data/vectors/binding-pkh-wrong-owner.json +41 -0
  55. data/vectors/binding-revoked.json +41 -0
  56. data/vectors/binding-status-unavailable.json +39 -0
  57. data/vectors/binding-status-wrong-issuer.json +41 -0
  58. data/vectors/binding-v1-type.json +45 -0
  59. data/vectors/binding-valid-all-checks.json +46 -0
  60. data/vectors/binding-valid.json +41 -0
  61. data/vectors/binding-wrong-owner.json +41 -0
  62. data/vectors/envelope-example-v1.0.json +458 -0
  63. data/vectors/fixture-flextrust-passport-indicative-v0.1.json +323 -0
  64. data/vectors/fixture-flexyield-mandate-indicative-v0.1.json +187 -0
  65. data/vectors/identity-expired.json +24 -0
  66. data/vectors/identity-issuer-mismatch.json +24 -0
  67. data/vectors/identity-key-compromised.json +24 -0
  68. data/vectors/identity-key-unknown.json +17 -0
  69. data/vectors/identity-keys.json +20 -0
  70. data/vectors/identity-malformed-no-subject-id.json +24 -0
  71. data/vectors/identity-no-status.json +23 -0
  72. data/vectors/identity-not-yet-valid.json +24 -0
  73. data/vectors/identity-owner-mismatch.json +25 -0
  74. data/vectors/identity-revoked.json +24 -0
  75. data/vectors/identity-signature-invalid.json +24 -0
  76. data/vectors/identity-status-list-revoked.json +11 -0
  77. data/vectors/identity-status-list-valid.json +9 -0
  78. data/vectors/identity-status-list-wrong-issuer.json +9 -0
  79. data/vectors/identity-status-unavailable.json +23 -0
  80. data/vectors/identity-status-wrong-issuer.json +24 -0
  81. data/vectors/identity-valid-owner-match.json +25 -0
  82. data/vectors/identity-valid.json +24 -0
  83. data/vectors/keys.json +71 -0
  84. data/vectors/mandate-agent-mismatch.json +24 -0
  85. data/vectors/mandate-claim-overreach.json +23 -0
  86. data/vectors/mandate-expired.json +23 -0
  87. data/vectors/mandate-float-in-subject.json +23 -0
  88. data/vectors/mandate-indicative-as-delivered.json +23 -0
  89. data/vectors/mandate-issuer-mismatch.json +23 -0
  90. data/vectors/mandate-key-compromised.json +23 -0
  91. data/vectors/mandate-key-unknown.json +16 -0
  92. data/vectors/mandate-keys.json +16 -0
  93. data/vectors/mandate-not-yet-valid.json +23 -0
  94. data/vectors/mandate-receipts-inconsistent.json +23 -0
  95. data/vectors/mandate-signature-invalid.json +23 -0
  96. data/vectors/mandate-valid-agent-match.json +24 -0
  97. data/vectors/mandate-valid.json +23 -0
  98. data/vectors/record-digest-mismatch.json +350 -0
  99. data/vectors/record-expired.json +350 -0
  100. data/vectors/record-indicative-valid.json +350 -0
  101. data/vectors/record-key-compromised.json +350 -0
  102. data/vectors/record-key-unknown.json +343 -0
  103. data/vectors/record-merkle-invalid.json +350 -0
  104. data/vectors/record-not-yet-valid.json +350 -0
  105. data/vectors/record-public-tier-unsigned.json +188 -0
  106. data/vectors/record-root-mismatch.json +350 -0
  107. data/vectors/record-root-signature-invalid.json +350 -0
  108. data/vectors/record-root-unavailable.json +344 -0
  109. data/vectors/record-score-mismatch.json +350 -0
  110. data/vectors/record-signature-invalid.json +350 -0
  111. data/vectors/registration-snapshot.json +30 -0
  112. data/vectors/status-list-revoked.json +10 -0
  113. data/vectors/status-list-valid.json +8 -0
  114. data/vectors/status-list-wrong-issuer.json +9 -0
  115. metadata +217 -0
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ module Collector
5
+ # A FlexYield mandate block (mandate-v1): a W3C VC 2.0 credential secured as a compact JWS (EdDSA, typ vc+jwt), parsed once at
6
+ # the boundary. The document a holder keeps is the JWS itself — its bytes are what the owner's binding hashes (binding spec §3
7
+ # rule 5). Shape errors are one Malformed; the verifier never meets a surprise. Rule: the registered claims nbf/exp are the
8
+ # instants checked, and validFrom/validUntil, when present, must name the same instants.
9
+ class MandateBlock
10
+ TYPE = "FlexYieldMandate"
11
+ VERSION = "mandate-v1"
12
+ DID_RE = /\Adid:[a-z0-9]+:[^\s#]+\z/
13
+ KID_RE = /\A(did:[a-z0-9]+:[^\s#]+)#[^\s#]+\z/
14
+ VERDICTS = %w[inside outside no_mandate].freeze
15
+ CAP_INTS = %w[amount_cents per_action_cents spent_cents].freeze
16
+
17
+ attr_reader :jws, :header, :payload, :subject
18
+
19
+ # doc: the compact JWS as a String, or a Hash carrying "jws" (FlexYield's wrapper, a collected block).
20
+ def self.from_document(doc)
21
+ jws = doc.is_a?(Hash) ? doc["jws"] : doc
22
+ raise Malformed, "mandate document must be a compact JWS or an object with a jws" unless jws.is_a?(String) && jws.count(".") == 2
23
+
24
+ header, payload = JWS.decode(jws.strip)
25
+ new(jws.strip, header, payload)
26
+ end
27
+
28
+ def initialize(jws, header, payload)
29
+ @jws, @header, @payload = jws, header, payload
30
+ validate!
31
+ @subject = payload["credentialSubject"]
32
+ end
33
+
34
+ def kid = header["kid"]
35
+ def kid_did = kid[KID_RE, 1]
36
+ def issuer = payload.dig("issuer", "id")
37
+ def iss = payload["iss"]
38
+ def sub = payload["sub"]
39
+ def id = payload["id"]
40
+ def nbf = payload["nbf"]
41
+ def exp = payload["exp"]
42
+ def iat = payload["iat"]
43
+ def agent_key_id = payload.dig("credentialSubject", "agent", "key_id")
44
+ def mandate_hash = "sha256:" + Digest::SHA256.hexdigest(jws)
45
+ def claim = subject.dig("principal", "claim")
46
+ def receipts = subject["receipts"]
47
+ def mandate = subject["mandate"]
48
+
49
+ # What a holder shows about a mandate block — the signed figures, never the receipt samples.
50
+ def summary
51
+ {
52
+ "id" => id, "issuer" => issuer, "version" => payload["version"], "agent" => subject["agent"],
53
+ "principal_account" => subject.dig("principal", "account"),
54
+ "mandate" => { "version" => mandate["version"], "cap" => mandate["cap"], "action_types" => mandate["action_types"], "fences" => mandate["fences"],
55
+ "allowlist_sizes" => mandate["allowlist"].transform_values(&:size), "denylist_sizes" => mandate["denylist"].transform_values(&:size) },
56
+ "receipts" => { "window" => receipts["window"], "count" => receipts["count"], "cost_cents" => receipts["cost_cents"], "verdicts" => receipts["verdicts"] },
57
+ "valid_until" => payload["validUntil"] || Time.at(exp).utc.strftime("%Y-%m-%dT%H:%M:%SZ"), "mandate_hash" => mandate_hash
58
+ }
59
+ end
60
+
61
+ private
62
+
63
+ def validate!
64
+ bad!("header.alg must be EdDSA") unless header["alg"] == JWS::ALG
65
+ bad!("header.typ must be #{JWS::TYP_VC}") unless header["typ"] == JWS::TYP_VC
66
+ bad!("header.kid must be <did>#<fragment>") unless header["kid"].is_a?(String) && header["kid"].match?(KID_RE)
67
+ p = payload
68
+ bad!("payload must be an object") unless p.is_a?(Hash)
69
+ bad!("type must include #{TYPE}") unless p["type"].is_a?(Array) && p["type"].include?(TYPE)
70
+ bad!("version must be #{VERSION}") unless p["version"] == VERSION
71
+ bad!("issuer.id must be a DID") unless p["issuer"].is_a?(Hash) && did?(p["issuer"]["id"])
72
+ bad!("id / jti must be strings") unless str?(p["id"]) && str?(p["jti"])
73
+ bad!("iss must be a DID") unless did?(p["iss"])
74
+ bad!("sub must be a DID") unless did?(p["sub"])
75
+ bad!("nbf and exp must be integers") unless p["nbf"].is_a?(Integer) && p["exp"].is_a?(Integer)
76
+ bad!("iat must be an integer") unless p["iat"].nil? || p["iat"].is_a?(Integer)
77
+ bad!("exp must be after nbf") unless p["exp"] > p["nbf"]
78
+ agree!("validFrom", p["validFrom"], p["nbf"])
79
+ agree!("validUntil", p["validUntil"], p["exp"])
80
+ subject!(p["credentialSubject"], p["sub"])
81
+ end
82
+
83
+ # validFrom must be the same instant as nbf (validUntil as exp): two spellings of one fact, never two facts.
84
+ def agree!(name, string, epoch)
85
+ return if string.nil?
86
+
87
+ bad!("#{name} must be an RFC 3339 timestamp") unless string.is_a?(String)
88
+ t = begin
89
+ Time.iso8601(string).to_i
90
+ rescue ArgumentError
91
+ bad!("#{name} must be an RFC 3339 timestamp")
92
+ end
93
+ bad!("#{name} (#{string}) disagrees with #{name == 'validFrom' ? 'nbf' : 'exp'} (#{epoch})") unless t == epoch
94
+ end
95
+
96
+ def subject!(cs, sub)
97
+ bad!("credentialSubject must be an object with a DID id") unless cs.is_a?(Hash) && did?(cs["id"])
98
+ bad!("credentialSubject.id must equal sub") unless cs["id"] == sub
99
+ bad!("agent.key_id must equal credentialSubject.id") unless cs["agent"].is_a?(Hash) && cs["agent"]["key_id"] == cs["id"]
100
+ pr = cs["principal"]
101
+ bad!("principal must carry account and claim") unless pr.is_a?(Hash) && str?(pr["account"]) && pr["claim"].is_a?(Hash) && str?(pr["claim"]["kind"])
102
+ m = cs["mandate"]
103
+ bad!("mandate must be an object") unless m.is_a?(Hash) && str?(m["version"])
104
+ bad!("mandate.cap must carry currency, period and integer cents") unless m["cap"].is_a?(Hash) && str?(m["cap"]["currency"]) && str?(m["cap"]["period"]) && CAP_INTS.all? { |k| m["cap"][k].is_a?(Integer) && m["cap"][k] >= 0 }
105
+ bad!("mandate.action_types must be strings") unless m["action_types"].is_a?(Array) && m["action_types"].all? { |a| str?(a) }
106
+ %w[allowlist denylist].each { |l| bad!("mandate.#{l} must be an object of lists") unless m[l].is_a?(Hash) && m[l].values.all? { |v| v.is_a?(Array) } }
107
+ bad!("mandate.fences must be an object") unless m["fences"].is_a?(Hash)
108
+ bad!("mandate.keys must be strings") unless m["keys"].is_a?(Array) && m["keys"].all? { |k| str?(k) }
109
+ r = cs["receipts"]
110
+ bad!("receipts must be an object") unless r.is_a?(Hash)
111
+ bad!("receipts.window must carry from and to") unless r["window"].is_a?(Hash) && str?(r["window"]["from"]) && str?(r["window"]["to"])
112
+ bad!("receipts.count / cost_cents must be integers") unless r["count"].is_a?(Integer) && r["cost_cents"].is_a?(Integer)
113
+ bad!("receipts.verdicts must carry integer #{VERDICTS.join(', ')}") unless r["verdicts"].is_a?(Hash) && VERDICTS.all? { |v| r["verdicts"][v].is_a?(Integer) }
114
+ bad!("receipts.sample must be a list of objects") unless r["sample"].is_a?(Array) && r["sample"].all? { |s| s.is_a?(Hash) }
115
+ no_floats!(cs, "credentialSubject")
116
+ end
117
+
118
+ def no_floats!(v, path)
119
+ case v
120
+ when Float then bad!("#{path} is a float — money in cents, counts as integers")
121
+ when Hash then v.each { |k, x| no_floats!(x, "#{path}.#{k}") }
122
+ when Array then v.each_with_index { |x, i| no_floats!(x, "#{path}[#{i}]") }
123
+ end
124
+ end
125
+
126
+ def str?(v) = v.is_a?(String) && !v.strip.empty?
127
+ def did?(v) = v.is_a?(String) && v.match?(DID_RE)
128
+ def bad!(msg) = raise(Malformed, msg)
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ module Collector
5
+ # Verifies a FlexYield mandate block offline: FlexYield's verify steps plus the DISTRIBUTION rule that a claim mandates and never
6
+ # asserts ownership or identity. Every failure one typed reason; the checks hash shows what ran. The only trusted input is the
7
+ # JWK directory the caller supplies (kid → public key with validity).
8
+ # Reasons: :ok, :malformed, :key_unknown, :key_compromised, :signature_invalid, :issuer_mismatch, :not_yet_valid, :expired,
9
+ # :agent_mismatch, :claim_overreach, :receipts_inconsistent
10
+ class MandateVerifier
11
+ CHECKS = %i[key issuer window subject claim receipts].freeze
12
+
13
+ Result = Struct.new(:reason, :block, :checks, keyword_init: true) do
14
+ def ok? = reason == :ok
15
+ def to_h = { "ok" => ok?, "reason" => reason.to_s, "checks" => checks.transform_keys(&:to_s).transform_values(&:to_s), "block" => block&.summary }
16
+ end
17
+
18
+ def initialize(jwk_directory:, now: -> { Time.now }, expected_agent: nil)
19
+ @jwk_directory, @now, @expected_agent = jwk_directory, now, expected_agent
20
+ end
21
+
22
+ def verify(doc)
23
+ checks = CHECKS.to_h { |c| [ c, :skipped ] }
24
+ block = nil
25
+ reason = catch(:fail) do
26
+ block = parse(doc)
27
+ check_key(block, checks)
28
+ check_issuer(block, checks)
29
+ check_window(block, checks)
30
+ check_subject(block, checks)
31
+ check_claim(block, checks)
32
+ check_receipts(block, checks)
33
+ :ok
34
+ end
35
+ Result.new(reason: reason, block: block, checks: checks)
36
+ end
37
+
38
+ private
39
+
40
+ def fail!(reason, checks, check)
41
+ checks[check] = :failed
42
+ throw :fail, reason
43
+ end
44
+
45
+ def parse(doc)
46
+ MandateBlock.from_document(doc)
47
+ rescue Malformed
48
+ throw :fail, :malformed
49
+ end
50
+
51
+ # 1 · kid is a directory key valid at issuance, and the Ed25519 signature verifies with it
52
+ def check_key(block, checks)
53
+ entry = @jwk_directory.call(block.kid)
54
+ fail!(:key_unknown, checks, :key) if entry.nil?
55
+ at = block.iat || block.nbf
56
+ begin
57
+ fail!(:key_unknown, checks, :key) if entry["valid_from"] && at < Sources.time(entry["valid_from"]).to_i
58
+ fail!(:key_unknown, checks, :key) if entry["retired_at"] && Sources.time(entry["retired_at"]).to_i <= at
59
+ fail!(:key_compromised, checks, :key) if entry["compromised_at"] && Sources.time(entry["compromised_at"]).to_i <= at
60
+ key = Keys::Ed25519.from_public_bytes(JWS.b64url_decode(entry["x"].to_s))
61
+ rescue Malformed, ArgumentError
62
+ fail!(:key_unknown, checks, :key)
63
+ end
64
+ begin
65
+ JWS.verify(block.jws, key)
66
+ rescue SignatureInvalid, Malformed
67
+ fail!(:signature_invalid, checks, :key)
68
+ end
69
+ checks[:key] = :passed
70
+ end
71
+
72
+ # 2 · iss == issuer.id == the DID the kid belongs to
73
+ def check_issuer(block, checks)
74
+ fail!(:issuer_mismatch, checks, :issuer) unless block.iss == block.issuer && block.issuer == block.kid_did
75
+ checks[:issuer] = :passed
76
+ end
77
+
78
+ # 3 · nbf ≤ now < exp
79
+ def check_window(block, checks)
80
+ now = @now.call.to_i
81
+ fail!(:not_yet_valid, checks, :window) if now < block.nbf
82
+ fail!(:expired, checks, :window) unless now < block.exp
83
+ checks[:window] = :passed
84
+ end
85
+
86
+ # 4 · the subject is the agent key the caller's binding names (shape equality sub == id == agent.key_id is the parser's)
87
+ def check_subject(block, checks)
88
+ fail!(:agent_mismatch, checks, :subject) if @expected_agent && block.agent_key_id != @expected_agent
89
+ checks[:subject] = :passed
90
+ end
91
+
92
+ # 5 · DISTRIBUTION v1.2: a claim at FlexYield mandates — it never asserts ownership or identity
93
+ def check_claim(block, checks)
94
+ c = block.claim
95
+ fail!(:claim_overreach, checks, :claim) unless c["kind"] == "mandate" && c["asserts_ownership"] == false && c["asserts_identity"] == false
96
+ checks[:claim] = :passed
97
+ end
98
+
99
+ # 6 · the receipt figures add up and the window runs forward
100
+ def check_receipts(block, checks)
101
+ r = block.receipts
102
+ fail!(:receipts_inconsistent, checks, :receipts) unless r["verdicts"].values_at(*MandateBlock::VERDICTS).sum == r["count"]
103
+ from, to = begin
104
+ [ Time.iso8601(r["window"]["from"]), Time.iso8601(r["window"]["to"]) ]
105
+ rescue ArgumentError
106
+ fail!(:receipts_inconsistent, checks, :receipts)
107
+ end
108
+ fail!(:receipts_inconsistent, checks, :receipts) unless from < to
109
+ fail!(:receipts_inconsistent, checks, :receipts) unless r["sample"].all? { |s| MandateBlock::VERDICTS.include?(s["verdict"]) && s["cost_cents"].is_a?(Integer) }
110
+ checks[:receipts] = :passed
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ module Collector
5
+ # FlexTrust's daily commitment tree (pinned 2026-10-27 against the indicative fixture):
6
+ # leaf = sha256("agent_id|value|computed_at_unix|salt"); pairing = sha256(left + right) over the concatenated
7
+ # lowercase HEX STRINGS (not the raw bytes); an odd node pairs with itself; bit i of the position says whether the
8
+ # node is the right child (1) or the left child (0) at level i.
9
+ module Merkle
10
+ HEX64 = /\A[0-9a-f]{64}\z/
11
+
12
+ module_function
13
+
14
+ def leaf_hex(agent_id:, value:, computed_at:, salt:) = Digest::SHA256.hexdigest("#{agent_id}|#{value}|#{computed_at}|#{salt}")
15
+
16
+ def fold_hex(leaf_hex, position, siblings)
17
+ raise Malformed, "leaf must be a sha256 hex string" unless leaf_hex.is_a?(String) && leaf_hex.match?(HEX64)
18
+ raise Malformed, "position must be a non-negative integer" unless position.is_a?(Integer) && position >= 0
19
+ raise Malformed, "siblings must be sha256 hex strings" unless siblings.is_a?(Array) && siblings.all? { |s| s.is_a?(String) && s.match?(HEX64) }
20
+
21
+ node = leaf_hex
22
+ pos = position
23
+ siblings.each do |sibling|
24
+ node = Digest::SHA256.hexdigest(pos.odd? ? sibling + node : node + sibling)
25
+ pos >>= 1
26
+ end
27
+ node
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ module Collector
5
+ # A FlexTrust agent passport (passport-v1) parsed once at the boundary. Shape errors are one Malformed here, so the
6
+ # verifier never meets a surprise. The public tier carries no statement (signed? false); the full tier carries the
7
+ # EIP-712 PassportStatement, the Merkle inclusion proof and the signed day root.
8
+ class RecordBlock
9
+ TYPE = "FlexTrustAgentPassport"
10
+ VERSION = "passport-v1"
11
+ TIERS = %w[public full].freeze
12
+ HEX64 = /\A(0x)?[0-9a-fA-F]{64}\z/
13
+ HEX_SIG = /\A0x[0-9a-fA-F]{130}\z/
14
+ DATE = /\A\d{4}-\d{2}-\d{2}\z/
15
+ MESSAGE_INTS = %w[subjectId score confidenceBps riskDerived leafPosition asOfBlock issuedAt validUntil].freeze
16
+ MESSAGE_BYTES32 = %w[documentDigest commitmentRoot].freeze
17
+ MESSAGE_STRINGS = %w[subject tier methodologyVersion commitmentDay ownerAddress keyId].freeze
18
+ MESSAGE_FIELDS = (MESSAGE_INTS + MESSAGE_BYTES32 + MESSAGE_STRINGS).freeze
19
+ PRIMARY_TYPE = "PassportStatement"
20
+ SUPPORTED_EIP712_TYPES = /\A(string|bytes|bytes32|address|bool|uint\d+)\z/
21
+
22
+ attr_reader :raw, :id, :issuer, :tier, :subject, :statement, :eip712_domain, :eip712_types
23
+
24
+ def self.from_h(h)
25
+ raise Malformed, "record must be an object" unless h.is_a?(Hash)
26
+ raise Malformed, "type must include #{TYPE}" unless h["type"].is_a?(Array) && h["type"].include?(TYPE)
27
+ raise Malformed, "version must be #{VERSION}" unless h["version"] == VERSION
28
+ raise Malformed, "tier must be one of #{TIERS.join(', ')}" unless TIERS.include?(h["tier"])
29
+ raise Malformed, "issuer must be an object with an id" unless h["issuer"].is_a?(Hash) && string?(h["issuer"]["id"])
30
+ raise Malformed, "id must be a string" unless string?(h["id"])
31
+ raise Malformed, "validFrom / validUntil must be timestamps" unless time?(h["validFrom"]) && time?(h["validUntil"])
32
+
33
+ cs = h["credentialSubject"]
34
+ raise Malformed, "credentialSubject must be an object with an id" unless cs.is_a?(Hash) && string?(cs["id"])
35
+ raise Malformed, "credentialSubject.score.value must be an integer" unless cs["score"].is_a?(Hash) && cs["score"]["value"].is_a?(Integer)
36
+
37
+ statement = h["statement"].nil? ? nil : statement!(h["statement"])
38
+ domain = types = nil
39
+ if statement
40
+ e = h.dig("proof", "eip712")
41
+ raise Malformed, "proof.eip712 must carry domain and types for a signed record" unless e.is_a?(Hash)
42
+ domain, types = eip712!(e)
43
+ end
44
+ new(raw: h, statement: statement, eip712_domain: domain, eip712_types: types)
45
+ end
46
+
47
+ def initialize(raw:, statement:, eip712_domain:, eip712_types:)
48
+ @raw, @statement, @eip712_domain, @eip712_types = raw, statement, eip712_domain, eip712_types
49
+ @id, @issuer, @tier, @subject = raw["id"], raw["issuer"]["id"], raw["tier"], raw["credentialSubject"]
50
+ end
51
+
52
+ def signed? = !@statement.nil?
53
+ def public? = tier == "public"
54
+ def subject_id = subject["id"]
55
+ def score_value = subject.dig("score", "value")
56
+ def bound = subject["bound"]
57
+ def binding_status_url = subject["binding_status_url"]
58
+ def owner_address = subject.dig("control_continuity", "owner_address")
59
+
60
+ def message = statement["message"]
61
+ def key_id = statement["key_id"]
62
+ def signature_bytes = RecordBlock.hex_bytes(statement["signature"])
63
+ def committed_score = statement.dig("committed_score", "value")
64
+ def merkle = statement["proof"]
65
+ def root_signature = statement["root_signature"]
66
+ def root_signature_bytes = RecordBlock.hex_bytes(root_signature["value"])
67
+
68
+ # The signed message with bytes32 fields as 32 raw bytes, as the EIP-712 encoder expects.
69
+ def eip712_message = message.to_h { |k, v| [ k, MESSAGE_BYTES32.include?(k) ? RecordBlock.hex_bytes(v) : v ] }
70
+
71
+ # What a holder shows about a record block — nothing beyond the public fields of the document itself.
72
+ def summary
73
+ score = subject["score"]
74
+ {
75
+ "id" => id, "issuer" => issuer, "tier" => tier, "agent" => subject["agent"],
76
+ "score" => { "value" => score["value"], "scale" => score["scale"], "band" => score["band"], "computed_at" => score["computed_at"] },
77
+ "bound" => bound, "binding_status_url" => binding_status_url, "owner_address" => owner_address, "valid_until" => raw["validUntil"]
78
+ }
79
+ end
80
+
81
+ def to_h = raw
82
+
83
+ class << self
84
+ def hex_bytes(hex) = [ hex.to_s.delete_prefix("0x") ].pack("H*")
85
+ def hex_norm(hex) = hex.to_s.delete_prefix("0x").downcase
86
+
87
+ private
88
+
89
+ def string?(v) = v.is_a?(String) && !v.strip.empty?
90
+ def time?(v) = v.is_a?(String) && v.match?(/\A\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2}))?\z/)
91
+ def hex64?(v) = v.is_a?(String) && v.match?(HEX64)
92
+
93
+ def statement!(s)
94
+ raise Malformed, "statement must be an object" unless s.is_a?(Hash)
95
+ m = s["message"]
96
+ raise Malformed, "statement.message must be an object" unless m.is_a?(Hash)
97
+ missing = MESSAGE_FIELDS - m.keys
98
+ raise Malformed, "statement.message lacks #{missing.join(', ')}" unless missing.empty?
99
+ MESSAGE_INTS.each { |k| raise Malformed, "statement.message.#{k} must be a non-negative integer" unless m[k].is_a?(Integer) && m[k] >= 0 }
100
+ MESSAGE_BYTES32.each { |k| raise Malformed, "statement.message.#{k} must be 32 bytes hex" unless hex64?(m[k]) }
101
+ MESSAGE_STRINGS.each { |k| raise Malformed, "statement.message.#{k} must be a string" unless m[k].is_a?(String) }
102
+ raise Malformed, "statement.signature must be 65 bytes hex" unless s["signature"].is_a?(String) && s["signature"].match?(HEX_SIG)
103
+ raise Malformed, "statement.key_id must be a string" unless string?(s["key_id"])
104
+ raise Malformed, "statement.key_id must equal message.keyId" unless s["key_id"] == m["keyId"]
105
+ raise Malformed, "statement.committed_score.value must be an integer" unless s["committed_score"].is_a?(Hash) && s["committed_score"]["value"].is_a?(Integer)
106
+ proof!(s["proof"])
107
+ rs = s["root_signature"]
108
+ raise Malformed, "statement.root_signature must carry key_id, signed_at and a 65-byte value" unless rs.is_a?(Hash) && string?(rs["key_id"]) && time?(rs["signed_at"]) && rs["value"].is_a?(String) && rs["value"].match?(HEX_SIG)
109
+ s
110
+ end
111
+
112
+ def proof!(p)
113
+ raise Malformed, "statement.proof must be an object" unless p.is_a?(Hash)
114
+ l = p["leaf"]
115
+ raise Malformed, "statement.proof.leaf must carry agent_id, value, computed_at (integers) and salt" unless l.is_a?(Hash) && %w[agent_id value computed_at].all? { |k| l[k].is_a?(Integer) } && string?(l["salt"])
116
+ raise Malformed, "statement.proof.position must be a non-negative integer" unless p["position"].is_a?(Integer) && p["position"] >= 0
117
+ raise Malformed, "statement.proof.siblings must be sha256 hex strings" unless p["siblings"].is_a?(Array) && p["siblings"].all? { |x| hex64?(x) }
118
+ raise Malformed, "statement.proof.root must be a sha256 hex string" unless hex64?(p["root"])
119
+ raise Malformed, "statement.proof.committed_on must be a date" unless p["committed_on"].is_a?(String) && p["committed_on"].match?(DATE)
120
+ end
121
+
122
+ # EIP-712 types arrive as [{name, type}] objects (the wallet convention); our encoder takes [name, type] pairs.
123
+ def eip712!(e)
124
+ d = e["domain"]
125
+ raise Malformed, "eip712.domain must carry name, version and an integer chainId" unless d.is_a?(Hash) && string?(d["name"]) && string?(d["version"]) && d["chainId"].is_a?(Integer)
126
+ t = e["types"]
127
+ raise Malformed, "eip712.types must define EIP712Domain and #{PRIMARY_TYPE}" unless t.is_a?(Hash) && t["EIP712Domain"].is_a?(Array) && t[PRIMARY_TYPE].is_a?(Array)
128
+ types = t.to_h do |name, fields|
129
+ raise Malformed, "eip712.types.#{name} must be a list of {name, type}" unless fields.is_a?(Array)
130
+ [ name, fields.map do |f|
131
+ raise Malformed, "eip712.types.#{name}: unsupported field #{f.inspect}" unless f.is_a?(Hash) && string?(f["name"]) && f["type"].is_a?(String) && f["type"].match?(SUPPORTED_EIP712_TYPES)
132
+ [ f["name"], f["type"] ]
133
+ end ]
134
+ end
135
+ raise Malformed, "eip712.types.#{PRIMARY_TYPE} must name exactly the message fields" unless types[PRIMARY_TYPE].map(&:first).sort == MESSAGE_FIELDS.sort
136
+ [ d.slice("name", "version", "chainId"), types ]
137
+ end
138
+ end
139
+ end
140
+ end
141
+ end
@@ -0,0 +1,134 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ module Collector
5
+ # Verifies a FlexTrust record block offline — FlexTrust's six checks (spec /spec/passport) in their order, every failure
6
+ # one typed reason, the checks hash shows what ran. Sources are injected: a key directory (key_id → address, validity)
7
+ # and the daily commitments (day → root, leaf count); nothing is trusted that the caller did not supply.
8
+ # Reasons: :ok, :malformed, :unsigned, :not_yet_valid, :expired, :key_unknown, :key_compromised, :signature_invalid,
9
+ # :digest_mismatch, :merkle_invalid, :root_unavailable, :root_mismatch, :root_signature_invalid, :score_mismatch
10
+ class RecordVerifier
11
+ CHECKS = %i[window key digest merkle root freshness].freeze
12
+ COMMITMENT_ROOT_TYPE = "CommitmentRoot"
13
+ COMMITMENT_ROOT_FIELDS = [ %w[day string], %w[merkleRoot bytes32], %w[leafCount uint32], %w[methodologyVersion string],
14
+ %w[signedAt uint64], %w[keyId string] ].freeze
15
+
16
+ Result = Struct.new(:reason, :block, :checks, keyword_init: true) do
17
+ def ok? = reason == :ok
18
+ def to_h = { "ok" => ok?, "reason" => reason.to_s, "checks" => checks.transform_keys(&:to_s).transform_values(&:to_s), "block" => block&.summary }
19
+ end
20
+
21
+ def initialize(key_directory:, commitments:, now: -> { Time.now })
22
+ @key_directory, @commitments, @now = key_directory, commitments, now
23
+ end
24
+
25
+ def verify(raw)
26
+ checks = CHECKS.to_h { |c| [ c, :skipped ] }
27
+ block = nil
28
+ reason = catch(:fail) do
29
+ block = parse(raw)
30
+ throw :fail, :unsigned unless block.signed?
31
+ check_window(block, checks)
32
+ check_key(block, checks)
33
+ check_digest(block, checks)
34
+ check_merkle(block, checks)
35
+ check_root(block, checks)
36
+ check_freshness(block, checks)
37
+ :ok
38
+ end
39
+ Result.new(reason: reason, block: block, checks: checks)
40
+ end
41
+
42
+ private
43
+
44
+ def fail!(reason, checks, check)
45
+ checks[check] = :failed
46
+ throw :fail, reason
47
+ end
48
+
49
+ def parse(raw)
50
+ RecordBlock.from_h(raw)
51
+ rescue Malformed
52
+ throw :fail, :malformed
53
+ end
54
+
55
+ # 1 · issuedAt ≤ now < validUntil
56
+ def check_window(block, checks)
57
+ now = @now.call.to_i
58
+ fail!(:not_yet_valid, checks, :window) if now < block.message["issuedAt"]
59
+ fail!(:expired, checks, :window) unless now < block.message["validUntil"]
60
+ checks[:window] = :passed
61
+ end
62
+
63
+ # 2 · the statement signer is a published key with the stated keyId, valid and not compromised at issuance
64
+ def check_key(block, checks)
65
+ expected = trusted_address(block.key_id, at: block.message["issuedAt"], checks: checks, check: :key)
66
+ recovered = recover(block.eip712_domain, RecordBlock::PRIMARY_TYPE, block.eip712_message, block.eip712_types, block.signature_bytes, checks, :key, :signature_invalid)
67
+ fail!(:signature_invalid, checks, :key) unless recovered == expected
68
+ checks[:key] = :passed
69
+ end
70
+
71
+ # 3 · canonical credentialSubject hashes to documentDigest
72
+ def check_digest(block, checks)
73
+ fail!(:digest_mismatch, checks, :digest) unless Canonical.sha256_hex(block.subject) == RecordBlock.hex_norm(block.message["documentDigest"])
74
+ checks[:digest] = :passed
75
+ end
76
+
77
+ # 4 · the leaf folds to commitmentRoot at leafPosition, and the proof speaks of the signed day and position
78
+ def check_merkle(block, checks)
79
+ pr, m = block.merkle, block.message
80
+ root = RecordBlock.hex_norm(m["commitmentRoot"])
81
+ fail!(:merkle_invalid, checks, :merkle) unless pr["position"] == m["leafPosition"] && pr["committed_on"] == m["commitmentDay"] && RecordBlock.hex_norm(pr["root"]) == root
82
+ l = pr["leaf"]
83
+ leaf = Merkle.leaf_hex(agent_id: l["agent_id"], value: l["value"], computed_at: l["computed_at"], salt: l["salt"])
84
+ folded = begin
85
+ Merkle.fold_hex(leaf, pr["position"], pr["siblings"].map { |s| RecordBlock.hex_norm(s) })
86
+ rescue Malformed
87
+ fail!(:merkle_invalid, checks, :merkle)
88
+ end
89
+ fail!(:merkle_invalid, checks, :merkle) unless folded == root
90
+ checks[:merkle] = :passed
91
+ end
92
+
93
+ # 5 · commitmentRoot is the published root for commitmentDay, and the day root's own signature is a published key's
94
+ def check_root(block, checks)
95
+ m, rs = block.message, block.root_signature
96
+ entry = @commitments.call(m["commitmentDay"])
97
+ fail!(:root_unavailable, checks, :root) if entry.nil?
98
+ fail!(:root_mismatch, checks, :root) unless RecordBlock.hex_norm(entry["merkle_root"]) == RecordBlock.hex_norm(m["commitmentRoot"])
99
+ signed_at = Time.iso8601(rs["signed_at"]).to_i
100
+ expected = trusted_address(rs["key_id"], at: signed_at, checks: checks, check: :root)
101
+ message = { "day" => m["commitmentDay"], "merkleRoot" => RecordBlock.hex_bytes(m["commitmentRoot"]), "leafCount" => entry["leaf_count"],
102
+ "methodologyVersion" => entry["methodology_version"] || m["methodologyVersion"], "signedAt" => signed_at, "keyId" => rs["key_id"] }
103
+ types = block.eip712_types.slice("EIP712Domain").merge(COMMITMENT_ROOT_TYPE => COMMITMENT_ROOT_FIELDS)
104
+ recovered = recover(block.eip712_domain, COMMITMENT_ROOT_TYPE, message, types, block.root_signature_bytes, checks, :root, :root_signature_invalid)
105
+ fail!(:root_signature_invalid, checks, :root) unless recovered == expected
106
+ checks[:root] = :passed
107
+ end
108
+
109
+ # 6 · the committed score in the statement equals the signed score
110
+ def check_freshness(block, checks)
111
+ fail!(:score_mismatch, checks, :freshness) unless block.committed_score == block.message["score"]
112
+ checks[:freshness] = :passed
113
+ end
114
+
115
+ # Directory lookup: unknown, not yet valid or retired at `at` → :key_unknown; compromised at or before `at` → :key_compromised.
116
+ def trusted_address(key_id, at:, checks:, check:)
117
+ entry = @key_directory.call(key_id)
118
+ fail!(:key_unknown, checks, check) if entry.nil?
119
+ fail!(:key_unknown, checks, check) if entry["valid_from"] && at < Sources.time(entry["valid_from"]).to_i
120
+ fail!(:key_unknown, checks, check) if entry["retired_at"] && Sources.time(entry["retired_at"]).to_i <= at
121
+ fail!(:key_compromised, checks, check) if entry["compromised_at"] && Sources.time(entry["compromised_at"]).to_i <= at
122
+ Secp256k1.checksum(entry["address"])
123
+ rescue Malformed
124
+ fail!(:key_unknown, checks, check)
125
+ end
126
+
127
+ def recover(domain, primary, message, types, signature, checks, check, reason)
128
+ Secp256k1.recover_address(EIP712.digest(domain, primary, message, types), signature)
129
+ rescue SignatureInvalid, Malformed
130
+ fail!(reason, checks, check)
131
+ end
132
+ end
133
+ end
134
+ end