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,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ # Compact JWS, EdDSA only (RFC 8037). Used to secure the binding credential and the status list
5
+ # credential (W3C "Securing VCs with JOSE": typ vc+jwt, the credential is the payload).
6
+ module JWS
7
+ ALG = "EdDSA"
8
+ ALGS = [ "EdDSA", "EIP712" ].freeze # EIP712 = FlexHold's envelope profile for wallet owners (not a JOSE-registered alg)
9
+ TYP_VC = "vc+jwt"
10
+
11
+ module_function
12
+
13
+ def b64url(bytes) = Base64.urlsafe_encode64(bytes, padding: false)
14
+
15
+ def b64url_decode(str)
16
+ raise Malformed, "base64url" unless str.is_a?(String) && str.match?(/\A[A-Za-z0-9_-]*\z/)
17
+
18
+ Base64.urlsafe_decode64(str)
19
+ end
20
+
21
+ def sign(payload, key, typ: TYP_VC)
22
+ header = { "alg" => key.alg, "typ" => typ, "kid" => key.kid }
23
+ signing_input = "#{b64url(JSON.generate(header))}.#{b64url(JSON.generate(payload))}"
24
+ "#{signing_input}.#{b64url(key.sign_jws(signing_input, payload))}"
25
+ end
26
+
27
+ # Header and payload without verification (needed to find the issuer key first).
28
+ def decode(compact)
29
+ parts = compact.is_a?(String) ? compact.split(".", -1) : []
30
+ raise Malformed, "compact JWS needs three parts" unless parts.size == 3
31
+
32
+ header = JSON.parse(b64url_decode(parts[0]))
33
+ payload = JSON.parse(b64url_decode(parts[1]))
34
+ raise Malformed, "header must be an object" unless header.is_a?(Hash)
35
+ raise Malformed, "alg must be one of #{ALGS.join(', ')}" unless ALGS.include?(header["alg"])
36
+
37
+ [ header, payload ]
38
+ rescue JSON::ParserError, ArgumentError
39
+ raise Malformed, "JWS parts are not valid base64url JSON"
40
+ end
41
+
42
+ def verify(compact, public_key)
43
+ header, payload = decode(compact)
44
+ raise SignatureInvalid, "alg #{header['alg']} does not match the key (#{public_key.alg})" unless header["alg"] == public_key.alg
45
+
46
+ h, p, s = compact.split(".", -1)
47
+ raise SignatureInvalid, "signature does not verify" unless public_key.verify_jws(b64url_decode(s), "#{h}.#{p}", payload)
48
+
49
+ payload
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,196 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ module Keys
5
+ PKH_RE = %r{\Adid:pkh:eip155:(\d+):(0x[0-9a-fA-F]{40})\z}
6
+
7
+ # DID → public-only key: did:key (Ed25519) or did:pkh:eip155 (an Ethereum account, EIP-712 signatures).
8
+ def self.public_from_did(did)
9
+ raise UnsupportedDID, "DID must be a string" unless did.is_a?(String)
10
+ return Ed25519.public_from_did(did) if did.start_with?("did:key:")
11
+ return Pkh.from_did(did) if did.start_with?("did:pkh:")
12
+
13
+ raise UnsupportedDID, "unsupported DID method"
14
+ end
15
+
16
+ # PEM file → private key object by curve (Ed25519 or secp256k1).
17
+ def self.from_pem(path, chain_id: 1)
18
+ pkey = OpenSSL::PKey.read(File.binread(path))
19
+ case pkey
20
+ when OpenSSL::PKey::EC
21
+ raise Malformed, "EC key is not secp256k1" unless pkey.group.curve_name == "secp256k1"
22
+
23
+ Secp256k1.from_private_bytes(FlexHold::Secp256k1.octets(pkey.private_key), chain_id: chain_id)
24
+ else
25
+ raise Malformed, "unsupported key type" unless pkey.oid == "ED25519"
26
+
27
+ Ed25519.new(pkey)
28
+ end
29
+ rescue OpenSSL::PKey::PKeyError, Errno::ENOENT => e
30
+ raise Malformed, "key file: #{e.class}"
31
+ end
32
+
33
+ # Ed25519 owner / recovery / agent keys on Ruby's OpenSSL (no native gem). H1 identifier: did:key.
34
+ # Private material never leaves this object except through #write_pem (mode 0600).
35
+ class Ed25519
36
+ MULTICODEC_ED25519_PUB = "\xED\x01".b # varint(0xed)
37
+ DID_KEY_PREFIX = "did:key:z"
38
+
39
+ attr_reader :pkey
40
+
41
+ def self.generate = new(OpenSSL::PKey.generate_key("ED25519"))
42
+
43
+ def self.from_seed(seed)
44
+ raise Malformed, "seed must be 32 bytes" unless seed.bytesize == 32
45
+
46
+ new(OpenSSL::PKey.new_raw_private_key("ED25519", seed))
47
+ end
48
+
49
+ def self.from_pem(path)
50
+ new(OpenSSL::PKey.read(File.binread(path)))
51
+ rescue OpenSSL::PKey::PKeyError, Errno::ENOENT => e
52
+ raise Malformed, "key file: #{e.class}"
53
+ end
54
+
55
+ def self.from_public_bytes(bytes)
56
+ raise Malformed, "public key must be 32 bytes" unless bytes.bytesize == 32
57
+
58
+ new(OpenSSL::PKey.new_raw_public_key("ED25519", bytes))
59
+ end
60
+
61
+ # did:key → public-only key. Only Ed25519 did:key is supported in H1.
62
+ def self.public_from_did(did)
63
+ raise UnsupportedDID, "only did:key (Ed25519) is supported" unless did.is_a?(String) && did.start_with?(DID_KEY_PREFIX)
64
+
65
+ raw = Base58.decode(did.delete_prefix(DID_KEY_PREFIX))
66
+ raise UnsupportedDID, "did:key is not Ed25519" unless raw.start_with?(MULTICODEC_ED25519_PUB) && raw.bytesize == 34
67
+
68
+ from_public_bytes(raw.byteslice(2, 32))
69
+ rescue Malformed
70
+ raise UnsupportedDID, "did:key could not be decoded"
71
+ end
72
+
73
+ def initialize(pkey)
74
+ @pkey = pkey
75
+ end
76
+
77
+ def public_key_bytes = @pkey.raw_public_key
78
+ def private?
79
+ @pkey.raw_private_key
80
+ true
81
+ rescue OpenSSL::PKey::PKeyError
82
+ false
83
+ end
84
+ def multibase = "z" + Base58.encode(MULTICODEC_ED25519_PUB + public_key_bytes)
85
+ def did = "did:key:" + multibase
86
+ def kid = "#{did}##{multibase}"
87
+
88
+ def to_jwk = { "kty" => "OKP", "crv" => "Ed25519", "x" => JWS.b64url(public_key_bytes) }
89
+ def alg = "EdDSA"
90
+
91
+ # JWS hooks (the payload is irrelevant for EdDSA; the EIP-712 keys need it for the typed data)
92
+ def sign_jws(signing_input, _payload) = sign(signing_input)
93
+ def verify_jws(signature, signing_input, _payload) = verify(signature, signing_input)
94
+
95
+ def sign(data)
96
+ raise Error, "no private key" unless private?
97
+
98
+ @pkey.sign(nil, data)
99
+ end
100
+
101
+ def verify(signature, data)
102
+ @pkey.verify(nil, signature, data)
103
+ rescue OpenSSL::PKey::PKeyError
104
+ false
105
+ end
106
+
107
+ def write_pem(path)
108
+ File.open(path, File::WRONLY | File::CREAT | File::TRUNC, 0o600) { |f| f.write(@pkey.private_to_pem) }
109
+ File.chmod(0o600, path)
110
+ path
111
+ end
112
+
113
+ def inspect = "#<FlexHold::Keys::Ed25519 #{did}#{private? ? ' (private)' : ''}>"
114
+ alias to_s inspect
115
+ end
116
+ end
117
+ end
118
+
119
+ module FlexHold
120
+ module Keys
121
+ # An Ethereum account as the owner key O: did:pkh:eip155:<chain_id>:<EIP-55 address>; signs the binding as
122
+ # EIP-712 typed data (FlexHold profile, see EIP712::BindingProfile). Private scalar kept in this object only.
123
+ class Secp256k1
124
+ attr_reader :chain_id, :address
125
+
126
+ def self.generate(chain_id: 1) = from_private_bytes(FlexHold::Secp256k1.octets(OpenSSL::PKey::EC.generate("secp256k1").private_key), chain_id: chain_id)
127
+
128
+ def self.from_private_bytes(bytes, chain_id: 1)
129
+ raise Malformed, "private key must be 32 bytes" unless bytes.bytesize == 32
130
+
131
+ new(bytes, chain_id: chain_id)
132
+ end
133
+
134
+ def initialize(private_bytes, chain_id:)
135
+ raise Malformed, "chain_id must be a positive integer" unless chain_id.is_a?(Integer) && chain_id.positive?
136
+
137
+ @private_bytes = private_bytes.b
138
+ @chain_id = chain_id
139
+ @public = FlexHold::Secp256k1.public_key(@private_bytes)
140
+ @address = FlexHold::Secp256k1.address(@public)
141
+ end
142
+
143
+ def did = "did:pkh:eip155:#{chain_id}:#{address}"
144
+ def kid = "#{did}#blockchainAccountId"
145
+ def alg = "EIP712"
146
+ def private? = true
147
+ def public_key_uncompressed = @public
148
+
149
+ def sign_digest(digest) = FlexHold::Secp256k1.sign(digest, @private_bytes)
150
+ def sign_jws(signing_input, payload) = sign_digest(EIP712::BindingProfile.digest(payload, signing_input, chain_id))
151
+ def verify_jws(signature, signing_input, payload) = Pkh.new(chain_id: chain_id, address: address).verify_jws(signature, signing_input, payload)
152
+
153
+ def write_pem(path)
154
+ ec = OpenSSL::PKey::EC.new(OpenSSL::ASN1::Sequence([
155
+ OpenSSL::ASN1::Integer(1), OpenSSL::ASN1::OctetString(@private_bytes),
156
+ OpenSSL::ASN1::ObjectId("secp256k1", 0, :EXPLICIT), OpenSSL::ASN1::BitString(@public, 1, :EXPLICIT)
157
+ ]).to_der)
158
+ File.open(path, File::WRONLY | File::CREAT | File::TRUNC, 0o600) { |f| f.write(ec.private_to_pem) }
159
+ File.chmod(0o600, path)
160
+ path
161
+ end
162
+
163
+ def inspect = "#<FlexHold::Keys::Secp256k1 #{did} (private)>"
164
+ alias to_s inspect
165
+ end
166
+
167
+ # Public-only did:pkh:eip155 key: verification = recover the signer address from the EIP-712 signature and compare.
168
+ class Pkh
169
+ attr_reader :chain_id, :address
170
+
171
+ def self.from_did(did)
172
+ m = PKH_RE.match(did) or raise UnsupportedDID, "only did:pkh:eip155:<chain>:<address> is supported"
173
+ new(chain_id: m[1].to_i, address: m[2])
174
+ end
175
+
176
+ def initialize(chain_id:, address:)
177
+ @chain_id = chain_id
178
+ @address = FlexHold::Secp256k1.checksum(address)
179
+ end
180
+
181
+ def did = "did:pkh:eip155:#{chain_id}:#{address}"
182
+ def kid = "#{did}#blockchainAccountId"
183
+ def alg = "EIP712"
184
+ def private? = false
185
+
186
+ def verify_jws(signature, signing_input, payload)
187
+ FlexHold::Secp256k1.recover_address(EIP712::BindingProfile.digest(payload, signing_input, chain_id), signature) == address
188
+ rescue SignatureInvalid, Malformed
189
+ false
190
+ end
191
+
192
+ def inspect = "#<FlexHold::Keys::Pkh #{did}>"
193
+ alias to_s inspect
194
+ end
195
+ end
196
+ end
@@ -0,0 +1,296 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fast_mcp"
4
+ require_relative "../flex_hold"
5
+
6
+ module FlexHold
7
+ # Local stdio MCP server (build instructions §9): an owner drives FlexHold from an agent client without hosting
8
+ # anything. Tools call the same Services as the CLI. H2 adds the collector tools, H4 the store, H3 `present_passport`.
9
+ module MCPServer
10
+ module Guarded
11
+ # Every tool returns a typed JSON result; FlexHold errors become {ok:false, error:…} and never raise
12
+ # (the transport would otherwise print a backtrace into the client's error text).
13
+ def guarded
14
+ JSON.generate(yield)
15
+ rescue FlexHold::Error => e
16
+ JSON.generate({ "ok" => false, "error" => e.class.name.split("::").last, "message" => e.message })
17
+ end
18
+ end
19
+
20
+ class SignTool < FastMcp::Tool
21
+ include Guarded
22
+ tool_name "sign"
23
+ description "Sign a binding (owner key O controls agent key K under mandate M until T) with the owner key file → compact JWS. The key never leaves the file."
24
+ arguments do
25
+ required(:key_path).filled(:string).description("path of the owner key file (Ed25519 PEM, 0600)")
26
+ required(:binding).filled(:string).description("binding as a JSON string or a path to a JSON file")
27
+ optional(:audience).filled(:string).description("door-bound binding: the policy_url / door id")
28
+ optional(:out).filled(:string).description("write the JWS to this path")
29
+ optional(:chain_id).filled(:integer).description("for a secp256k1 (wallet) key: the eip155 chain id of the owner's did:pkh (default 1)")
30
+ end
31
+ def call(key_path:, binding:, audience: nil, out: nil, chain_id: 1) = guarded { Services.sign(key_path: key_path, binding: binding, audience: audience, out: out, chain_id: chain_id).merge("ok" => true) }
32
+ end
33
+
34
+ class VerifyTool < FastMcp::Tool
35
+ include Guarded
36
+ tool_name "verify"
37
+ description "Verify a binding JWS offline: signature, time window, audience, status list, mandate hash, agent key, ERC-8004 owner equality. Returns ok plus one typed reason."
38
+ arguments do
39
+ required(:jws).filled(:string).description("the compact JWS or a path to a file holding it")
40
+ optional(:status_list_path).filled(:string).description("status-list JWS file (default: the binding's file:// URL)")
41
+ optional(:mandate_path).filled(:string).description("the mandate block as presented; its bytes are hashed")
42
+ optional(:mandate_issuer).filled(:string).description("the mandate block's issuer as verify_mandate established it; must equal the binding's mandate.issuer (v1.1)")
43
+ optional(:registration_path).filled(:string).description("ERC-8004 registration snapshot JSON")
44
+ optional(:request_key_id).filled(:string).description("DID of the key that signed the request")
45
+ optional(:audience).filled(:string).description("this door's policy_url / id")
46
+ end
47
+ def call(jws:, status_list_path: nil, mandate_path: nil, mandate_issuer: nil, registration_path: nil, request_key_id: nil, audience: nil)
48
+ guarded { Services.verify(jws: jws, status: status_list_path, mandate: mandate_path, mandate_issuer: mandate_issuer, registration: registration_path, request_key_id: request_key_id, audience: audience) }
49
+ end
50
+ end
51
+
52
+ class RevokeTool < FastMcp::Tool
53
+ include Guarded
54
+ tool_name "revoke"
55
+ description "Revoke a binding: the recovery key R sets its status bit and re-issues the status list (works without the owner key O)."
56
+ arguments do
57
+ required(:recovery_key_path).filled(:string).description("path of the recovery key file R")
58
+ required(:status_list_path).filled(:string).description("status-list JWS file, re-written atomically")
59
+ required(:index).filled(:integer).description("the binding's status index")
60
+ end
61
+ def call(recovery_key_path:, status_list_path:, index:) = guarded { Services.revoke(recovery_key_path: recovery_key_path, status_list: status_list_path, index: index) }
62
+ end
63
+
64
+ class VerifyRecordTool < FastMcp::Tool
65
+ include Guarded
66
+ tool_name "verify_record"
67
+ description "Verify a FlexTrust record block (passport-v1 document) offline: window, key, digest, merkle, root, freshness. Nothing is trusted without a key directory and the commitments. Returns ok plus one typed reason and the block summary."
68
+ arguments do
69
+ required(:path).filled(:string).description("path to the passport JSON document")
70
+ optional(:keys).filled(:string).description("key directory: file or https URL (/.well-known/flextrust)")
71
+ optional(:commitments).filled(:string).description("daily commitments: file or https URL (/commitments.json)")
72
+ optional(:now).filled(:string).description("verification time, RFC 3339 (default: now)")
73
+ end
74
+ def call(path:, keys: nil, commitments: nil, now: nil) = guarded { Services.record_verify(path: path, keys: keys, commitments: commitments, now: now) }
75
+ end
76
+
77
+ class CollectRecordTool < FastMcp::Tool
78
+ include Guarded
79
+ tool_name "collect_record"
80
+ description "Fetch a FlexTrust record block (agent id → the public passport at zero cost, a flextrust.io URL, or a local file), verify it and return it as a collected block {source, ref, collected_at, verification, block}. Remote refs default to the live key directory and commitments."
81
+ arguments do
82
+ required(:ref).filled(:string).description("agent id, https://flextrust.io/... URL, or a file path")
83
+ optional(:keys).filled(:string).description("key directory: file or https URL")
84
+ optional(:commitments).filled(:string).description("daily commitments: file or https URL")
85
+ optional(:now).filled(:string).description("verification time, RFC 3339 (default: now)")
86
+ optional(:out).filled(:string).description("write the collected block to this path")
87
+ end
88
+ def call(ref:, keys: nil, commitments: nil, now: nil, out: nil) = guarded { Services.record_collect(ref: ref, keys: keys, commitments: commitments, now: now, out: out) }
89
+ end
90
+
91
+ class VerifyMandateTool < FastMcp::Tool
92
+ include Guarded
93
+ tool_name "verify_mandate"
94
+ description "Verify a FlexYield mandate block (mandate-v1 compact JWS or its JSON wrapper) offline: key, issuer, window, subject, claim, receipts. Nothing is trusted without a JWK Set. Returns ok, one typed reason, the mandate summary and mandate_hash (what the owner's binding carries)."
95
+ arguments do
96
+ required(:path).filled(:string).description("path to the mandate: FlexYield's JSON wrapper or the bare compact JWS")
97
+ optional(:keys).filled(:string).description("JWK Set with validity: file or https URL")
98
+ optional(:now).filled(:string).description("verification time, RFC 3339 (default: now)")
99
+ optional(:agent).filled(:string).description("the agent key K the binding names; the mandate's subject must be this key")
100
+ end
101
+ def call(path:, keys: nil, now: nil, agent: nil) = guarded { Services.mandate_verify(path: path, keys: keys, now: now, agent: agent) }
102
+ end
103
+
104
+ class CollectMandateTool < FastMcp::Tool
105
+ include Guarded
106
+ tool_name "collect_mandate"
107
+ description "Fetch a FlexYield mandate block (a flexyield.io URL or a local file), verify it and return it as a collected block {source, ref, collected_at, verification, block}. Remote refs default to the issuer's JWK Set (/.well-known/flexyield, reserved by FlexYield, not live yet)."
108
+ arguments do
109
+ required(:ref).filled(:string).description("https://flexyield.io/... URL, or a file path (JSON wrapper or bare JWS)")
110
+ optional(:keys).filled(:string).description("JWK Set with validity: file or https URL")
111
+ optional(:now).filled(:string).description("verification time, RFC 3339 (default: now)")
112
+ optional(:agent).filled(:string).description("the agent key K the binding names")
113
+ optional(:out).filled(:string).description("write the collected block to this path")
114
+ end
115
+ def call(ref:, keys: nil, now: nil, agent: nil, out: nil) = guarded { Services.mandate_collect(ref: ref, keys: keys, now: now, agent: agent, out: out) }
116
+ end
117
+
118
+ class VerifyIdentityTool < FastMcp::Tool
119
+ include Guarded
120
+ tool_name "verify_identity"
121
+ description "Verify an owner-identity credential (jwt_vc_json: W3C VC 2.0 as a compact JWS, or its JSON wrapper) offline: key, issuer, window, subject, status. The issuer is a third party: nothing is trusted without ITS JWK Set. Returns ok, one typed reason and a summary with claim names only — never claim values."
122
+ arguments do
123
+ required(:path).filled(:string).description("path to the credential: JSON wrapper {jws} or the bare compact JWS")
124
+ optional(:keys).filled(:string).description("the issuer's JWK Set with validity: file or https URL")
125
+ optional(:status).filled(:string).description("the issuer's status-list JWS as a file (for a credentialStatus entry)")
126
+ optional(:now).filled(:string).description("verification time, RFC 3339 (default: now)")
127
+ optional(:owner).filled(:string).description("the owner DID O the binding names; the credential's subject must be O")
128
+ end
129
+ def call(path:, keys: nil, status: nil, now: nil, owner: nil) = guarded { Services.identity_verify(path: path, keys: keys, status: status, now: now, owner: owner) }
130
+ end
131
+
132
+ class CollectIdentityTool < FastMcp::Tool
133
+ include Guarded
134
+ tool_name "collect_identity"
135
+ description "Fetch an owner-identity credential (an https URL of any issuer — JSON wrapper {jws} — or a local file), verify it with the issuer's JWK Set and return it as a collected block {source: identity, ref, collected_at, verification, block} ready for store_add. No default key URL: the issuer is a third party."
136
+ arguments do
137
+ required(:ref).filled(:string).description("https URL (issuer wrapper {jws}) or a file path (wrapper or bare JWS)")
138
+ optional(:keys).filled(:string).description("the issuer's JWK Set with validity: file or https URL")
139
+ optional(:status).filled(:string).description("the issuer's status-list JWS as a file")
140
+ optional(:now).filled(:string).description("verification time, RFC 3339 (default: now)")
141
+ optional(:owner).filled(:string).description("the owner DID O the binding names")
142
+ optional(:out).filled(:string).description("write the collected block to this path")
143
+ end
144
+ def call(ref:, keys: nil, status: nil, now: nil, owner: nil, out: nil) = guarded { Services.identity_collect(ref: ref, keys: keys, status: status, now: now, owner: owner, out: out) }
145
+ end
146
+
147
+ # H4 · store tools take a passphrase FILE, never the passphrase: tool arguments travel through the agent client's logs.
148
+ class StoreAddTool < FastMcp::Tool
149
+ include Guarded
150
+ tool_name "store_add"
151
+ description "Consent to and store one collected block (the file written by collect_record / collect_mandate --out) or a binding JWS in the owner's encrypted local store. Returns the item id, kind, content hash, agents and the consent_ref the binding should carry."
152
+ arguments do
153
+ required(:store).filled(:string).description("store directory")
154
+ required(:path).filled(:string).description("collected block JSON or binding JWS file")
155
+ required(:passphrase_file).filled(:string).description("0600 file holding the store passphrase")
156
+ end
157
+ def call(store:, path:, passphrase_file:) = guarded { Services.store_add(store: store, path: path, passphrase_file: passphrase_file) }
158
+ end
159
+
160
+ class StoreListTool < FastMcp::Tool
161
+ include Guarded
162
+ tool_name "store_list"
163
+ description "List the store's items: ids, kinds, hashes, agents, consent refs, withdrawal marks — never the credentials themselves."
164
+ arguments do
165
+ required(:store).filled(:string).description("store directory")
166
+ required(:passphrase_file).filled(:string).description("0600 file holding the store passphrase")
167
+ end
168
+ def call(store:, passphrase_file:) = guarded { Services.store_list(store: store, passphrase_file: passphrase_file) }
169
+ end
170
+
171
+ class ConsentLogTool < FastMcp::Tool
172
+ include Guarded
173
+ tool_name "consent_log"
174
+ description "Read and verify the append-only consent log (hash chain): what was consented, stored, presented, withdrawn, revoked — references and hashes only. Needs no passphrase."
175
+ arguments do
176
+ required(:store).filled(:string).description("store directory")
177
+ end
178
+ def call(store:) = guarded { Services.consent_log(store: store) }
179
+ end
180
+
181
+ class ConsentWithdrawTool < FastMcp::Tool
182
+ include Guarded
183
+ tool_name "consent_withdraw"
184
+ description "Withdraw consent for an item or an agent: logs the withdrawal and revokes every binding resting on it by re-issuing the status list with the recovery key R (file path). The door refuses on the next call."
185
+ arguments do
186
+ required(:store).filled(:string).description("store directory")
187
+ required(:passphrase_file).filled(:string).description("0600 file holding the store passphrase")
188
+ required(:recovery_key_path).filled(:string).description("the recovery key R file")
189
+ optional(:item).filled(:string).description("item id")
190
+ optional(:agent).filled(:string).description("agent key / id")
191
+ optional(:reason).filled(:string).description("free text, logged")
192
+ end
193
+ def call(store:, passphrase_file:, recovery_key_path:, item: nil, agent: nil, reason: nil)
194
+ guarded { Services.consent_withdraw(store: store, recovery_key_path: recovery_key_path, item: item, agent: agent, reason: reason, passphrase_file: passphrase_file) }
195
+ end
196
+ end
197
+
198
+ # H3 · present_passport. The result carries the data form (`agent_passport`) — E2: the MCP default — for _meta.agentPassport.
199
+ class PresentPassportTool < FastMcp::Tool
200
+ include Guarded
201
+ tool_name "present_passport"
202
+ description "Write one Agent Passport Envelope (spec v1.0) for a door from the owner's encrypted store: the agent's mandate, record and binding blocks by role (minimum disclosure — name only the roles the door's policy needs), as issued and byte-unchanged. Logs `presented` (to whom, which items, hash) in the consent log. Returns the envelope, its hash and the data form for the `Agent-Passport` header / MCP `_meta.agentPassport` (≤ 32 KB)."
203
+ arguments do
204
+ required(:store).filled(:string).description("store directory")
205
+ required(:passphrase_file).filled(:string).description("0600 file holding the store passphrase")
206
+ required(:agent).filled(:string).description("the agent key K (did:key / Web Bot Auth key id) presenting the envelope")
207
+ optional(:roles).array(:string).description("roles the door needs: mandate, record, binding, identity — overrides the policy (default: the policy's roles, else every single role present; identity credentials only on ask)")
208
+ optional(:policy).filled(:string).description("the door's gate policy (gate-policy-v1) as a file path or https URL: its keys name the roles (bound → binding, the rest → record)")
209
+ optional(:also).array(:string).description("roles added on top of the policy (the mandate and identity credentials are presented only when asked for)")
210
+ optional(:policy_url).filled(:string).description("the door's published gate policy URL: read for the roles unless `roles` is given; carried in the envelope, logged as `to`")
211
+ optional(:audience).filled(:string).description("door id for a door-bound presentation (`aud`)")
212
+ optional(:agent_key_path).filled(:string).description("agent key PEM for the offline `proof` (file form); normally the agent signs the request instead")
213
+ optional(:out).filled(:string).description("also write the envelope document to this path (file form)")
214
+ end
215
+ def call(store:, passphrase_file:, agent:, roles: nil, policy: nil, also: nil, policy_url: nil, audience: nil, agent_key_path: nil, out: nil)
216
+ guarded do
217
+ Services.present(store: store, agent: agent, roles: roles, policy: policy, also: also, policy_url: policy_url, audience: audience, agent_key_path: agent_key_path,
218
+ out: out, passphrase_file: passphrase_file).merge("ok" => true)
219
+ end
220
+ end
221
+ end
222
+
223
+ # H3.2 · read_gate_policy: a door's policy → the roles the presenter would disclose (no store, nothing presented).
224
+ class ReadGatePolicyTool < FastMcp::Tool
225
+ include Guarded
226
+ tool_name "read_gate_policy"
227
+ description "Read a door's gate policy (FlexTrust gate-policy-v1 vocabulary; a file path or https URL) and return the passport roles it asks for: `bound` → binding, every other condition → record, the mandate only on explicit ask. Unknown keys or out-of-vocabulary values are refused with a typed reason. Use it before present_passport to see what would leave the store."
228
+ arguments do
229
+ required(:source).filled(:string).description("the policy: a file path or an https URL (a door's published policy, an instance of the vocabulary — not the vocabulary itself)")
230
+ end
231
+ def call(source:) = guarded { Services.policy_read(source: source).merge("ok" => true) }
232
+ end
233
+
234
+ class GatePolicyVocabularyResource < FastMcp::Resource
235
+ uri "flexhold://spec/gate-policy-v1"
236
+ resource_name "Gate policy vocabulary v1 (FlexTrust C3, vendored)"
237
+ description "The JSON Schema (2020-12) of the gate-policy vocabulary a door's policy is written in — the byte-identical copy FlexHold's policy reader validates against (source: https://flextrust.io/spec/gate-policy.json)."
238
+ mime_type "application/json"
239
+ def content = File.read(Policy::VOCABULARY_PATH)
240
+ end
241
+
242
+ class EnvelopeSpecResource < FastMcp::Resource
243
+ uri "flexhold://spec/envelope-v1.0"
244
+ resource_name "Agent Passport Envelope spec v1.0"
245
+ description "The open, issuer-neutral envelope: one Verifiable Presentation carrying mandate, record, binding (and identity) blocks by role; the door verifier's rule; transports; disclosure."
246
+ mime_type "text/markdown"
247
+ SPEC_PATHS = [ File.expand_path("../../../../docs/bridge/ENVELOPE-SPEC-v1.0.md", __dir__), File.expand_path("../../ENVELOPE.md", __dir__) ].freeze
248
+ def content
249
+ path = SPEC_PATHS.find { |p| File.exist?(p) }
250
+ path ? File.read(path) : "spec not bundled; read it at https://github.com/1909-Works/agent-passport/blob/main/spec/envelope-v1.0.md"
251
+ end
252
+ end
253
+
254
+ class CollectorSpecResource < FastMcp::Resource
255
+ uri "flexhold://spec/collector-v1"
256
+ resource_name "FlexHold collector spec v1"
257
+ description "What FlexHold checks when it collects an issuer block: the FlexTrust record block (six checks), the FlexYield mandate block (six checks) and an owner-identity credential in jwt_vc_json (five checks), typed reasons, conventions, key sources."
258
+ mime_type "text/markdown"
259
+ SPEC_PATHS = [ File.expand_path("../../../../docs/spec/collector-v1.md", __dir__), File.expand_path("../../COLLECTOR.md", __dir__) ].freeze
260
+ def content
261
+ path = SPEC_PATHS.find { |p| File.exist?(p) }
262
+ path ? File.read(path) : "spec not bundled and not published yet; the checks and typed reasons are listed at https://github.com/1909-Works/agent-passport/blob/main/vectors/README.md"
263
+ end
264
+ end
265
+
266
+ class SpecResource < FastMcp::Resource
267
+ uri "flexhold://spec/binding-v1"
268
+ resource_name "FlexHold binding spec v1"
269
+ description "The binding block v1: fields, encoding, verification rule, status list, recovery."
270
+ mime_type "text/markdown"
271
+ SPEC_PATHS = [ File.expand_path("../../../../docs/spec/binding-v1.md", __dir__), File.expand_path("../../SPEC.md", __dir__) ].freeze
272
+ def content
273
+ path = SPEC_PATHS.find { |p| File.exist?(p) }
274
+ path ? File.read(path) : "spec not bundled; read it at https://github.com/1909-Works/agent-passport/blob/main/spec/binding-v1.1.md"
275
+ end
276
+ end
277
+
278
+ class VectorsResource < FastMcp::Resource
279
+ uri "flexhold://vectors"
280
+ resource_name "FlexHold test vectors"
281
+ description "Index of the committed JSON test vectors (test-only keys) and how to run them."
282
+ mime_type "application/json"
283
+ def content = JSON.generate({ "dir" => Vectors::DEFAULT_DIR, "vectors" => Vectors::Runner.new(Vectors::DEFAULT_DIR).names, "record_vectors" => Vectors::RecordRunner.new(Vectors::DEFAULT_DIR).names,
284
+ "mandate_vectors" => Vectors::MandateRunner.new(Vectors::DEFAULT_DIR).names, "identity_vectors" => Vectors::IdentityRunner.new(Vectors::DEFAULT_DIR).names,
285
+ "envelope_vectors" => Vectors::EnvelopeRunner.new(Vectors::DEFAULT_DIR).names, "run" => "flexhold vectors verify" })
286
+ end
287
+
288
+ def self.build
289
+ server = FastMcp::Server.new(name: "flexhold", version: FlexHold::VERSION)
290
+ server.register_tools(SignTool, VerifyTool, RevokeTool, VerifyRecordTool, CollectRecordTool, VerifyMandateTool, CollectMandateTool,
291
+ VerifyIdentityTool, CollectIdentityTool, StoreAddTool, StoreListTool, ConsentLogTool, ConsentWithdrawTool, PresentPassportTool, ReadGatePolicyTool)
292
+ server.register_resources(SpecResource, CollectorSpecResource, EnvelopeSpecResource, GatePolicyVocabularyResource, VectorsResource)
293
+ server
294
+ end
295
+ end
296
+ end
@@ -0,0 +1 @@
1
+ {"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://flextrust.io/spec/gate-policy.json","title":"FlexTrust gate policy (gate-policy-v1)","description":"What a door requires of an agent before serving or paying it. Published vocabulary; every door publishes its own policy.","type":"object","properties":{"min_score":{"type":"integer","description":"lowest acceptable FlexTrust Score — public view: the daily score rounded to 25 (exact score = the paid pre-check)","minimum":0,"maximum":1000},"min_confidence":{"type":"number","description":"lowest acceptable evidence confidence (0–1) — full view only — the free door reports it unevaluated and names the paid pre-check","minimum":0.0,"maximum":1.0},"min_liveness":{"oneOf":[{"type":"integer","description":"lowest acceptable liveness rung (number or rung name) — the liveness ladder v1 rung (/spec/liveness); unprobed agents are unevaluated","minimum":0,"maximum":6},{"type":"string","enum":["registered","pointer","resolves","parses","declares_endpoint","answers","handshake"]}]},"alive":{"type":"boolean","description":"the declared endpoint must answer — shorthand for min_liveness 5 (`answers`)"},"no_open_incidents":{"type":"boolean","description":"no open incident on the ledger — the incident ledger: a confirmed manipulation pattern not yet closed, an open dispute, an owner suspension"},"bound":{"type":"boolean","description":"an owner-signed binding must be present and not revoked — a FlexHold binding presented with the check (binding + status list), verified offline and anchored to this agent's ERC-8004 registration"},"operator_attested":{"type":"boolean","description":"an identity credential names the operator — the passport's operator_attested_by slot — no attestation writer exists yet, so every agent is unattested today"},"bonded":{"type":"boolean","description":"the agent carries a bond — reserved: no bonding product exists yet, so every agent is unbonded today (VISION M4–M12)"},"policy_url":{"type":"string","description":"where this policy is published — not evaluated — the URL a door publishes its policy at; echoed so the answer names the policy it was checked against","format":"uri"}},"additionalProperties":false,"examples":[{"min_score":600,"alive":true,"no_open_incidents":true,"bound":true,"policy_url":"https://door.example/.well-known/gate-policy.json"}]}
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ # H3.2 · the policy reader: a door's published gate policy → the roles the presenter discloses (ENVELOPE §5, minimum disclosure
5
+ # by construction). The vocabulary is FlexTrust's gate-policy-v1 (C3), vendored byte-identical in policy/gate-policy-v1.json;
6
+ # a door's policy is an instance of it (`{"min_score": 600, "bound": true}`), never the vocabulary itself. Mapping agreed over
7
+ # the bridge (2026-10-28): `bound` → binding, every other key → record, no key names the mandate (presented only on explicit
8
+ # ask), `policy_url` is the pointer. Unknown keys and out-of-vocabulary values are typed errors, never ignored. Pure: no network
9
+ # here — `fetch` goes through the injectable collector fetcher.
10
+ class Policy
11
+ VERSION = "gate-policy-v1"
12
+ VOCABULARY_PATH = File.expand_path("policy/gate-policy-v1.json", __dir__)
13
+ ROLE_OF = { "bound" => "binding", "min_score" => "record", "min_confidence" => "record", "min_liveness" => "record", "alive" => "record",
14
+ "no_open_incidents" => "record", "operator_attested" => "record", "bonded" => "record", "policy_url" => nil }.freeze
15
+ ROLE_ORDER = Presenter::SELECTABLE
16
+ FETCH_MAX_BYTES = 65_536
17
+
18
+ def self.vocabulary = @vocabulary ||= JSON.parse(File.read(VOCABULARY_PATH)).freeze
19
+ def self.default_fetcher = Collector::Fetcher::HTTPS.new(max_bytes: FETCH_MAX_BYTES)
20
+
21
+ # URL (https, through the fetcher) or local file → Policy
22
+ def self.load(ref, fetcher: default_fetcher)
23
+ ref.to_s.match?(%r{\A[a-z][a-z0-9+.-]*://}i) ? fetch(ref, fetcher: fetcher) : read(Collector::Sources.document(ref, fetcher: fetcher), source: ref)
24
+ end
25
+
26
+ def self.fetch(url, fetcher: default_fetcher) = read(fetcher.call(url), source: url)
27
+
28
+ # The boundary: shape (a JSON object of vocabulary keys with vocabulary values) and meaning (at least one role-bearing key).
29
+ def self.read(doc, source: nil)
30
+ reject(:not_a_policy, "a gate policy is a JSON object of vocabulary keys (#{ROLE_OF.keys.join(', ')})") unless doc.is_a?(Hash)
31
+ reject(:not_a_policy, "this is the vocabulary (the schema), not a door's policy") if (doc.keys & %w[$schema $id properties]).any?
32
+ unknown = doc.keys - ROLE_OF.keys
33
+ reject(:unknown_key, "#{unknown.join(', ')} not in #{VERSION} (keys: #{ROLE_OF.keys.join(', ')})") if unknown.any?
34
+ doc.each { |k, v| Schema.check!(k, v, vocabulary.dig("properties", k)) }
35
+ roles = ROLE_ORDER & doc.keys.filter_map { |k| ROLE_OF[k] }
36
+ reject(:no_roles, "the policy names no condition a passport block answers (#{doc.keys.join(', ')})") if roles.empty?
37
+
38
+ new(source: source, fields: doc, roles: roles)
39
+ end
40
+
41
+ def self.reject(reason, message) = raise(PolicyRejected.new(reason, message))
42
+
43
+ attr_reader :source, :fields, :roles, :hash
44
+
45
+ def initialize(source:, fields:, roles:)
46
+ @source = source
47
+ @fields = fields.freeze
48
+ @roles = roles.freeze
49
+ @hash = "sha256:" + Collector::Canonical.sha256_hex(fields)
50
+ freeze
51
+ end
52
+
53
+ def version = VERSION
54
+ def keys = fields.keys
55
+ def url? = source.to_s.start_with?("https://")
56
+ def to_h = { "source" => source, "version" => version, "fields" => fields, "roles" => roles, "hash" => hash }
57
+
58
+ # The subset of JSON Schema 2020-12 the vocabulary uses: type (integer / number / boolean / string), minimum / maximum, enum,
59
+ # format (not evaluated beyond "a string"), oneOf over those. Read from the vendored schema, so a re-vendored v1 applies as published.
60
+ module Schema
61
+ module_function
62
+
63
+ def check!(key, value, schema)
64
+ Policy.reject(:invalid_value, "#{key}: #{value.inspect} does not fit #{describe(schema)}") unless fits?(value, schema)
65
+ end
66
+
67
+ def fits?(value, schema)
68
+ return false unless schema.is_a?(Hash)
69
+ return schema["oneOf"].one? { |s| fits?(value, s) } if schema["oneOf"]
70
+
71
+ case schema["type"]
72
+ when "integer" then value.is_a?(Integer) && in_range?(value, schema)
73
+ when "number" then value.is_a?(Numeric) && !value.is_a?(Complex) && in_range?(value, schema)
74
+ when "boolean" then value == true || value == false
75
+ when "string" then value.is_a?(String) && (schema["enum"].nil? || schema["enum"].include?(value))
76
+ else false
77
+ end
78
+ end
79
+
80
+ def in_range?(v, s) = (s["minimum"].nil? || v >= s["minimum"]) && (s["maximum"].nil? || v <= s["maximum"])
81
+
82
+ def describe(schema)
83
+ return "nothing in the vocabulary" unless schema.is_a?(Hash)
84
+ return schema["oneOf"].map { |s| describe(s) }.join(" or ") if schema["oneOf"]
85
+
86
+ [ schema["type"], schema["enum"] && "one of #{schema['enum'].join('/')}", schema["minimum"] && "≥ #{schema['minimum']}", schema["maximum"] && "≤ #{schema['maximum']}" ].compact.join(" ")
87
+ end
88
+ end
89
+ end
90
+ end