hooktrace 0.1.0

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 6332c306c82b599988592467f4d743fa2cba34d903df349b64a8c3a8246fc089
4
+ data.tar.gz: dbe326e3efa6c3c5105ab410082ab42fb9337ec8a823375e311b2c03692bd82d
5
+ SHA512:
6
+ metadata.gz: 13215ddd63d4ed012f1e87c60a553d8bb8468a80d9d7c00ae8d6ed07faad4a813d7a7ed89c7924c0f1854ce0b59eb880c419ebcf41cf68e4bfc5f4032d5f4a42
7
+ data.tar.gz: b041fdb4e5dd904f571bec5281553380e9f579dd949516c300a3c44f9fab15f37163176765e1cb05a5df6f53bade62100022cb0450aa7a9bed3973ec1711839a
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,47 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+
6
+ Style/Documentation:
7
+ Enabled: false
8
+
9
+ Style/StringLiterals:
10
+ EnforcedStyle: double_quotes
11
+
12
+ Style/StringLiteralsInInterpolation:
13
+ EnforcedStyle: double_quotes
14
+
15
+ Metrics/BlockLength:
16
+ Exclude:
17
+ - "spec/**/*"
18
+ - "Rakefile"
19
+ - "hooktrace.gemspec"
20
+
21
+ Metrics/ClassLength:
22
+ Max: 200
23
+
24
+ Metrics/ModuleLength:
25
+ Max: 220
26
+
27
+ Metrics/MethodLength:
28
+ Max: 25
29
+
30
+ Metrics/ParameterLists:
31
+ Max: 8
32
+
33
+ Metrics/AbcSize:
34
+ Max: 30
35
+
36
+ Layout/LineLength:
37
+ Max: 120
38
+
39
+ Metrics/CyclomaticComplexity:
40
+ Max: 15
41
+
42
+ Metrics/PerceivedComplexity:
43
+ Max: 15
44
+
45
+ Naming/PredicateMethod:
46
+ AllowedMethods:
47
+ - is_a?
data/CHANGELOG.md ADDED
@@ -0,0 +1,39 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Added
11
+ - **Built-in OpenAPI Provider Contracts & Sync Importers:**
12
+ - `Hooktrace::Importers::OpenApiSchemaConverter` to convert OpenAPI 3 schemas (`$ref`, `allOf`, `anyOf`/`oneOf`, `required`, `nullable`, arrays, and nested objects) into Hooktrace contracts.
13
+ - `Hooktrace::Importers::StripeOpenApi` (`spec3.sdk.json`) generating 32 core Stripe contracts (`event.base` + `charge.*`, `payment_intent.*`, `checkout.session.*`, `invoice.*`, `customer.*`, `payment_method.*`, `payout.*`, `refund.*`), with `--all` support for 275+ Stripe events.
14
+ - `Hooktrace::Importers::PaypalOpenApi` (`notifications_webhooks_v1.json` + Payments, Orders, Subscriptions, Invoicing, and Disputes specs) generating 21 PayPal contracts.
15
+ - Pre-synced `lib/hooktrace/contracts/stripe.json` and `lib/hooktrace/contracts/paypal.json` auto-loaded on boot (`Hooktrace.load_builtin_contracts!`, `Hooktrace.builtin_providers`).
16
+ - `Hooktrace.sync_contracts!` Ruby API and `hooktrace sync [stripe|paypal|all]` CLI command.
17
+ - **Automatic Real Webhook Processing:**
18
+ - `Hooktrace::WebhookProcessor` (`Hooktrace.process_webhook` / `Hooktrace.handle_webhook`) and `Hooktrace::WebhookOutcome` to parse raw JSON or Hash payloads, auto-detect Stripe and PayPal from headers/payload, match `<provider>.event.base` + `<provider>.<event_type>`, validate, and persist results.
19
+ - **Database Storage & Rails Install Generator:**
20
+ - `Hooktrace::Storage::ActiveRecordStore` storing validation records and errors in `hooktrace_events` (auto-selected when ActiveRecord is connected and the table exists, keeping `ActiveRecord` an optional dependency with `FileStore` fallback).
21
+ - `Hooktrace::Generators::InstallGenerator` (`rails generate hooktrace:install`) to generate the `CreateHooktraceEvents` migration.
22
+ - **Contract Overrides & Configuration DSL:**
23
+ - `Hooktrace.configure`, `Hooktrace.override`, `Hooktrace.contracts_path=`, and `Hooktrace::Contract.override` (`required`, `optional`, `object`, `array`, `remove`) to customize built-in contracts in Rails initializers.
24
+
25
+ ### Changed
26
+ - Updated `Hooktrace.validate` to accept single or multiple contracts, deduplicate overlapping errors, and auto-save validation outcomes to `Hooktrace.store` when `auto_record` is enabled.
27
+ - Refactored `Hooktrace::Web` to render external ERB templates (`lib/hooktrace/web/views/*.erb`) and `lib/hooktrace/web/assets/application.css` instead of inline HTML heredocs.
28
+ - Simplified `Hooktrace::EventRecord` and `Hooktrace::Contract` deserialization (`transform_keys(&:to_s)`) and focused provider detection strictly on Stripe and PayPal.
29
+
30
+ ### Removed
31
+ - Removed unused/superseded modules and sample files (`examples/`, `Inferrer`, `Comparator`, `FixtureLoader`, RSpec matcher adapter, and Shopify fixtures).
32
+
33
+ ## [0.1.0] - 2026-10-30
34
+
35
+ ### Added
36
+ - Core contract DSL (`Hooktrace::Contract`, `Hooktrace::Field`), schema validator (`Hooktrace::Validator`), and immutable result/error models (`Hooktrace::Result`, `Hooktrace::Error`).
37
+ - JSON contract loading (`Hooktrace.load_contract`, `Hooktrace.load_contracts_from`) with multi-event provider bundle support.
38
+ - Event recording (`Hooktrace::EventRecord`, `Hooktrace::Storage::FileStore`) and mountable Rack dashboard (`Hooktrace::Web`).
39
+ - Standalone CLI executable (`exe/hooktrace`) for contract validation.
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Sachin Singh Tomar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,190 @@
1
+ # Hooktrace
2
+
3
+ **Webhook contract validation, OpenAPI schema sync, and live event diagnostics for Ruby & Rails applications.**
4
+
5
+ Third-party webhook providers (**Stripe** and **PayPal**) evolve their webhook payloads across API versions. Hooktrace ships pre-synced OpenAPI schemas, automatically matches and validates real incoming webhooks, records validation results into your database, and provides a Sidekiq-style dashboard for inspecting payload violations.
6
+
7
+ ---
8
+
9
+ ## Features
10
+
11
+ - **Built-In OpenAPI Contracts (Stripe & PayPal):** Ships with 32 core Stripe contracts (`2026-10-28.endive`) and 21 PayPal contracts (`v1.11`) generated directly from official OpenAPI specifications and auto-loaded on boot.
12
+ - **Automatic Real Webhook Matching:** `Hooktrace.process_webhook` auto-detects Stripe or PayPal from headers/payload, matches `<provider>.event.base` + `<provider>.<event_type>`, and validates in one call.
13
+ - **Automatic Database Persistence:** `Hooktrace::Storage::ActiveRecordStore` automatically persists valid and failed webhook events to the `hooktrace_events` table whenever you validate (with `FileStore` fallback outside Rails).
14
+ - **Initializer Override DSL:** Customize, add, or remove fields on any built-in OpenAPI contract inside `config/initializers/hooktrace.rb` using `Hooktrace.configure` and `config.override`.
15
+ - **OpenAPI CLI Sync:** Refresh contracts directly from Stripe and PayPal OpenAPI repositories anytime with `hooktrace sync`.
16
+ - **Mountable Web Dashboard:** Sidekiq-style Rack UI (`Hooktrace::Web`) for browsing captured events, contract violations, and active contracts.
17
+ - **Zero Heavy Dependencies:** Core & OpenAPI sync use Ruby stdlib (`json`, `net/http`, `erb`, `optparse`), and the Web UI only requires `rack >= 2.1` (`ActiveRecord` is optional).
18
+
19
+ ---
20
+
21
+ ## Quick Start (How to Use in Your Rails App)
22
+
23
+ ### 1. Install the Gem
24
+
25
+ Add to your `Gemfile`:
26
+
27
+ ```ruby
28
+ gem "hooktrace"
29
+ ```
30
+
31
+ Run:
32
+
33
+ ```bash
34
+ bundle install
35
+ ```
36
+
37
+ ### 2. Create the Database Table
38
+
39
+ Generate and run the `hooktrace_events` migration:
40
+
41
+ ```bash
42
+ rails generate hooktrace:install
43
+ rails db:migrate
44
+ ```
45
+
46
+ Once `hooktrace_events` exists, `Hooktrace.store` automatically selects `Hooktrace::Storage::ActiveRecordStore`.
47
+
48
+ ### 3. Mount the Dashboard (`config/routes.rb`)
49
+
50
+ ```ruby
51
+ Rails.application.routes.draw do
52
+ mount Hooktrace::Web => "/hooktrace"
53
+ end
54
+ ```
55
+
56
+ ### 4. Validate Incoming Real Webhooks in Your Controller
57
+
58
+ Pass the raw request body (or parsed Hash) and headers to `Hooktrace.process_webhook`. Validation and database recording happen automatically—no manual `store.save` needed:
59
+
60
+ ```ruby
61
+ class WebhooksController < ApplicationController
62
+ skip_before_action :verify_authenticity_token
63
+
64
+ def stripe
65
+ event = Stripe::Webhook.construct_event(
66
+ request.raw_post,
67
+ request.env["HTTP_STRIPE_SIGNATURE"],
68
+ ENV["STRIPE_WEBHOOK_SECRET"]
69
+ )
70
+ payload = JSON.parse(event.to_json)
71
+
72
+ outcome = Hooktrace.process_webhook(payload, headers: request.headers.to_h, provider: "stripe")
73
+ render json: outcome.to_h, status: outcome.valid? ? :ok : :unprocessable_entity
74
+ end
75
+
76
+ def paypal
77
+ outcome = Hooktrace.process_webhook(request.raw_post, headers: request.headers.to_h, provider: "paypal")
78
+ render json: outcome.to_h, status: :ok
79
+ rescue Hooktrace::InvalidPayloadError => e
80
+ render json: { error: e.message }, status: :bad_request
81
+ end
82
+ end
83
+ ```
84
+
85
+ You can also validate against specific contract name(s) directly:
86
+
87
+ ```ruby
88
+ # Validates & auto-saves one event record into hooktrace_events
89
+ result = Hooktrace.validate(["stripe.event.base", "stripe.charge.succeeded"], payload)
90
+
91
+ result.valid? # => true / false
92
+ result.errors # => Array<Hooktrace::Error>
93
+ ```
94
+
95
+ *(Pass `record: false` or set `Hooktrace.auto_record = false` to skip persistence.)*
96
+
97
+ Open **`http://localhost:3000/hooktrace`** to view live stats, captured payloads, violation details, and active contracts.
98
+
99
+ ---
100
+
101
+ ## Overriding Contracts in `config/initializers/hooktrace.rb`
102
+
103
+ You do **not** need an initializer for default behavior, because built-in contracts and `ActiveRecordStore` configure themselves automatically.
104
+
105
+ If your app needs custom rules on top of a built-in OpenAPI contract, add `config/initializers/hooktrace.rb`:
106
+
107
+ ```ruby
108
+ require "hooktrace"
109
+
110
+ Hooktrace.configure do |config|
111
+ # Partially override a built-in OpenAPI contract
112
+ config.override("stripe.charge.succeeded") do
113
+ object :data do
114
+ object :object do
115
+ required :customer, type: :string, nullable: false # tighten existing field
116
+ optional :tenant_id, type: :string # add app-specific field
117
+ remove :statement_descriptor_suffix # ignore an unneeded field
118
+ end
119
+ end
120
+ end
121
+
122
+ # Or define a brand-new custom contract
123
+ config.define("custom.order.created") do
124
+ required :id, type: :string
125
+ required :amount, type: :integer
126
+ end
127
+
128
+ # Or load custom JSON bundles from a folder
129
+ # config.contracts_path = Rails.root.join("config", "contracts")
130
+ end
131
+ ```
132
+
133
+ ---
134
+
135
+ ## Syncing Updated OpenAPI Contracts
136
+
137
+ When Stripe or PayPal updates their webhook schemas, refresh your contracts using the CLI or Ruby API:
138
+
139
+ ```bash
140
+ # Sync core Stripe & PayPal contracts into lib/hooktrace/contracts/
141
+ hooktrace sync all
142
+
143
+ # Sync only Stripe (use --all for all 275+ Stripe events)
144
+ hooktrace sync stripe
145
+ hooktrace sync stripe --all --output config/contracts/stripe.json
146
+
147
+ # Sync only PayPal
148
+ hooktrace sync paypal --output config/contracts/paypal.json
149
+ ```
150
+
151
+ Or in Ruby:
152
+
153
+ ```ruby
154
+ Hooktrace.sync_contracts!(:stripe, output: Rails.root.join("config/contracts/stripe.json"))
155
+ Hooktrace.sync_contracts!(:paypal, output: Rails.root.join("config/contracts/paypal.json"))
156
+ ```
157
+
158
+ ### Validate a Payload via CLI
159
+
160
+ ```bash
161
+ hooktrace validate --contract path/to/contract.json --payload path/to/payload.json
162
+ ```
163
+
164
+ Exit codes: `0` (valid / success), `1` (validation failure), `2` (invalid arguments), `3` (runtime error).
165
+
166
+ ---
167
+
168
+ ## Changelog
169
+
170
+ See [CHANGELOG.md](CHANGELOG.md) for the full release history. Highlights of recent additions:
171
+
172
+ - **OpenAPI Importers (`StripeOpenApi`, `PaypalOpenApi`):** Auto-sync built-in contracts from official Stripe & PayPal OpenAPI specs via `hooktrace sync`.
173
+ - **Automatic Webhook Matching (`Hooktrace.process_webhook`):** Auto-detect Stripe/PayPal webhooks, match base + event contracts, validate, and record in one call.
174
+ - **Database Persistence (`ActiveRecordStore`):** Added `rails generate hooktrace:install` for the `hooktrace_events` table with auto-detection.
175
+ - **Initializer Override DSL:** Added `Hooktrace.configure` and `Hooktrace.override` to customize built-in schemas per app.
176
+ - **ERB Web Dashboard:** Refactored `Hooktrace::Web` HTML and CSS into modular templates under `lib/hooktrace/web/`.
177
+
178
+ ---
179
+
180
+ ## Development
181
+
182
+ ```bash
183
+ bin/setup
184
+ bundle exec rspec
185
+ bundle exec rubocop
186
+ ```
187
+
188
+ ## License
189
+
190
+ The gem is available as open source under the terms of the [MIT License](LICENSE.txt).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+ require "rubocop/rake_task"
6
+
7
+ RSpec::Core::RakeTask.new(:spec)
8
+ RuboCop::RakeTask.new
9
+
10
+ task default: %i[spec rubocop]
data/exe/hooktrace ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ $LOAD_PATH.unshift(File.expand_path("../lib", __dir__)) unless $LOAD_PATH.include?(File.expand_path("../lib", __dir__))
5
+
6
+ require "hooktrace"
7
+ require "hooktrace/cli"
8
+
9
+ exit(Hooktrace::CLI.run(ARGV))
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+ require "rails/generators/active_record"
5
+
6
+ module Hooktrace
7
+ module Generators
8
+ class InstallGenerator < ::Rails::Generators::Base
9
+ include ::ActiveRecord::Generators::Migration
10
+
11
+ source_root File.expand_path("templates", __dir__)
12
+ desc "Creates the hooktrace_events migration for Hooktrace database storage."
13
+
14
+ def copy_migration
15
+ migration_template(
16
+ "create_hooktrace_events.rb.erb",
17
+ "db/migrate/create_hooktrace_events.rb",
18
+ migration_version: migration_version
19
+ )
20
+ end
21
+
22
+ private
23
+
24
+ def migration_version
25
+ "#{::ActiveRecord::VERSION::MAJOR}.#{::ActiveRecord::VERSION::MINOR}"
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ class CreateHooktraceEvents < ActiveRecord::Migration[<%= migration_version %>]
4
+ def change
5
+ create_table :hooktrace_events do |t|
6
+ t.string :event_id, null: false
7
+ t.string :event_type, null: false
8
+ t.string :provider, null: false
9
+ t.boolean :valid_event, null: false, default: false
10
+ t.integer :error_count, null: false, default: 0
11
+ t.json :validation_errors
12
+ t.json :payload
13
+ t.datetime :received_at, null: false
14
+
15
+ t.timestamps
16
+ end
17
+
18
+ add_index :hooktrace_events, :event_id, unique: true
19
+ add_index :hooktrace_events, :event_type
20
+ add_index :hooktrace_events, :provider
21
+ add_index :hooktrace_events, :valid_event
22
+ add_index :hooktrace_events, :received_at
23
+ end
24
+ end
25
+
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+ require "json"
5
+ require_relative "../hooktrace"
6
+
7
+ module Hooktrace
8
+ class CLI
9
+ EXIT_SUCCESS = 0
10
+ EXIT_FAILURE = 1
11
+ EXIT_USAGE_ERROR = 2
12
+ EXIT_RUNTIME_ERROR = 3
13
+
14
+ def self.run(argv)
15
+ new.run(argv)
16
+ end
17
+
18
+ def run(argv)
19
+ command = argv.shift
20
+ case command
21
+ when "validate" then run_validate(argv)
22
+ when "sync" then run_sync(argv)
23
+ when "-v", "--version"
24
+ puts "Hooktrace version #{Hooktrace::VERSION}"
25
+ EXIT_SUCCESS
26
+ when "-h", "--help", nil
27
+ print_help
28
+ command.nil? ? EXIT_USAGE_ERROR : EXIT_SUCCESS
29
+ else
30
+ warn "Unknown command: #{command}"
31
+ print_help
32
+ EXIT_USAGE_ERROR
33
+ end
34
+ rescue ArgumentError => e
35
+ warn "Argument error: #{e.message}"
36
+ EXIT_USAGE_ERROR
37
+ rescue StandardError => e
38
+ warn "Error: #{e.message}"
39
+ EXIT_RUNTIME_ERROR
40
+ end
41
+
42
+ private
43
+
44
+ def run_validate(argv)
45
+ options = parse_validate_options(argv)
46
+ contract = load_contract(options[:contract])
47
+ payload = load_json(options[:payload])
48
+ result = contract.validate(payload, strict: options[:strict])
49
+
50
+ render_validate_result(result, contract, options[:json])
51
+ result.valid? ? EXIT_SUCCESS : EXIT_FAILURE
52
+ end
53
+
54
+ def parse_validate_options(argv)
55
+ options = { strict: false, json: false }
56
+ parser = OptionParser.new do |opts|
57
+ opts.banner = "Usage: hooktrace validate --contract <path> --payload <path> [options]"
58
+ opts.on("-c", "--contract PATH", "Path to contract JSON file") { |v| options[:contract] = v }
59
+ opts.on("-p", "--payload PATH", "Path to payload JSON file") { |v| options[:payload] = v }
60
+ opts.on("-s", "--strict", "Disallow unknown fields") { options[:strict] = true }
61
+ opts.on("-j", "--json", "Output results in JSON format") { options[:json] = true }
62
+ end
63
+ parser.parse!(argv)
64
+ validate_required_options!(options, %i[contract payload], parser)
65
+ options
66
+ end
67
+
68
+ def render_validate_result(result, contract, json_output)
69
+ if json_output
70
+ puts result.to_json
71
+ elsif result.valid?
72
+ puts "✓ Payload is valid according to contract '#{contract.name}'"
73
+ else
74
+ warn "✗ Validation failed for contract '#{contract.name}' with #{result.errors.size} error(s):"
75
+ result.errors.each { |err| warn " - #{err.path}: [#{err.code}] #{err.message}" }
76
+ end
77
+ end
78
+
79
+ def run_sync(argv)
80
+ options = parse_sync_options(argv)
81
+ provider = argv.first || "all"
82
+ result = Hooktrace.sync_contracts!(
83
+ provider,
84
+ output: options[:output],
85
+ events: options[:all] ? :all : nil,
86
+ spec_source: options[:spec]
87
+ )
88
+ if provider == "all"
89
+ result.each do |name, bundle|
90
+ puts "✓ Synced #{bundle["events"].size} contract(s) for '#{name}' (API #{bundle["api_version"]})"
91
+ end
92
+ else
93
+ puts "✓ Synced #{result["events"].size} contract(s) for '#{provider}' (API #{result["api_version"]})"
94
+ end
95
+ EXIT_SUCCESS
96
+ end
97
+
98
+ def parse_sync_options(argv)
99
+ options = { all: false }
100
+ parser = OptionParser.new do |opts|
101
+ opts.banner = "Usage: hooktrace sync [provider] [options]"
102
+ opts.on("-a", "--all", "Sync all events instead of core events only") { options[:all] = true }
103
+ opts.on("-o", "--output PATH", "Output JSON file path") { |v| options[:output] = v }
104
+ opts.on("-s", "--spec SOURCE", "Custom OpenAPI spec URL or file path") { |v| options[:spec] = v }
105
+ end
106
+ parser.parse!(argv)
107
+ options
108
+ end
109
+
110
+ def load_contract(path)
111
+ Contract.from_json(File.read(path, encoding: "UTF-8"))
112
+ end
113
+
114
+ def load_json(path)
115
+ JSON.parse(File.read(path, encoding: "UTF-8"))
116
+ end
117
+
118
+ def validate_required_options!(options, required_keys, parser)
119
+ missing = required_keys.select { |k| options[k].nil? }
120
+ return if missing.empty?
121
+
122
+ warn "Missing required options: #{missing.map { |m| "--#{m}" }.join(", ")}"
123
+ warn parser.banner
124
+ raise ArgumentError, "Missing required options"
125
+ end
126
+
127
+ def print_help
128
+ puts <<~HELP
129
+ Hooktrace #{Hooktrace::VERSION} — Webhook contract validation & OpenAPI sync
130
+
131
+ Usage:
132
+ hooktrace validate --contract <path> --payload <path> [--strict] [--json]
133
+ hooktrace sync [stripe|paypal|all] [--all] [--output PATH] [--spec URL_OR_PATH]
134
+ hooktrace --version
135
+ hooktrace --help
136
+ HELP
137
+ end
138
+ end
139
+ end