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
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1ca276b67493d49b36f4d796b05c423bffecedfdd658bee38fdb5c703c89384e
4
+ data.tar.gz: 6e10bc9e67dd4e3119a093783d2dbabffbf2f68c82fa163ba7e6a8576f86e679
5
+ SHA512:
6
+ metadata.gz: b548675c2c79bca8ccb5b0f1ce788680a8dd35e6ebf13d3f976d8d76cdfa30e4193570cfead67fbfd46c40d059dd1174ea0cb63e7d2b073fd34c49d0d1cf49f1
7
+ data.tar.gz: 6674521739f1dc7a9050c1f02eb159f348ff02f2df3f19ea35399ee4ef3c947f4baa4918d32e4243c3398c28bbf9e08c3822e553b65e5287a5d91a82d3c937cf
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/NOTICE ADDED
@@ -0,0 +1,22 @@
1
+ flex_hold
2
+ Copyright 2026 Christian Schlager
3
+
4
+ Licensed under the Apache License, Version 2.0. See LICENSE.
5
+
6
+ The files under vectors/ are test vectors, published under Creative Commons
7
+ Attribution 4.0 International (CC BY 4.0) at
8
+ https://github.com/1909-Works/agent-passport and bundled here unchanged.
9
+ Two of them carry blocks made by other projects, included with their
10
+ permission under the same licence:
11
+
12
+ - vectors/fixture-flexyield-mandate-indicative-v0.1.json and the JWS the
13
+ mandate-*.json vectors carry: attribution FlexYield.
14
+ - vectors/fixture-flextrust-passport-indicative-v0.1.json and the block the
15
+ record-*.json vectors carry: attribution FlexTrust.
16
+
17
+ Every key in vectors/ is a test-only key whose seed is published. Never use
18
+ one for anything real.
19
+
20
+ lib/flex_hold/policy/gate-policy-v1.json is the gate-policy vocabulary
21
+ (gate-policy-v1) that FlexTrust publishes at
22
+ https://flextrust.io/spec/gate-policy.json, vendored for offline checks.
data/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # flex_hold
2
+
3
+ The owner's wallet for agent passports.
4
+
5
+ An AI agent acts for someone. `flex_hold` is the tool that someone, the **owner**, uses to say so in a way a door can verify, and to
6
+ keep the credentials the agent carries. It signs the one thing only an owner can sign, the **binding**: "owner key O controls agent
7
+ key K under mandate M until T, revocable here". It issues no identity, computes no score and meters nothing.
8
+
9
+ **Status: 0.1.0.pre1, a preview release.** It is published so the formats can be tried with working code. Read "Limits of this
10
+ preview" before you rely on it.
11
+
12
+ ## Install
13
+
14
+ ```
15
+ gem install flex_hold --pre # a preview release; Ruby 3.4 or newer
16
+ flexhold version
17
+ flexhold vectors verify # runs the bundled test vectors through the signer and the verifiers
18
+ ```
19
+
20
+ ## What it does
21
+
22
+ | Area | Commands | What you get |
23
+ |---|---|---|
24
+ | Binding | `flexhold keygen`, `sign`, `verify`, `revoke` | a W3C VC 2.0 credential as a compact JWS, signed by the owner key (Ed25519 / EdDSA, or an Ethereum account / EIP-712); offline verification with one typed reason per failure |
25
+ | Status list | `flexhold status-list init`, `refresh` | a Bitstring Status List signed by a second, offline recovery key R; revocation re-issues the list |
26
+ | Collector | `flexhold record`, `mandate`, `identity` with `verify` or `collect` | verifies a reputation record block, an authority's mandate block and one owner-identity credential (`jwt_vc_json`) against the issuer's published keys before anything is stored |
27
+ | Store and consent | `flexhold store init`, `add`, `list`, `show`, `export`, `import`; `flexhold consent log`, `verify`, `withdraw` | an encrypted store on your own machine (scrypt, AES-256-GCM) and an append-only, hash-chained consent log; withdrawing consent revokes the bindings that rest on it |
28
+ | Presenter | `flexhold present`, `flexhold policy read` | one Agent Passport Envelope (v1.0) per door, carrying only the blocks the door's gate policy asks for |
29
+ | MCP | `flexhold mcp` | a local stdio MCP server with 15 tools and 5 resources covering the same capabilities |
30
+
31
+ `flexhold help` and `flexhold help COMMAND` list every option.
32
+
33
+ ## First steps
34
+
35
+ ```
36
+ flexhold keygen --out owner.key
37
+ flexhold keygen --out recovery.key --recovery
38
+ flexhold status-list init --recovery-key recovery.key --url file://$PWD/status.jws --out status.jws
39
+ flexhold help sign
40
+ ```
41
+
42
+ Key files are created with mode 0600 and are never overwritten. The store passphrase is read from `FLEXHOLD_STORE_PASSPHRASE` or a
43
+ 0600 file, never from the command line.
44
+
45
+ ## Limits of this preview
46
+
47
+ - **Status lists are read from a file or a `file://` URL only.** This release does not fetch a status list over https, and it hosts
48
+ nothing: where a list is published is the owner's choice.
49
+ - **The consent wording is not part of this preview.** `flexhold store add` writes a log entry that names a wording version
50
+ (`draft-2026-10-27`). That wording is a draft, has not been reviewed by a lawyer, and is neither shipped nor shown. The log records
51
+ that you stored a block, when, and its hash. Do not treat it as a legal consent record yet.
52
+ - Identity credentials are verified with EdDSA (Ed25519) issuer keys only.
53
+ - The MCP server is local (stdio). There is no hosted service and no web interface.
54
+ - The collector's own specification is not published yet; its checks are listed with the test vectors (link below).
55
+
56
+ ## Specifications and test vectors
57
+
58
+ The formats are open and published at <https://github.com/1909-Works/agent-passport> (CC BY 4.0): the Agent Passport Envelope v1.0,
59
+ the binding v1.1, two JSON-LD contexts and the test vectors with their check tables. The 74 vector files in this gem's `vectors/`
60
+ are that public set, unchanged. Every key in them is a test-only key with a published seed.
61
+
62
+ ## Licence
63
+
64
+ Code: Apache License 2.0 (`LICENSE`). Test vectors: CC BY 4.0, with attributions in `NOTICE`.
65
+
66
+ Contact: hello@flexyield.io
data/exe/flexhold ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../lib/flex_hold/cli"
5
+ begin
6
+ FlexHold::CLI.start(ARGV)
7
+ rescue FlexHold::Error => e
8
+ warn "flexhold: #{e.message}"
9
+ exit 1
10
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ # Base58 (Bitcoin alphabet) — needed for did:key multibase ("z" prefix). Pinned by the vectors.
5
+ module Base58
6
+ ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
7
+ INDEX = ALPHABET.each_char.with_index.to_h.freeze
8
+
9
+ module_function
10
+
11
+ def encode(bytes)
12
+ leading = bytes.each_byte.take_while(&:zero?).size
13
+ n = bytes.unpack1("H*").to_i(16)
14
+ out = +""
15
+ while n.positive?
16
+ n, r = n.divmod(58)
17
+ out.prepend(ALPHABET[r])
18
+ end
19
+ ("1" * leading) + out
20
+ end
21
+
22
+ def decode(str)
23
+ raise Malformed, "base58: empty" if str.empty?
24
+
25
+ n = 0
26
+ str.each_char do |c|
27
+ d = INDEX[c] or raise Malformed, "base58: bad character"
28
+ n = n * 58 + d
29
+ end
30
+ hex = n.to_s(16)
31
+ hex = "0" + hex if hex.length.odd?
32
+ body = n.zero? ? "".b : [ hex ].pack("H*")
33
+ ("\x00" * str.each_char.take_while { |c| c == "1" }.size).b + body
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,175 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexHold
4
+ # The binding block v1 (build instructions §4): "owner key O controls agent key K under mandate M
5
+ # until T, revocable here". A value object validated at the boundary; serialises to a W3C VC 2.0
6
+ # credential and to the JWT claims that secure it.
7
+ class Binding
8
+ CONTEXT = [ "https://www.w3.org/ns/credentials/v2", "https://w3id.org/agent-passport/binding/v1" ].freeze # D37 (Christian, 2026-10-28): w3id.org permanent id, published with envelope v1.0
9
+ # v1.1 (2026-10-28, ENVELOPE E1): the envelope role type `AgentBinding` rides along so a door recognises the block by role;
10
+ # a v1 binding without it still parses — REQUIRED_TYPES are the two every binding must carry.
11
+ TYPE = [ "VerifiableCredential", "FlexHoldBinding", "AgentBinding" ].freeze
12
+ REQUIRED_TYPES = [ "VerifiableCredential", "FlexHoldBinding" ].freeze
13
+ DID_RE = /\Adid:[a-z0-9]+:[A-Za-z0-9.\-_:%]+\z/
14
+ HASH_RE = /\Asha256:[0-9a-f]{64}\z/
15
+ EVM_ADDRESS_RE = /\A0x[0-9a-fA-F]{40}\z/
16
+
17
+ attr_reader :owner, :agent, :mandate, :valid_from, :valid_until, :status, :consent_ref, :identity_refs
18
+
19
+ def self.from_h(h)
20
+ raise Malformed, "binding must be an object" unless h.is_a?(Hash)
21
+
22
+ new(
23
+ owner: did!(h["owner"], "owner"),
24
+ agent: agent!(h["agent"]),
25
+ mandate: mandate!(h["mandate"]),
26
+ valid_from: time!(h["valid_from"], "valid_from"),
27
+ valid_until: time!(h["valid_until"], "valid_until"),
28
+ status: status!(h["status"]),
29
+ consent_ref: string!(h["consent_ref"], "consent_ref"),
30
+ identity_refs: refs!(h["identity_refs"])
31
+ )
32
+ end
33
+
34
+ # Inverse of #to_claims (the credential is the JWT payload).
35
+ def self.from_claims(c)
36
+ raise Malformed, "claims must be an object" unless c.is_a?(Hash)
37
+ raise Malformed, "type" unless c["type"].is_a?(Array) && REQUIRED_TYPES.all? { |t| c["type"].include?(t) }
38
+
39
+ cs = c["credentialSubject"]
40
+ st = c["credentialStatus"]
41
+ raise Malformed, "credentialSubject" unless cs.is_a?(Hash)
42
+ raise Malformed, "credentialStatus" unless st.is_a?(Hash) && st["type"] == "BitstringStatusListEntry" && st["statusPurpose"] == "revocation"
43
+
44
+ agent = (cs["agent"] || {}).merge("key_id" => cs["id"])
45
+ from_h(
46
+ "owner" => c["issuer"], "agent" => agent, "mandate" => cs["mandate"],
47
+ "valid_from" => c["validFrom"], "valid_until" => c["validUntil"],
48
+ "status" => { "url" => st["statusListCredential"], "index" => Integer(st["statusListIndex"], 10, exception: false), "issuer" => st["issuer"] },
49
+ "consent_ref" => cs["consent_ref"], "identity_refs" => cs["identity_refs"]
50
+ )
51
+ end
52
+
53
+ def initialize(owner:, agent:, mandate:, valid_from:, valid_until:, status:, consent_ref:, identity_refs:)
54
+ raise Malformed, "valid_until must be after valid_from" unless valid_until > valid_from
55
+
56
+ @owner, @agent, @mandate, @valid_from, @valid_until, @status, @consent_ref, @identity_refs =
57
+ owner, agent, mandate, valid_from, valid_until, status, consent_ref, identity_refs
58
+ freeze
59
+ end
60
+
61
+ def agent_key_id = agent["key_id"]
62
+ def erc8004? = agent.key?("erc8004")
63
+ def erc8004 = agent["erc8004"]
64
+ def status_url = status["url"]
65
+ def status_index = status["index"]
66
+ def status_issuer = status["issuer"]
67
+ def mandate_hash = mandate["hash"]
68
+
69
+ def to_h
70
+ {
71
+ "owner" => owner, "agent" => agent, "mandate" => mandate,
72
+ "valid_from" => iso(valid_from), "valid_until" => iso(valid_until),
73
+ "status" => status, "consent_ref" => consent_ref, "identity_refs" => identity_refs
74
+ }
75
+ end
76
+
77
+ def to_credential
78
+ {
79
+ "@context" => CONTEXT,
80
+ "type" => TYPE,
81
+ "issuer" => owner,
82
+ "validFrom" => iso(valid_from),
83
+ "validUntil" => iso(valid_until),
84
+ "credentialSubject" => {
85
+ "id" => agent_key_id,
86
+ "agent" => agent.except("key_id"),
87
+ "mandate" => mandate,
88
+ "consent_ref" => consent_ref,
89
+ "identity_refs" => identity_refs
90
+ },
91
+ "credentialStatus" => {
92
+ "type" => "BitstringStatusListEntry",
93
+ "statusPurpose" => "revocation",
94
+ "statusListIndex" => status_index.to_s,
95
+ "statusListCredential" => status_url,
96
+ "issuer" => status_issuer
97
+ }
98
+ }
99
+ end
100
+
101
+ def to_claims(jti:, iat:, nonce:, audience: nil)
102
+ claims = to_credential.merge(
103
+ "id" => jti, "iss" => owner, "sub" => agent_key_id,
104
+ "nbf" => valid_from.to_i, "exp" => valid_until.to_i, "iat" => iat.to_i, "jti" => jti, "nonce" => nonce
105
+ )
106
+ claims["aud"] = audience if audience
107
+ claims
108
+ end
109
+
110
+ class << self
111
+ private
112
+
113
+ def did!(v, name)
114
+ raise Malformed, "#{name} must be a DID" unless v.is_a?(String) && v.match?(DID_RE)
115
+
116
+ v
117
+ end
118
+
119
+ def string!(v, name)
120
+ raise Malformed, "#{name} must be a non-empty string" unless v.is_a?(String) && !v.strip.empty?
121
+
122
+ v
123
+ end
124
+
125
+ def time!(v, name)
126
+ raise Malformed, "#{name} must be an RFC 3339 timestamp" unless v.is_a?(String) && v.match?(/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})\z/)
127
+
128
+ Time.iso8601(v).utc
129
+ rescue ArgumentError
130
+ raise Malformed, "#{name} must be an RFC 3339 timestamp"
131
+ end
132
+
133
+ def agent!(a)
134
+ raise Malformed, "agent must be an object" unless a.is_a?(Hash)
135
+
136
+ out = { "key_id" => string!(a["key_id"], "agent.key_id") }
137
+ out["web_bot_auth_key_id"] = string!(a["web_bot_auth_key_id"], "agent.web_bot_auth_key_id") if a.key?("web_bot_auth_key_id")
138
+ if a.key?("erc8004")
139
+ e = a["erc8004"]
140
+ raise Malformed, "agent.erc8004 must be an object" unless e.is_a?(Hash)
141
+ raise Malformed, "agent.erc8004.chain_id must be a positive integer" unless e["chain_id"].is_a?(Integer) && e["chain_id"].positive?
142
+ raise Malformed, "agent.erc8004.registry must be an EVM address" unless e["registry"].is_a?(String) && e["registry"].match?(EVM_ADDRESS_RE)
143
+
144
+ out["erc8004"] = { "chain_id" => e["chain_id"], "registry" => e["registry"].downcase, "agent_id" => string!(e["agent_id"].to_s, "agent.erc8004.agent_id") }
145
+ end
146
+ out
147
+ end
148
+
149
+ def mandate!(m)
150
+ raise Malformed, "mandate must be an object" unless m.is_a?(Hash)
151
+ raise Malformed, "mandate.hash must be sha256:<hex>" unless m["hash"].is_a?(String) && m["hash"].match?(HASH_RE)
152
+
153
+ { "hash" => m["hash"], "issuer" => string!(m["issuer"], "mandate.issuer"), "version" => string!(m["version"].to_s, "mandate.version") }
154
+ end
155
+
156
+ def status!(s)
157
+ raise Malformed, "status must be an object" unless s.is_a?(Hash)
158
+ raise Malformed, "status.index must be a non-negative integer" unless s["index"].is_a?(Integer) && s["index"] >= 0
159
+
160
+ { "url" => string!(s["url"], "status.url"), "index" => s["index"], "issuer" => did!(s["issuer"], "status.issuer") }
161
+ end
162
+
163
+ def refs!(r)
164
+ r = [] if r.nil?
165
+ raise Malformed, "identity_refs must be an array of strings" unless r.is_a?(Array) && r.all? { |x| x.is_a?(String) && !x.empty? }
166
+
167
+ r
168
+ end
169
+ end
170
+
171
+ private
172
+
173
+ def iso(t) = t.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
174
+ end
175
+ end