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,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ module Collector
5
+ # The injectable sources a record verifier trusts: a key directory (issuer keys with validity) and the daily commitments.
6
+ # Each comes from a static map (tests, vectors), a local file or an https URL — never from the block being verified.
7
+ module Sources
8
+ DATE = /\A\d{4}-\d{2}-\d{2}\z/
9
+
10
+ # "2026-09-04" (a day, UTC midnight) or an RFC 3339 timestamp → Time
11
+ def self.time(v)
12
+ raise Malformed, "not a timestamp" unless v.is_a?(String)
13
+
14
+ v.match?(DATE) ? Time.utc(*v.split("-").map(&:to_i)) : Time.iso8601(v)
15
+ rescue ArgumentError
16
+ raise Malformed, "not a timestamp"
17
+ end
18
+
19
+ # file path or https URL → parsed JSON; nil → nil (the caller falls back to an empty source)
20
+ def self.document(ref, fetcher:)
21
+ return nil if ref.nil?
22
+ return fetcher.call(ref) if ref.to_s.start_with?("https://")
23
+
24
+ JSON.parse(File.read(ref))
25
+ rescue SystemCallError, JSON::ParserError
26
+ raise Malformed, "#{ref} not readable as JSON"
27
+ end
28
+ end
29
+
30
+ # FlexTrust's /.well-known/flextrust → attestation_keys[]: {key_id, address, valid_from, retired_at, compromised_at}
31
+ module KeyDirectory
32
+ class Static
33
+ def initialize(map) = @map = map
34
+ def call(key_id) = @map[key_id]
35
+ end
36
+
37
+ def self.from_document(doc)
38
+ keys = doc.is_a?(Hash) ? doc["attestation_keys"] : nil
39
+ raise Malformed, "attestation_keys must be a list" unless keys.is_a?(Array)
40
+
41
+ Static.new(keys.to_h do |k|
42
+ raise Malformed, "attestation key must carry key_id and an EVM address" unless k.is_a?(Hash) && k["key_id"].is_a?(String) && k["address"].is_a?(String) && k["address"].match?(/\A0x[0-9a-fA-F]{40}\z/)
43
+ %w[valid_from retired_at compromised_at].each { |f| Sources.time(k[f]) unless k[f].nil? }
44
+ [ k["key_id"], k.slice("address", "valid_from", "retired_at", "compromised_at") ]
45
+ end)
46
+ end
47
+
48
+ def self.load(ref, fetcher:)
49
+ doc = Sources.document(ref, fetcher: fetcher)
50
+ doc.nil? ? Static.new({}) : from_document(doc)
51
+ end
52
+ end
53
+
54
+ # A JWK Set (RFC 7517) with validity — the shape FlexHold reads for an issuer's signing keys (FlexYield's /.well-known/flexyield,
55
+ # reserved): keys[]: {kid, kty "OKP", crv "Ed25519", x, valid_from, retired_at, compromised_at}. Ed25519 only in v1.
56
+ module JwkDirectory
57
+ class Static
58
+ def initialize(map) = @map = map
59
+ def call(kid) = @map[kid]
60
+ end
61
+
62
+ def self.from_document(doc)
63
+ keys = doc.is_a?(Hash) ? doc["keys"] : nil
64
+ raise Malformed, "keys must be a list (JWK Set)" unless keys.is_a?(Array)
65
+
66
+ Static.new(keys.to_h do |k|
67
+ raise Malformed, "each key must carry kid and an Ed25519 OKP jwk (kty, crv, x)" unless k.is_a?(Hash) && k["kid"].is_a?(String) && k["kty"] == "OKP" && k["crv"] == "Ed25519" && k["x"].is_a?(String)
68
+ %w[valid_from retired_at compromised_at].each { |f| Sources.time(k[f]) unless k[f].nil? }
69
+ [ k["kid"], k.slice("x", "valid_from", "retired_at", "compromised_at") ]
70
+ end)
71
+ end
72
+
73
+ def self.load(ref, fetcher:)
74
+ doc = Sources.document(ref, fetcher: fetcher)
75
+ doc.nil? ? Static.new({}) : from_document(doc)
76
+ end
77
+
78
+ # The key a kid names, as of an instant: [:ok, Ed25519 public key] | [:key_unknown] | [:key_compromised]. Shared by the
79
+ # verifiers that read a JWK Set with validity (H2.2 mandate, H2.3 identity + its status list).
80
+ def self.key_at(directory, kid, at:)
81
+ entry = directory.call(kid)
82
+ return [ :key_unknown ] if entry.nil? || !at.is_a?(Integer)
83
+ return [ :key_unknown ] if entry["valid_from"] && at < Sources.time(entry["valid_from"]).to_i
84
+ return [ :key_unknown ] if entry["retired_at"] && Sources.time(entry["retired_at"]).to_i <= at
85
+ return [ :key_compromised ] if entry["compromised_at"] && Sources.time(entry["compromised_at"]).to_i <= at
86
+
87
+ [ :ok, Keys::Ed25519.from_public_bytes(JWS.b64url_decode(entry["x"].to_s)) ]
88
+ rescue Malformed, ArgumentError
89
+ [ :key_unknown ]
90
+ end
91
+ end
92
+
93
+ # FlexTrust's /commitments.json → commitments[]: {day, merkle_root, leaf_count, methodology_version, signature}
94
+ module Commitments
95
+ class Static
96
+ def initialize(map) = @map = map
97
+ def call(day) = @map[day]
98
+ end
99
+
100
+ def self.from_document(doc)
101
+ list = doc.is_a?(Hash) ? doc["commitments"] : nil
102
+ raise Malformed, "commitments must be a list" unless list.is_a?(Array)
103
+
104
+ Static.new(list.to_h do |c|
105
+ raise Malformed, "commitment must carry day, merkle_root and leaf_count" unless c.is_a?(Hash) && c["day"].is_a?(String) && c["merkle_root"].is_a?(String) && c["merkle_root"].match?(/\A(0x)?[0-9a-fA-F]{64}\z/) && c["leaf_count"].is_a?(Integer) && c["leaf_count"] >= 0
106
+ [ c["day"], c.slice("merkle_root", "leaf_count", "methodology_version") ]
107
+ end)
108
+ end
109
+
110
+ def self.load(ref, fetcher:)
111
+ doc = Sources.document(ref, fetcher: fetcher)
112
+ doc.nil? ? Static.new({}) : from_document(doc)
113
+ end
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "collector/canonical"
4
+ require_relative "collector/merkle"
5
+ require_relative "collector/record_block"
6
+ require_relative "collector/mandate_block"
7
+ require_relative "collector/identity_block"
8
+ require_relative "collector/sources"
9
+ require_relative "collector/fetcher"
10
+ require_relative "collector/record_verifier"
11
+ require_relative "collector/mandate_verifier"
12
+ require_relative "collector/identity_verifier"
13
+
14
+ module FlexHold
15
+ # H2: the collector fetches signed blocks from issuers and verifies them. One shape for every source: fetch(ref) → raw
16
+ # document, verify(raw) → typed verdict; a collected block keeps the document exactly as fetched next to its verdict.
17
+ # Sources: FlexTrust record block (H2.1), FlexYield mandate block (H2.2), an owner-identity credential from any issuer (H2.3).
18
+ module Collector
19
+ def self.collect(source:, ref:, key_directory:, commitments: nil, fetcher: Fetcher::HTTPS.new, now: -> { Time.now }, expected_agent: nil,
20
+ expected_owner: nil, status_resolver: nil)
21
+ src = Sources.for(source)
22
+ raw, location = src.fetch(ref, fetcher: fetcher)
23
+ result = src.verifier(key_directory: key_directory, commitments: commitments, now: now, expected_agent: expected_agent,
24
+ expected_owner: expected_owner, status_resolver: status_resolver).verify(raw)
25
+ {
26
+ "source" => src::NAME, "ref" => location, "collected_at" => now.call.utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
27
+ "verification" => result.to_h, "block" => raw
28
+ }
29
+ end
30
+
31
+ module Sources
32
+ def self.for(name)
33
+ case name
34
+ when FlexTrustRecord::NAME then FlexTrustRecord
35
+ when FlexYieldMandate::NAME then FlexYieldMandate
36
+ when Identity::NAME then Identity
37
+ else raise Malformed, "unknown source #{name.inspect} (known: #{FlexTrustRecord::NAME}, #{FlexYieldMandate::NAME}, #{Identity::NAME})"
38
+ end
39
+ end
40
+
41
+ # Shared: an https URL must sit on the issuer's host; a file is read as JSON (or, when the source allows, as text).
42
+ def self.host!(ref, host)
43
+ raise Malformed, "not a #{host} URL" unless URI.parse(ref).host == host
44
+ rescue URI::InvalidURIError
45
+ raise Malformed, "not a URL"
46
+ end
47
+
48
+ def self.file!(ref)
49
+ raise Malformed, "not readable: #{ref}" unless File.file?(ref)
50
+
51
+ File.read(ref)
52
+ rescue SystemCallError
53
+ raise Malformed, "not readable: #{ref}"
54
+ end
55
+
56
+ # The FlexTrust record block (C1 agent passport). ref = agent id (→ the public passport document, zero cost),
57
+ # a passport URL on flextrust.io, or a local file (fixtures, a full-tier document the owner fetched herself).
58
+ module FlexTrustRecord
59
+ NAME = "flextrust"
60
+ HOST = "flextrust.io"
61
+ KEYS_URL = "https://#{HOST}/.well-known/flextrust"
62
+ COMMITMENTS_URL = "https://#{HOST}/commitments.json"
63
+
64
+ def self.remote?(ref) = ref.to_s.match?(/\A\d+\z/) || ref.to_s.start_with?("https://")
65
+
66
+ def self.fetch(ref, fetcher:)
67
+ ref = ref.to_s
68
+ if ref.match?(/\A\d+\z/)
69
+ url = "https://#{HOST}/agents/#{ref}/passport.json"
70
+ [ fetcher.call(url), url ]
71
+ elsif ref.start_with?("https://")
72
+ Sources.host!(ref, HOST)
73
+ [ fetcher.call(ref), ref ]
74
+ else
75
+ [ JSON.parse(Sources.file!(ref)), ref ]
76
+ end
77
+ rescue JSON::ParserError
78
+ raise Malformed, "record not readable as JSON"
79
+ end
80
+
81
+ def self.verifier(key_directory:, commitments:, now:, **) = RecordVerifier.new(key_directory: key_directory, commitments: commitments, now: now)
82
+ end
83
+
84
+ # The FlexYield mandate block (#9 export_mandate, mandate-v1 as a compact JWS). ref = a flexyield.io URL (the owner's
85
+ # mandate export; FlexYield's API is not live for this yet) or a local file — FlexYield's JSON wrapper {jws, …} or the bare JWS.
86
+ # key_directory here is a JwkDirectory (kid → Ed25519 public key with validity).
87
+ module FlexYieldMandate
88
+ NAME = "flexyield"
89
+ HOST = "flexyield.io"
90
+ KEYS_URL = "https://#{HOST}/.well-known/flexyield" # reserved by FlexYield, not live (2026-10-27)
91
+
92
+ def self.remote?(ref) = ref.to_s.start_with?("https://")
93
+
94
+ def self.fetch(ref, fetcher:)
95
+ ref = ref.to_s
96
+ if ref.start_with?("https://")
97
+ Sources.host!(ref, HOST)
98
+ [ fetcher.call(ref), ref ]
99
+ else
100
+ text = Sources.file!(ref).strip
101
+ doc = text.start_with?("{") ? JSON.parse(text) : { "jws" => text }
102
+ [ doc, ref ]
103
+ end
104
+ rescue JSON::ParserError
105
+ raise Malformed, "mandate not readable as JSON or a compact JWS"
106
+ end
107
+
108
+ def self.verifier(key_directory:, now:, expected_agent: nil, **) = MandateVerifier.new(jwk_directory: key_directory, now: now, expected_agent: expected_agent)
109
+ end
110
+
111
+ # H2.3 · an owner-identity credential (jwt_vc_json) from ANY issuer: ref = an https URL (any host — the issuer is a third party;
112
+ # the document is the issuer's JSON wrapper {jws, …}) or a local file (wrapper or bare JWS). key_directory = the issuer's JWK Set.
113
+ module Identity
114
+ NAME = "identity"
115
+
116
+ def self.remote?(ref) = ref.to_s.start_with?("https://")
117
+
118
+ def self.fetch(ref, fetcher:)
119
+ ref = ref.to_s
120
+ if ref.start_with?("https://")
121
+ [ fetcher.call(ref), ref ]
122
+ else
123
+ text = Sources.file!(ref).strip
124
+ doc = text.start_with?("{") ? JSON.parse(text) : { "jws" => text }
125
+ [ doc, ref ]
126
+ end
127
+ rescue JSON::ParserError
128
+ raise Malformed, "identity credential not readable as JSON or a compact JWS"
129
+ end
130
+
131
+ def self.verifier(key_directory:, now:, expected_owner: nil, status_resolver: nil, **)
132
+ IdentityVerifier.new(jwk_directory: key_directory, status_resolver: status_resolver, now: now, expected_owner: expected_owner)
133
+ end
134
+ end
135
+ end
136
+ end
137
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ # Withdrawal → revocation (build instructions §8 H4, acceptance #4): a withdrawn consent revokes every binding that rests on it.
5
+ # The recovery key R is a file the owner passes for this one act; it is never stored. The log gets `withdrawn` then `revoked`.
6
+ module Consent
7
+ module_function
8
+
9
+ def withdraw(store:, recovery_key_path:, item: nil, agent: nil, reason: nil, now: Time.now)
10
+ raise Malformed, "name an item or an agent to withdraw consent for" if item.nil? && agent.nil?
11
+
12
+ recovery = Keys.from_pem(recovery_key_path)
13
+ raise Malformed, "the recovery key must be an Ed25519 key" unless recovery.is_a?(Keys::Ed25519)
14
+
15
+ targets = targets_for(store, item: item, agent: agent)
16
+ bindings = targets.select { |i| i["kind"] == "binding" }
17
+ # Fail before writing anything: every status list must be re-issuable by this key.
18
+ bindings.each do |b|
19
+ path = b.dig("payload", "status_list_path")
20
+ raise Malformed, "binding #{b['id']} names a status list this store cannot re-issue (#{b.dig('payload', 'binding', 'status', 'url')})" unless path && File.file?(path)
21
+ issuer = b.dig("payload", "binding", "status", "issuer")
22
+ raise Error, "binding #{b['id']}: the status list is issued by #{issuer}, not by the recovery key given (#{recovery.did})" unless issuer == recovery.did
23
+ end
24
+
25
+ ids = targets.map { |i| i["id"] }
26
+ store.log.append(event: "withdrawn", subject: item || "agent:#{agent}", now: now,
27
+ detail: { "items" => ids, "agent" => agent, "reason" => reason }.compact)
28
+ revoked = bindings.map do |b|
29
+ path, index = b.dig("payload", "status_list_path"), b.dig("payload", "binding", "status", "index")
30
+ Revoker.new(recovery_key: recovery, path: path, now: now).revoke(index)
31
+ list_hash = "sha256:" + Digest::SHA256.hexdigest(File.read(path))
32
+ store.log.append(event: "revoked", subject: b["id"], now: now, detail: { "status_index" => index, "status_list_hash" => list_hash, "consent_ref" => b["consent_ref"] })
33
+ { "binding_id" => b["id"], "status_index" => index, "status_list_path" => path, "status_list_hash" => list_hash }
34
+ end
35
+ store.mark_withdrawn(ids, now: now)
36
+ { "withdrawn" => ids, "revoked" => revoked }
37
+ end
38
+
39
+ # The items a withdrawal covers: the named item plus every binding whose consent_ref points at it, or every item of an agent.
40
+ def targets_for(store, item:, agent:)
41
+ items = store.items.reject { |i| i["withdrawn_at"] }
42
+ if item
43
+ named = items.find { |i| i["id"] == item }
44
+ raise Malformed, "no item #{item} in this store (or already withdrawn)" unless named
45
+
46
+ dependents = items.select { |i| i["kind"] == "binding" && i.dig("payload", "binding", "consent_ref") == named["consent_ref"] && i["id"] != named["id"] }
47
+ [ named ] + dependents
48
+ else
49
+ found = items.select { |i| Array(i["agents"]).include?(agent) }
50
+ raise Malformed, "no items for agent #{agent} in this store" if found.empty?
51
+
52
+ found
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ # guarded — ADR-003: the consent log is append-only and hash-chained. It records what was collected, stored, presented to whom,
4
+ # withdrawn and revoked — as ids, hashes and references, never credential contents (build instructions §6 "logs leaking credentials").
5
+ module FlexHold
6
+ class ConsentLog
7
+ GENESIS = "genesis"
8
+ EVENTS = %w[store_initialised consented stored presented withdrawn revoked exported imported].freeze
9
+ FORBIDDEN_KEYS = %w[payload block jws credential credentialSubject statement proof key private].freeze
10
+ MAX_STRING = 1024
11
+ CONSENT_REF_RE = /\Aconsent:([0-9a-f-]{36}):(\d+)\z/
12
+
13
+ attr_reader :path
14
+
15
+ def self.consent_ref(store_id, seq) = "consent:#{store_id}:#{seq}"
16
+
17
+ def self.parse_consent_ref(ref)
18
+ m = ref.to_s.match(CONSENT_REF_RE)
19
+ m && [ m[1], Integer(m[2]) ]
20
+ end
21
+
22
+ # hash = sha256 over the canonical entry without its own hash — the chain link the next entry carries as prev.
23
+ def self.entry_hash(entry) = Collector::Canonical.sha256_hex(entry.reject { |k, _| k == "hash" })
24
+
25
+ def initialize(path) = @path = path
26
+
27
+ # One entry = one line, one write, O_APPEND: nothing before it is ever touched.
28
+ def append(event:, subject:, detail: {}, now: Time.now)
29
+ raise Malformed, "unknown consent event #{event.inspect}" unless EVENTS.include?(event)
30
+ raise Malformed, "subject must be a non-empty string" unless subject.is_a?(String) && !subject.strip.empty?
31
+ references_only!(detail, "detail")
32
+
33
+ last = entries
34
+ entry = { "seq" => last.size + 1, "at" => now.utc.strftime("%Y-%m-%dT%H:%M:%SZ"), "event" => event, "subject" => subject,
35
+ "detail" => detail, "prev" => last.empty? ? GENESIS : last.last["hash"] }
36
+ entry["hash"] = self.class.entry_hash(entry)
37
+ File.open(path, File::WRONLY | File::APPEND | File::CREAT, 0o600) { |f| f.write(JSON.generate(entry) + "\n") }
38
+ entry
39
+ end
40
+
41
+ # The verified chain; a broken chain is a tampered store, not a list.
42
+ def entries
43
+ v = verify
44
+ raise StoreTampered, "consent log chain broken at entry #{v['broken_at']}" unless v["ok"]
45
+
46
+ v["entries"]
47
+ end
48
+
49
+ def head = verify["head"]
50
+
51
+ def verify
52
+ lines = File.exist?(path) ? File.readlines(path, chomp: true).reject(&:empty?) : []
53
+ entries = []
54
+ prev = GENESIS
55
+ lines.each_with_index do |line, i|
56
+ e = begin
57
+ JSON.parse(line)
58
+ rescue JSON::ParserError
59
+ return broken(entries, i + 1)
60
+ end
61
+ return broken(entries, i + 1) unless e.is_a?(Hash) && e["seq"] == i + 1 && e["prev"] == prev && e["hash"] == self.class.entry_hash(e) && EVENTS.include?(e["event"])
62
+
63
+ entries << e
64
+ prev = e["hash"]
65
+ end
66
+ { "ok" => true, "count" => entries.size, "head" => prev, "broken_at" => nil, "entries" => entries }
67
+ end
68
+
69
+ private
70
+
71
+ def broken(entries, at) = { "ok" => false, "count" => entries.size, "head" => entries.last&.fetch("hash") || GENESIS, "broken_at" => at, "entries" => entries }
72
+
73
+ def references_only!(v, where)
74
+ case v
75
+ when Hash
76
+ v.each do |k, x|
77
+ raise Malformed, "#{where}.#{k}: the consent log carries references and hashes, never credential contents" if FORBIDDEN_KEYS.include?(k.to_s)
78
+ references_only!(x, "#{where}.#{k}")
79
+ end
80
+ when Array then v.each_with_index { |x, i| references_only!(x, "#{where}[#{i}]") }
81
+ when String then raise Malformed, "#{where}: string longer than #{MAX_STRING} chars is not a reference" if v.length > MAX_STRING
82
+ when Numeric, TrueClass, FalseClass, NilClass then nil
83
+ else raise Malformed, "#{where}: unsupported value"
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ # guarded — ADR-003 / ADR-005: EIP-712 typed-data hashing (encodeType, hashStruct, domain separator, final digest).
4
+ # Pinned by the specification's "Mail" example in test/secp256k1_eip712_test.rb.
5
+ module FlexHold
6
+ module EIP712
7
+ module_function
8
+
9
+ def keccak256(bytes) = Secp256k1.keccak256(bytes)
10
+
11
+ # "Mail(Person from,Person to,string contents)Person(string name,address wallet)"
12
+ def encode_type(primary, types)
13
+ deps = collect_deps(primary, types) - [ primary ]
14
+ ([ primary ] + deps.sort).map { |t| "#{t}(#{types.fetch(t).map { |n, ty| "#{ty} #{n}" }.join(',')})" }.join
15
+ end
16
+
17
+ def type_hash(primary, types) = keccak256(encode_type(primary, types))
18
+
19
+ def hash_struct(primary, data, types) = keccak256(encode_data(primary, data, types))
20
+
21
+ def encode_data(primary, data, types)
22
+ type_hash(primary, types) + types.fetch(primary).map { |name, type| encode_field(type, data.fetch(name), types) }.join
23
+ end
24
+
25
+ def encode_field(type, value, types)
26
+ case type
27
+ when "string" then keccak256(value.to_s.b)
28
+ when "bytes" then keccak256(value.b)
29
+ when "bytes32"
30
+ raise Malformed, "bytes32 must be 32 bytes" unless value.bytesize == 32
31
+
32
+ value.b
33
+ when "address" then Secp256k1.octets(OpenSSL::BN.new(value.delete_prefix("0x"), 16))
34
+ when /\Auint(\d+)\z/ then uint(Integer($1), value, type)
35
+ when "bool" then Secp256k1.octets(OpenSSL::BN.new(value ? 1 : 0))
36
+ else
37
+ raise Malformed, "unknown EIP-712 type #{type}" unless types.key?(type)
38
+
39
+ hash_struct(type, value, types)
40
+ end
41
+ end
42
+
43
+ # uint8 … uint256 (multiples of 8): a 32-byte big-endian word; negative or out-of-range values are Malformed (H2 generalised
44
+ # the H1.1 set uint256/uint64/uint32 — FlexTrust's PassportStatement uses uint16 and uint8).
45
+ def uint(bits, value, type)
46
+ raise Malformed, "unknown EIP-712 type #{type}" unless bits.between?(8, 256) && (bits % 8).zero?
47
+
48
+ n = Integer(value)
49
+ raise Malformed, "#{type} out of range" if n.negative? || n.bit_length > bits
50
+
51
+ Secp256k1.octets(OpenSSL::BN.new(n))
52
+ rescue ArgumentError, TypeError
53
+ raise Malformed, "#{type} must be an integer"
54
+ end
55
+
56
+ def domain_separator(domain, types) = hash_struct("EIP712Domain", domain, types)
57
+
58
+ # keccak256("\x19\x01" ‖ domainSeparator ‖ hashStruct(message))
59
+ def digest(domain, primary, message, types)
60
+ keccak256("\x19\x01".b + domain_separator(domain, types) + hash_struct(primary, message, types))
61
+ end
62
+
63
+ def collect_deps(type, types, found = [])
64
+ return found if found.include?(type) || !types.key?(type)
65
+
66
+ found << type
67
+ types[type].each { |_n, ty| collect_deps(ty.delete_suffix("[]"), types, found) }
68
+ found
69
+ end
70
+ end
71
+ end
72
+
73
+ module FlexHold
74
+ module EIP712
75
+ # The FlexHold profile: what an owner's wallet shows and signs for a binding. The human-readable fields come
76
+ # from the payload; payloadHash binds the exact JWS signing input (header + payload), so nothing else can change.
77
+ module BindingProfile
78
+ TYPES = {
79
+ "EIP712Domain" => [ %w[name string], %w[version string], %w[chainId uint256] ],
80
+ "FlexHoldBinding" => [ %w[jti string], %w[owner string], %w[agent string], %w[mandateHash string], %w[validUntil string],
81
+ %w[statusList string], %w[statusIndex uint256], %w[audience string], %w[payloadHash bytes32] ]
82
+ }.freeze
83
+ NAME = "FlexHold Binding"
84
+ VERSION = "1"
85
+
86
+ module_function
87
+
88
+ def domain(chain_id) = { "name" => NAME, "version" => VERSION, "chainId" => chain_id }
89
+
90
+ def message(payload, signing_input)
91
+ raise Malformed, "EIP-712 profile covers the FlexHoldBinding credential only" unless payload.is_a?(Hash) && payload["type"] == Binding::TYPE
92
+
93
+ cs, st = payload["credentialSubject"], payload["credentialStatus"]
94
+ raise Malformed, "payload lacks credentialSubject / credentialStatus" unless cs.is_a?(Hash) && st.is_a?(Hash)
95
+
96
+ {
97
+ "jti" => payload["jti"].to_s, "owner" => payload["iss"].to_s, "agent" => cs["id"].to_s,
98
+ "mandateHash" => cs.dig("mandate", "hash").to_s, "validUntil" => payload["validUntil"].to_s,
99
+ "statusList" => st["statusListCredential"].to_s, "statusIndex" => Integer(st["statusListIndex"].to_s, 10),
100
+ "audience" => payload["aud"].to_s, "payloadHash" => Secp256k1.keccak256(signing_input.b)
101
+ }
102
+ rescue ArgumentError
103
+ raise Malformed, "statusListIndex must be an integer"
104
+ end
105
+
106
+ def digest(payload, signing_input, chain_id) = EIP712.digest(domain(chain_id), "FlexHoldBinding", message(payload, signing_input), TYPES)
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ # H3 · the Agent Passport Envelope (docs/bridge/ENVELOPE-SPEC-v1.0.md): ONE W3C VC 2.0 Verifiable Presentation that carries up to
5
+ # three signed blocks from three issuers — mandate, record, binding (+ identity credentials) — each as issued, bytes unchanged.
6
+ # Pure: builds, checks and encodes the document; it never fetches, stores or verifies an issuer's signature (the door does that).
7
+ module Envelope
8
+ CONTEXT_VC = "https://www.w3.org/ns/credentials/v2"
9
+ CONTEXT = "https://w3id.org/agent-passport/envelope/v1" # D37 (Christian, 2026-10-28): w3id.org permanent id; published 2026-10-28 with envelope v1.0 (public repo 1909-Works/agent-passport)
10
+ TYPE = [ "VerifiablePresentation", "AgentPassportEnvelope" ].freeze
11
+ VERSION = "envelope-v1.0"
12
+ ROLES = %w[mandate record binding identity].freeze
13
+ ENVELOPED_TYPE = "EnvelopedVerifiableCredential"
14
+ VC_JWT_URL = "data:application/vc+jwt,"
15
+ MEDIA_TYPE = "application/agent-passport+json"
16
+ HEADER = "Agent-Passport"
17
+ DATA_FORM_MAX = 32 * 1024 # §4: the data form is for envelopes ≤ 32 KB; above that the file (or, later, URL) form
18
+ PROOF_TYP = "agent-passport+jwt"
19
+
20
+ module_function
21
+
22
+ # §1. A JWS-secured block travels enveloped (data:application/vc+jwt,<compact JWS>); a JSON-LD block with its embedded proof
23
+ # travels inline. Pre-flight (§3 #3/#4) refuses an inconsistent passport before anything leaves the holder.
24
+ def build(holder:, nonce:, presented_at:, mandate_jws: nil, record: nil, binding_jws: nil, identity: [], policy_url: nil, audience: nil)
25
+ raise Malformed, "holder must be a DID" unless holder.is_a?(String) && holder.start_with?("did:")
26
+ raise Malformed, "nonce must be a non-empty string" unless nonce.is_a?(String) && !nonce.empty?
27
+ raise PresentationRefused.new(:role_unavailable, "nothing to present: no block for any role") if mandate_jws.nil? && record.nil? && binding_jws.nil? && Array(identity).empty?
28
+
29
+ check!(holder, mandate_jws, binding_jws)
30
+ credentials, roles = [], { "mandate" => nil, "record" => nil, "binding" => nil, "identity" => [] }
31
+ place = ->(role, entry) { roles[role] = credentials.size; credentials << entry }
32
+ place.call("mandate", enveloped(mandate_jws)) if mandate_jws
33
+ place.call("record", inline(record)) if record
34
+ place.call("binding", enveloped(binding_jws)) if binding_jws
35
+ Array(identity).each { |c| roles["identity"] << credentials.size; credentials << (c.is_a?(String) ? enveloped(c) : inline(c)) }
36
+
37
+ env = { "@context" => [ CONTEXT_VC, CONTEXT ], "type" => TYPE.dup, "version" => VERSION, "holder" => holder, "roles" => roles, "verifiableCredential" => credentials }
38
+ env["policy_url"] = policy_url if policy_url
39
+ env["anchors"] = []
40
+ env["presented_at"] = presented_at.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
41
+ env["aud"] = audience if audience
42
+ env["nonce"] = nonce
43
+ env
44
+ end
45
+
46
+ # §3 #3: holder = mandate subject = binding agent. §3 #4: binding.mandate.hash = sha256 over the mandate's own bytes (the compact
47
+ # JWS ASCII, nothing around it) and binding.mandate.issuer = the mandate's issuer (binding rule 5, v1.1).
48
+ def check!(holder, mandate_jws, binding_jws)
49
+ mandate = mandate_jws && JWS.decode(mandate_jws).last
50
+ binding = binding_jws && Binding.from_claims(JWS.decode(binding_jws).last)
51
+ subject = mandate && (mandate["sub"] || mandate.dig("credentialSubject", "id"))
52
+ refuse(:agent_mismatch, "mandate subject #{subject} is not the holder #{holder}") if mandate && subject != holder
53
+ refuse(:agent_mismatch, "binding agent #{binding.agent_key_id} is not the holder #{holder}") if binding && binding.agent_key_id != holder
54
+ return unless mandate && binding
55
+
56
+ hash = "sha256:" + Digest::SHA256.hexdigest(mandate_jws)
57
+ refuse(:mandate_mismatch, "the binding hashes another mandate (#{binding.mandate_hash}, presented #{hash})") unless binding.mandate_hash == hash
58
+ issuer = mandate["iss"] || mandate.dig("issuer", "id") || mandate["issuer"]
59
+ refuse(:mandate_mismatch, "the binding names mandate issuer #{binding.mandate['issuer']}, the mandate says #{issuer}") unless binding.mandate["issuer"] == issuer
60
+ end
61
+
62
+ def enveloped(jws)
63
+ raise Malformed, "a JWS block must be a compact JWS" unless jws.is_a?(String) && jws.count(".") == 2 && jws.match?(/\A[A-Za-z0-9_.-]+\z/)
64
+
65
+ { "@context" => [ CONTEXT_VC ], "type" => [ ENVELOPED_TYPE ], "id" => VC_JWT_URL + jws }
66
+ end
67
+
68
+ def inline(doc)
69
+ raise Malformed, "an inline block must be a JSON object (the credential as issued)" unless doc.is_a?(Hash)
70
+
71
+ doc
72
+ end
73
+
74
+ # §4 offline form: canonical = keys sorted at every level, no whitespace, without `proof` (the signing input).
75
+ def canonical(env) = Collector::Canonical.json(env.reject { |k, _| k == "proof" })
76
+ def hash(env) = "sha256:" + Digest::SHA256.hexdigest(canonical(env))
77
+
78
+ # proof = a compact JWS by the holder key K over the canonical envelope; aud + nonce ride inside it. Only K may sign.
79
+ def sign(env, agent_key)
80
+ refuse(:agent_mismatch, "the proof key #{agent_key.did} is not the holder #{env['holder']}") unless agent_key.did == env["holder"]
81
+
82
+ env.merge("proof" => JWS.sign(JSON.parse(canonical(env)), agent_key, typ: PROOF_TYP))
83
+ end
84
+
85
+ def proof_valid?(env)
86
+ return false unless env.is_a?(Hash) && env["proof"].is_a?(String)
87
+
88
+ header, payload = JWS.decode(env["proof"])
89
+ return false unless header["typ"] == PROOF_TYP && Collector::Canonical.json(payload) == canonical(env)
90
+
91
+ key = Keys.public_from_did(env["holder"])
92
+ return false unless header["kid"] == key.kid
93
+
94
+ parts = env["proof"].split(".")
95
+ key.verify_jws(JWS.b64url_decode(parts[2]), "#{parts[0]}.#{parts[1]}", payload)
96
+ rescue FlexHold::Error
97
+ false
98
+ end
99
+
100
+ # §4 data form (HTTP header / MCP _meta.agentPassport): the whole document, proof included, base64 of the canonical bytes.
101
+ def data_url(env, strict: true)
102
+ url = "data:#{MEDIA_TYPE};base64," + Base64.strict_encode64(Collector::Canonical.json(env))
103
+ return url if url.bytesize <= DATA_FORM_MAX
104
+ raise Malformed, "the envelope is #{url.bytesize} bytes in the data form; the cap is 32 KB — use the file form (--out)" if strict
105
+
106
+ nil
107
+ end
108
+
109
+ def header(env) = "#{HEADER}: #{data_url(env)}"
110
+
111
+ def refuse(reason, message) = raise(PresentationRefused.new(reason, message))
112
+ end
113
+ end