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,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ # guarded — ADR-003 (status list = the revocation path; changes need Christian's permission + second confirmation)
4
+ module FlexHold
5
+ module StatusList
6
+ # W3C VC 2.0 Bitstring Status List: ≥ 131072 bits, gzip + multibase base64url ("u" prefix), 1 = revoked.
7
+ class Bitstring
8
+ MIN_BITS = 131_072
9
+
10
+ attr_reader :size
11
+
12
+ def self.decode(encoded)
13
+ raise Malformed, "encodedList must be multibase base64url (u...)" unless encoded.is_a?(String) && encoded.start_with?("u")
14
+
15
+ bytes = Zlib::GzipReader.new(StringIO.new(JWS.b64url_decode(encoded[1..]))).read
16
+ new(bytes: bytes)
17
+ rescue Zlib::Error, ArgumentError
18
+ raise Malformed, "encodedList does not decode"
19
+ end
20
+
21
+ def initialize(size: MIN_BITS, bytes: nil)
22
+ if bytes
23
+ @bytes = bytes.b
24
+ @size = @bytes.bytesize * 8
25
+ else
26
+ @bytes = ("\x00" * (size / 8)).b
27
+ @size = size
28
+ end
29
+ raise Malformed, "status list must be at least #{MIN_BITS} bits" if @size < MIN_BITS
30
+ end
31
+
32
+ def set?(index)
33
+ check!(index)
34
+ (@bytes.getbyte(index / 8) >> (7 - index % 8)) & 1 == 1
35
+ end
36
+
37
+ def set(index)
38
+ check!(index)
39
+ @bytes.setbyte(index / 8, @bytes.getbyte(index / 8) | (1 << (7 - index % 8)))
40
+ self
41
+ end
42
+
43
+ def encode
44
+ io = StringIO.new("".b)
45
+ gz = Zlib::GzipWriter.new(io)
46
+ gz.mtime = 0 # deterministic output (vectors)
47
+ gz.write(@bytes)
48
+ gz.close
49
+ "u" + JWS.b64url(io.string)
50
+ end
51
+
52
+ def dup = Bitstring.new(bytes: @bytes.dup)
53
+
54
+ private
55
+
56
+ def check!(index)
57
+ raise Malformed, "status index out of range" unless index.is_a?(Integer) && index >= 0 && index < @size
58
+ end
59
+ end
60
+
61
+ # The BitstringStatusListCredential, secured as an EdDSA JWS by the recovery key R (ADR-004).
62
+ class Credential
63
+ CONTEXT = [ "https://www.w3.org/ns/credentials/v2" ].freeze
64
+ TYPE = [ "VerifiableCredential", "BitstringStatusListCredential" ].freeze
65
+
66
+ attr_reader :credential, :issuer, :url, :bitstring, :valid_from, :valid_until
67
+
68
+ def self.issue(issuer_key:, url:, valid_from:, valid_for:, bitstring: Bitstring.new)
69
+ valid_from = valid_from.utc
70
+ cred = {
71
+ "@context" => CONTEXT, "type" => TYPE, "id" => url, "issuer" => issuer_key.did,
72
+ "validFrom" => iso(valid_from), "validUntil" => iso(valid_from + valid_for),
73
+ "credentialSubject" => { "id" => "#{url}#list", "type" => "BitstringStatusList", "statusPurpose" => "revocation", "encodedList" => bitstring.encode }
74
+ }
75
+ claims = cred.merge("iss" => issuer_key.did, "nbf" => valid_from.to_i, "exp" => (valid_from + valid_for).to_i, "iat" => valid_from.to_i)
76
+ JWS.sign(claims, issuer_key)
77
+ end
78
+
79
+ # Verifies signature against the issuer the *binding* names (never the list's own claim alone), type, purpose, time.
80
+ def self.parse(jws, expected_issuer:, now:, allow_expired: false)
81
+ _h, claims = JWS.decode(jws)
82
+ raise StatusInvalid, "status list issuer is not the one the binding names" unless claims["issuer"] == expected_issuer && claims["iss"] == expected_issuer
83
+
84
+ JWS.verify(jws, Keys.public_from_did(expected_issuer))
85
+ raise StatusInvalid, "not a BitstringStatusListCredential" unless claims["type"] == TYPE
86
+ cs = claims["credentialSubject"]
87
+ raise StatusInvalid, "statusPurpose must be revocation" unless cs.is_a?(Hash) && cs["statusPurpose"] == "revocation"
88
+
89
+ from, to = Time.iso8601(claims["validFrom"]).utc, Time.iso8601(claims["validUntil"]).utc
90
+ raise StatusInvalid, "status list outside its validity window" unless from <= now.utc && (allow_expired || now.utc < to)
91
+
92
+ new(credential: claims, bitstring: Bitstring.decode(cs["encodedList"]), valid_from: from, valid_until: to)
93
+ rescue Malformed, SignatureInvalid, UnsupportedDID, ArgumentError, TypeError => e
94
+ raise StatusInvalid, "status list does not verify (#{e.class.name.split('::').last})"
95
+ end
96
+
97
+ def self.iso(t) = t.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
98
+
99
+ def initialize(credential:, bitstring:, valid_from:, valid_until:)
100
+ @credential, @bitstring, @valid_from, @valid_until = credential, bitstring, valid_from, valid_until
101
+ @issuer = credential["issuer"]
102
+ @url = credential["id"]
103
+ end
104
+
105
+ def revoked?(index) = bitstring.set?(index)
106
+
107
+ # Revocation = a new list credential with the bit set, signed by the same recovery key.
108
+ def with_revoked(index, issuer_key:, valid_from:, valid_for:)
109
+ raise Error, "the status list must be re-issued by its issuer (#{issuer})" unless issuer_key.did == issuer
110
+
111
+ self.class.issue(issuer_key: issuer_key, url: url, valid_from: valid_from, valid_for: valid_for, bitstring: bitstring.dup.set(index))
112
+ end
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,224 @@
1
+ # frozen_string_literal: true
2
+
3
+ # guarded — ADR-003 / ADR-008: the owner's local store. Encrypted at rest (scrypt → AES-256-GCM, authenticated envelope), local-first,
4
+ # one store per owner, many agents. Holds collected blocks and bindings; never the owner key O or the recovery key R. Coupled to the
5
+ # consent log: the ciphertext carries the log's head, so a truncated or edited log is caught when the store opens.
6
+ module FlexHold
7
+ class Store
8
+ FORMAT = "flexhold-store-v1"
9
+ BUNDLE_FORMAT = "flexhold-bundle-v1"
10
+ STORE_FILE = "store.json"
11
+ LOG_FILE = "consent.log"
12
+ CIPHER = "aes-256-gcm"
13
+ KDF = { "name" => "scrypt", "n" => 32_768, "r" => 8, "p" => 1 }.freeze
14
+ KEY_BYTES = 32
15
+ NONCE_BYTES = 12
16
+ MIN_PASSPHRASE = 12
17
+ CONSENT_TEXT_VERSION = "draft-2026-10-27" # docs/spec/consent-v1.md — DRAFT, counsel item (§7)
18
+ KINDS = %w[record mandate binding identity].freeze
19
+
20
+ attr_reader :dir, :store_id, :owner, :created_at, :log
21
+
22
+ # ---- envelope (guarded crypto) ----------------------------------------------------------------------------------------
23
+ module Envelope
24
+ module_function
25
+
26
+ def passphrase!(p)
27
+ raise Malformed, "a passphrase of at least #{MIN_PASSPHRASE} characters is required" unless p.is_a?(String) && p.length >= MIN_PASSPHRASE
28
+
29
+ p
30
+ end
31
+
32
+ def derive(passphrase, kdf)
33
+ OpenSSL::KDF.scrypt(passphrase, salt: Base64.strict_decode64(kdf["salt"]), N: kdf["n"], r: kdf["r"], p: kdf["p"], length: KEY_BYTES)
34
+ end
35
+
36
+ # The authenticated header: format, store id, KDF parameters, cipher name and key check — swapping any of them breaks the tag.
37
+ def aad(env) = Collector::Canonical.json(env.slice("format", "store_id", "kdf", "cipher", "kcv"))
38
+
39
+ # Key check value: 8 bytes of HMAC(key, label). Tells a wrong passphrase (kcv differs → StoreLocked) from a tampered
40
+ # envelope (kcv matches, GCM tag fails → StoreTampered). Guessing passphrases offline is already possible against the GCM
41
+ # tag; scrypt is the defence, the kcv adds nothing an attacker lacks.
42
+ def kcv(key) = Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", key, "#{FORMAT} kcv").byteslice(0, 8))
43
+
44
+ def seal(plaintext, passphrase, store_id:, salt: SecureRandom.random_bytes(16))
45
+ env = { "format" => FORMAT, "store_id" => store_id, "kdf" => KDF.merge("salt" => Base64.strict_encode64(salt)), "cipher" => CIPHER }
46
+ key = derive(passphrase!(passphrase), env["kdf"])
47
+ env["kcv"] = kcv(key)
48
+ c = OpenSSL::Cipher.new(CIPHER).encrypt
49
+ nonce = SecureRandom.random_bytes(NONCE_BYTES)
50
+ c.key, c.iv = key, nonce
51
+ c.auth_data = aad(env)
52
+ ct = c.update(plaintext) + c.final
53
+ env.merge("nonce" => Base64.strict_encode64(nonce), "ciphertext" => Base64.strict_encode64(ct), "tag" => Base64.strict_encode64(c.auth_tag))
54
+ end
55
+
56
+ # The KDF parameters this version writes are the only ones it reads (a changed parameter is tampering); the key check
57
+ # value separates a wrong passphrase from an altered envelope.
58
+ def open(env, passphrase)
59
+ raise Malformed, "not a #{FORMAT} store" unless env.is_a?(Hash) && env["format"] == FORMAT
60
+ %w[store_id kdf cipher kcv nonce ciphertext tag].each { |k| raise Malformed, "store envelope lacks #{k}" unless env[k] }
61
+ raise StoreTampered, "KDF parameters differ from the #{FORMAT} profile" unless env["kdf"].is_a?(Hash) && env["kdf"].slice(*KDF.keys) == KDF && env["cipher"] == CIPHER
62
+
63
+ key = derive(passphrase!(passphrase), env["kdf"])
64
+ raise StoreLocked, "the store does not open with this passphrase" unless secure_equal?(kcv(key), env["kcv"].to_s)
65
+
66
+ c = OpenSSL::Cipher.new(CIPHER).decrypt
67
+ c.key, c.iv = key, Base64.strict_decode64(env["nonce"])
68
+ c.auth_tag = Base64.strict_decode64(env["tag"])
69
+ c.auth_data = aad(env)
70
+ c.update(Base64.strict_decode64(env["ciphertext"])) + c.final
71
+ rescue OpenSSL::Cipher::CipherError
72
+ raise StoreTampered, "the store envelope was altered (authentication failed)"
73
+ rescue ArgumentError
74
+ raise Malformed, "store envelope is not valid base64"
75
+ end
76
+
77
+ def secure_equal?(a, b) = a.bytesize == b.bytesize && OpenSSL.fixed_length_secure_compare(a, b)
78
+ end
79
+
80
+ # ---- lifecycle --------------------------------------------------------------------------------------------------------
81
+ def self.create(dir, owner:, passphrase:, now: Time.now)
82
+ raise Error, "refusing to overwrite the store at #{dir}" if File.exist?(File.join(dir, STORE_FILE)) || File.exist?(File.join(dir, LOG_FILE))
83
+ raise Malformed, "owner must be a DID" unless owner.is_a?(String) && owner.match?(/\Adid:[a-z0-9]+:\S+\z/)
84
+
85
+ Envelope.passphrase!(passphrase)
86
+ FileUtils.mkdir_p(dir, mode: 0o700)
87
+ File.chmod(0o700, dir)
88
+ store = new(dir, passphrase: passphrase, store_id: SecureRandom.uuid, owner: owner, created_at: iso(now), items: [])
89
+ store.log.append(event: "store_initialised", subject: "store:#{store.store_id}", detail: { "owner" => owner }, now: now)
90
+ store.send(:save)
91
+ store
92
+ end
93
+
94
+ def self.open(dir, passphrase:)
95
+ env = begin
96
+ JSON.parse(File.read(File.join(dir, STORE_FILE)))
97
+ rescue SystemCallError, JSON::ParserError
98
+ raise Malformed, "no store at #{dir}"
99
+ end
100
+ data = JSON.parse(Envelope.open(env, passphrase))
101
+ store = new(dir, passphrase: passphrase, store_id: env["store_id"], owner: data["owner"], created_at: data["created_at"], items: data["items"])
102
+ v = store.log.verify
103
+ raise StoreTampered, "consent log chain broken at entry #{v['broken_at']}" unless v["ok"]
104
+ raise StoreTampered, "consent log head does not match the store (log truncated or edited)" unless v["head"] == data["log_head"]
105
+
106
+ store
107
+ end
108
+
109
+ # A bundle = the encrypted envelope + the consent log, still closed. Import proves the passphrase and the chain before writing.
110
+ def self.import(bundle, dir, passphrase:, now: Time.now)
111
+ bundle = JSON.parse(File.read(bundle)) if bundle.is_a?(String)
112
+ raise Malformed, "not a #{BUNDLE_FORMAT}" unless bundle.is_a?(Hash) && bundle["format"] == BUNDLE_FORMAT && bundle["envelope"].is_a?(Hash) && bundle["consent_log"].is_a?(Array)
113
+ raise Error, "refusing to overwrite the store at #{dir}" if File.exist?(File.join(dir, STORE_FILE))
114
+
115
+ data = JSON.parse(Envelope.open(bundle["envelope"], passphrase))
116
+ prev = ConsentLog::GENESIS
117
+ bundle["consent_log"].each_with_index do |e, i|
118
+ raise StoreTampered, "bundle consent log broken at entry #{i + 1}" unless e.is_a?(Hash) && e["seq"] == i + 1 && e["prev"] == prev && e["hash"] == ConsentLog.entry_hash(e)
119
+ prev = e["hash"]
120
+ end
121
+ raise StoreTampered, "bundle consent log does not match the store's log head" unless prev == data["log_head"]
122
+
123
+ FileUtils.mkdir_p(dir, mode: 0o700)
124
+ File.chmod(0o700, dir)
125
+ Revoker.write_atomically(File.join(dir, LOG_FILE), bundle["consent_log"].map { |e| JSON.generate(e) + "\n" }.join)
126
+ Revoker.write_atomically(File.join(dir, STORE_FILE), JSON.generate(bundle["envelope"]))
127
+ store = open(dir, passphrase: passphrase)
128
+ store.log.append(event: "imported", subject: "store:#{store.store_id}", detail: { "items" => store.items.size, "log_head" => data["log_head"] }, now: now)
129
+ store.send(:save)
130
+ store
131
+ end
132
+
133
+ def self.iso(t) = t.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
134
+
135
+ def initialize(dir, passphrase:, store_id:, owner:, created_at:, items:)
136
+ @dir, @passphrase, @store_id, @owner, @created_at, @items = dir, passphrase, store_id, owner, created_at, items
137
+ @log = ConsentLog.new(File.join(dir, LOG_FILE))
138
+ end
139
+
140
+ def items = @items.map(&:dup)
141
+ def item(id) = @items.find { |i| i["id"] == id }&.dup
142
+
143
+ # ---- adding -----------------------------------------------------------------------------------------------------------
144
+ # payload: a collected block as H2 produces it ({source, ref, collected_at, verification, block}) or a binding (compact JWS /
145
+ # {jws}). Only verified blocks enter; consent is recorded first (consent_ref), then the item (content hash).
146
+ def add(payload, now: Time.now)
147
+ kind, stored, hash, agents = classify(payload)
148
+ id = "item:#{SecureRandom.uuid}"
149
+ consented = log.append(event: "consented", subject: id, now: now,
150
+ detail: { "kind" => kind, "content_hash" => hash, "agents" => agents, "source" => stored["source"], "consent_text_version" => CONSENT_TEXT_VERSION })
151
+ item = { "id" => id, "kind" => kind, "added_at" => self.class.iso(now), "consent_ref" => ConsentLog.consent_ref(store_id, consented["seq"]),
152
+ "content_hash" => hash, "agents" => agents, "payload" => stored }
153
+ item["subject"] = stored.dig("verification", "block", "subject") if kind == "identity" # whose credential (the owner DID), for listings
154
+ @items << item
155
+ log.append(event: "stored", subject: id, detail: { "kind" => kind, "content_hash" => hash }, now: now)
156
+ save
157
+ item.dup
158
+ end
159
+
160
+ # One log entry + reseal, for events that change no item (H3 `presented`): the log head is sealed in the ciphertext, so an
161
+ # append without a save would make the store fail to open (StoreTampered).
162
+ def note(event:, subject:, detail: {}, now: Time.now)
163
+ entry = log.append(event: event, subject: subject, detail: detail, now: now)
164
+ save
165
+ entry
166
+ end
167
+
168
+ def mark_withdrawn(ids, now: Time.now)
169
+ @items.each { |i| i["withdrawn_at"] = self.class.iso(now) if ids.include?(i["id"]) }
170
+ save
171
+ end
172
+
173
+ def export(now: Time.now)
174
+ log.append(event: "exported", subject: "store:#{store_id}", detail: { "items" => @items.size }, now: now)
175
+ save
176
+ { "format" => BUNDLE_FORMAT, "exported_at" => self.class.iso(now), "envelope" => JSON.parse(File.read(File.join(dir, STORE_FILE))), "consent_log" => log.entries }
177
+ end
178
+
179
+ private
180
+
181
+ def save
182
+ plaintext = JSON.generate({ "owner" => owner, "created_at" => created_at, "items" => @items, "log_head" => log.head })
183
+ Revoker.write_atomically(File.join(dir, STORE_FILE), JSON.generate(Envelope.seal(plaintext, @passphrase, store_id: store_id)))
184
+ end
185
+
186
+ def classify(payload)
187
+ payload = JSON.parse(payload) if payload.is_a?(String) && payload.lstrip.start_with?("{")
188
+ if payload.is_a?(String) && payload.count(".") == 2 || payload.is_a?(Hash) && payload.key?("jws") && !payload.key?("verification")
189
+ binding_item(payload.is_a?(Hash) ? payload["jws"] : payload)
190
+ elsif payload.is_a?(Hash) && payload["verification"].is_a?(Hash) && payload.key?("block")
191
+ block_item(payload)
192
+ else
193
+ raise Malformed, "not a collected block ({source, verification, block}) or a binding JWS"
194
+ end
195
+ end
196
+
197
+ def binding_item(jws)
198
+ _header, claims = JWS.decode(jws.to_s.strip)
199
+ binding = Binding.from_claims(claims)
200
+ url = binding.status_url.to_s
201
+ path = url.start_with?("file://") ? url.delete_prefix("file://") : nil
202
+ agents = [ binding.agent_key_id ]
203
+ agents << "erc8004:#{binding.erc8004['chain_id']}:#{binding.erc8004['agent_id']}" if binding.erc8004?
204
+ [ "binding", { "jws" => jws.strip, "binding" => binding.to_h, "status_list_path" => path }, "sha256:" + Digest::SHA256.hexdigest(jws.strip), agents ]
205
+ rescue Malformed => e
206
+ raise Malformed, "binding does not parse: #{e.message}"
207
+ end
208
+
209
+ def block_item(payload)
210
+ v = payload["verification"]
211
+ raise Malformed, "only verified blocks enter the store (verdict: #{v['reason']})" unless v["ok"] == true
212
+ kind = { "flextrust" => "record", "flexyield" => "mandate", "identity" => "identity" }[payload["source"]]
213
+ raise Malformed, "unknown block source #{payload['source'].inspect}" unless kind
214
+
215
+ summary = v["block"].is_a?(Hash) ? v["block"] : {}
216
+ agents = case kind
217
+ when "record" then [ summary.dig("agent", "did"), payload.dig("block", "credentialSubject", "id") ].compact.uniq
218
+ when "mandate" then [ summary.dig("agent", "key_id") ].compact
219
+ else [] # H2.3: an identity credential is about the owner, not an agent — the binding's identity_refs link it (presenter)
220
+ end
221
+ [ kind, payload, "sha256:" + Collector::Canonical.sha256_hex(payload["block"]), agents ]
222
+ end
223
+ end
224
+ end