onlinewebdirectory-site 1.0.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: ca0907398d590e8d2e1418e999cfd2424e172a411024cbad64183460d805d26a
4
+ data.tar.gz: bc6508363f25f5c2953a9435d2a67dbeaa05f511de005f44979b82d1d009ab9a
5
+ SHA512:
6
+ metadata.gz: 9a0ebd13559dcc3f0fc4ec8adde0385e7a0d58ff619f0c9da2524787f6d940efe75f7a97c62981ea729c5de35ac109f4a4b22fa1c49ecfb507fc42f0d82e3451
7
+ data.tar.gz: 6528121c9d781216d9f654036e3628b4ed64ad501d697789caf7395e21071c6cdf74d72f9db24115e904e21f9c9281584e077c0f102344b1e6b8b3008e6df703
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Online Web Directory
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,194 @@
1
+ # Online Web Directory for Ruby sites
2
+
3
+ See whether AI agents can get into your site, confirm your free directory listing, and count the AI agents that request your pages.
4
+
5
+ Online Web Directory is where AI agents look a website up before they fetch it. This gem connects a site built on Rails, Sinatra or any other Rack framework to the directory.
6
+
7
+ It has no dependencies: it uses only what ships with Ruby. Ruby 2.7 or newer.
8
+
9
+ ## Free
10
+
11
+ - Pass or fail: can an AI agent with a plain web client get into your site? Plus a readiness score out of 100 and the date it was checked.
12
+ - Confirm your free listing from the command line, with no email round trip. Tell agents what your site is, in your own words.
13
+ - A count of requests from AI agents and crawlers (GPTBot, ClaudeBot, PerplexityBot and others), counted on your own server.
14
+ - A directory badge you can place in a view. It is never shown unless you place it.
15
+
16
+ ## Paid, bought from the command line
17
+
18
+ - Monitor: which agents came, which pages they asked for and the count for each day. A daily check, and an email when the result changes. You can ask for a fresh look after you change your site with `recheck`.
19
+ - Fix report: every point behind your score, what was found, why it matters and how to fix it. Where this gem can help with the fix (robots.txt lines for AI bots, an llms.txt made from your pages) the report says so.
20
+
21
+ Prices come from the service and are shown by `status` before you pay. Payment is by card on a secure payment page.
22
+
23
+ ## Install
24
+
25
+ ```ruby
26
+ gem "onlinewebdirectory-site"
27
+ ```
28
+
29
+ ## Connect your site
30
+
31
+ Run these where your site's code lives. Replace YOUR-DOMAIN with your site's address.
32
+
33
+ ```
34
+ bundle exec owd-site connect YOUR-DOMAIN
35
+ ```
36
+
37
+ This saves a proof and its secret in `.owd-site.json` and prints one line, `OWD_SITE_PROOF=...`. If your site runs somewhere else, set that line in its environment and deploy. The middleware then answers `/.well-known/owd-site.txt` with the proof. The proof works for one hour.
38
+
39
+ ```
40
+ bundle exec owd-site verify
41
+ ```
42
+
43
+ The service reads the proof file once and gives you a key. `verify` prints `OWD_SITE_KEY=...` one time: set it in the environment where your site runs. It also saves the key in `.owd-site.json` and removes the proof and secret from it. You can then remove `OWD_SITE_PROOF`. Do not run `verify` in a loop: the service rations it.
44
+
45
+ The proof file has to open at the top of your domain. A site that lives in a sub-folder cannot connect yet.
46
+
47
+ ### Keep `.owd-site.json` private
48
+
49
+ The file is made with mode 0600. It holds your key. Add it to `.gitignore` and never put it in version control. Set `OWD_SITE_FILE` to keep it somewhere else.
50
+
51
+ ## Settings
52
+
53
+ | Environment | What it is |
54
+ | --- | --- |
55
+ | `OWD_SITE_KEY` | Your site key. When it is not set, the key is read from `.owd-site.json`. |
56
+ | `OWD_SITE_PROOF` | The proof to serve while you connect. When it is not set, the proof is read from `.owd-site.json`. |
57
+ | `OWD_SITE_FILE` | Where `.owd-site.json` is kept. Default: the folder the process starts in. |
58
+ | `OWD_API` | The service address. Default: `https://onlinewebdirectory.net`. |
59
+
60
+ ## Add the middleware
61
+
62
+ ### Rails
63
+
64
+ In `config/application.rb`:
65
+
66
+ ```ruby
67
+ config.middleware.insert_before 0, OnlineWebDirectory::Site::Middleware, skip: ["/assets/", "/rails/"]
68
+ ```
69
+
70
+ Putting it first lets it answer the proof file before anything else and count requests that Rails later redirects.
71
+
72
+ ### Sinatra
73
+
74
+ ```ruby
75
+ require "sinatra"
76
+ require "onlinewebdirectory/site"
77
+
78
+ use OnlineWebDirectory::Site::Middleware
79
+ ```
80
+
81
+ ### Any Rack app (`config.ru`)
82
+
83
+ ```ruby
84
+ require "onlinewebdirectory/site"
85
+
86
+ use OnlineWebDirectory::Site::Middleware
87
+ run MyApp
88
+ ```
89
+
90
+ ### What the middleware does
91
+
92
+ - Answers `/.well-known/owd-site.txt` with the proof as `text/plain`, only while a proof is set.
93
+ - Counts a request when its user agent contains one of the agent words the service lists. It keeps the agent's name, the page path without the query string, and the day (UTC). Nothing else.
94
+ - Holds the counts in memory, one table per process, at most 500 rows. Past that, new pages are counted together as `(other pages)`.
95
+ - Hands the counts to the service about once an hour, from a background thread, in calls of at most 200 rows. A call that fails is sent again later under the same batch id, so it is never counted twice. It also hands them over when the process stops.
96
+ - Counts nothing when no key is set.
97
+ - Never blocks or breaks a request. Every failure in counting is swallowed.
98
+
99
+ Options, all optional: `skip:` (path beginnings that are never counted), `every:` (seconds between hand-overs, default 3600), `flush_on_exit:` (default `true`), and the llms.txt options below.
100
+
101
+ ## The badge
102
+
103
+ The badge is a small picture that links to your site's page in the directory. It is never shown automatically. Place it where you choose, for example in a Rails layout:
104
+
105
+ ```erb
106
+ <%= raw OnlineWebDirectory::Site.badge_html %>
107
+ ```
108
+
109
+ The HTML is cut down to exactly one link holding one image, https only. It is `""` until your listing is live. `badge_html` uses what the service last said and never calls the service, so it cannot slow a page down. To make it yourself from a site answer, call `OnlineWebDirectory::Site::Badge.html(site)`.
110
+
111
+ When the badge is on your home page, run `owd-site badge`. The service looks for it and says whether it was found.
112
+
113
+ ## llms.txt and robots.txt (optional, off by default)
114
+
115
+ To answer `/llms.txt`, give the middleware your own text or a list of your public pages:
116
+
117
+ ```ruby
118
+ use OnlineWebDirectory::Site::Middleware,
119
+ site_name: "My shop",
120
+ site_about: "Hand-made candles, posted worldwide.",
121
+ llms_pages: [
122
+ { title: "Home", url: "https://YOUR-DOMAIN/" },
123
+ { title: "Delivery", url: "https://YOUR-DOMAIN/delivery", about: "Costs and times." }
124
+ ]
125
+ ```
126
+
127
+ or `llms_text: "..."` for your own words. Remove the option to switch it off again. If your site already has a real `/llms.txt`, leave these options out.
128
+
129
+ To let named AI bots in, add lines to your own robots.txt:
130
+
131
+ ```ruby
132
+ files = OnlineWebDirectory::Site::Files
133
+ client = OnlineWebDirectory::Site::Client.new
134
+
135
+ puts files.robots_lines(files.robots_bots(client.report)) # the bots your fix report names
136
+ puts files.robots_lines(%w[GPTBot ClaudeBot]) # or bots you choose
137
+ ```
138
+
139
+ This gem does not change your files. You add the lines and you can take them out again.
140
+
141
+ ## Command line
142
+
143
+ ```
144
+ owd-site connect YOUR-DOMAIN
145
+ owd-site verify [--platform rails]
146
+ owd-site status
147
+ owd-site listing --email you@YOUR-DOMAIN --name "My shop" --about "Hand-made candles, posted worldwide." --kind shop [--contact hello@YOUR-DOMAIN]
148
+ owd-site visits
149
+ owd-site buy monitor --email you@YOUR-DOMAIN
150
+ owd-site buy report --email you@YOUR-DOMAIN
151
+ owd-site report
152
+ owd-site recheck
153
+ owd-site badge
154
+ ```
155
+
156
+ - `status` shows pass or fail, the score, the date checked, your listing, what is paid and the prices. After the result it shows what to do next, in the service's own words, with the command or the page for each step.
157
+ - `listing` needs `--email` the first time only. Give `--name`, `--about` and `--kind` every time: the listing is saved as you send it. `--kind` is one of the kinds the service lists. `--contact` is optional: an email address at your domain or an https page on it.
158
+ - `buy` prints the address of the payment page. Open it in your browser to pay by card.
159
+ - `badge` asks the service to look for the badge on your home page, at most once every ten minutes. Once it is found, the link from your directory page to your site is a normal followed link.
160
+ - When the service refuses something, its own words are printed and the command exits with 1.
161
+
162
+ The same calls are on `OnlineWebDirectory::Site::Client` for your own code: `site`, `listing`, `visits`, `order`, `report`, `recheck`, `badge_check`. A refusal raises `OnlineWebDirectory::Site::Error` with the service's words in `message` and the status in `status`. When the service answers 401 the key is no longer valid: it is forgotten and you connect again.
163
+
164
+ ## External services
165
+
166
+ This gem connects to Online Web Directory (https://onlinewebdirectory.net), which provides the check, the listing and the reports. Nothing is sent until you run `connect`.
167
+
168
+ - When you connect: your site address is sent, and the service reads one proof file from your site (`/.well-known/owd-site.txt`) to confirm the request came from it. The name of the integration and its version are sent with it.
169
+ - When you run `status`, `visits`, `report` or `recheck`, and about once an hour while your site runs: the gem asks the service for your site's result, listing and counts, and for the list of agents to count.
170
+ - When you run `badge`: the service reads your home page once to look for the badge.
171
+ - When you save your listing: the name, description, kind of site, contact for agents and the email address you enter are sent.
172
+ - Once an hour: counts of requests from AI agents are sent. Each count holds the agent's name, the page path and the day. No IP address, no visitor data and nothing about people is collected or sent.
173
+ - When you buy something: the email address you enter is sent, and you are given the address of a payment page run by Stripe.
174
+
175
+ Terms: https://onlinewebdirectory.net/terms
176
+ Privacy: https://onlinewebdirectory.net/privacy
177
+
178
+ ## Questions
179
+
180
+ **Why is my count of AI agents lower than my server logs?** Requests answered before your application runs (a CDN, a full-page cache, static files served by the web server) never reach the middleware, so they are not counted. Requests that arrive in the first moments after a process starts, before the list of agents has been read, are not counted either.
181
+
182
+ **Does the badge add a link to my site without asking?** No. It appears only where you place it.
183
+
184
+ ## Licence
185
+
186
+ MIT. See `LICENSE`.
187
+
188
+ ## Tests
189
+
190
+ `test/e2e_test.rb` runs against a local copy of the service and refuses to run against the live one.
191
+
192
+ ## Changelog
193
+
194
+ 1.0.0: first release.
data/exe/owd-site ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+ $LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
3
+ require "onlinewebdirectory/site"
4
+
5
+ exit OnlineWebDirectory::Site::CLI.run(ARGV)
@@ -0,0 +1,61 @@
1
+ module OnlineWebDirectory
2
+ module Site
3
+ # The directory badge: a small picture that links to this site's page in the
4
+ # directory. Shown only where the owner puts it. Never shown automatically.
5
+ module Badge
6
+ LINK = %r{<a\b([^>]*)>(.*?)</a\s*>}im.freeze
7
+ IMAGE = /<img\b([^>]*)>/im.freeze
8
+ ATTRIBUTE = /([a-zA-Z][a-zA-Z0-9_:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/.freeze
9
+ HTTPS = %r{\Ahttps://[^\s"'<>\\]+\z}.freeze
10
+ ESCAPES = { "&" => "&amp;", "<" => "&lt;", ">" => "&gt;", '"' => "&quot;", "'" => "&#x27;" }.freeze
11
+ NAMED = { "amp" => "&", "lt" => "<", "gt" => ">", "quot" => '"', "apos" => "'" }.freeze
12
+
13
+ module_function
14
+
15
+ # Cuts badge HTML down to exactly one <a href> holding one <img src alt width height>.
16
+ # https only. Everything else is dropped. Returns "" when no safe badge is left.
17
+ def html(source)
18
+ source = source["badge"].is_a?(Hash) ? source["badge"]["html"] : nil if source.is_a?(Hash)
19
+ return "" unless source.is_a?(String) && !source.empty?
20
+
21
+ source.scan(LINK) do |link, inside|
22
+ href = attributes(link)["href"].to_s
23
+ image = inside[IMAGE, 1]
24
+ next unless image && href.match?(HTTPS)
25
+
26
+ found = attributes(image)
27
+ src = found["src"].to_s
28
+ next unless src.match?(HTTPS)
29
+
30
+ out = %(<a href="#{escape(href)}"><img src="#{escape(src)}" alt="#{escape(found["alt"].to_s)}")
31
+ %w[width height].each { |name| out += %( #{name}="#{found[name]}") if found[name].to_s.match?(/\A[0-9]{1,4}\z/) }
32
+ return "#{out}></a>"
33
+ end
34
+ ""
35
+ end
36
+
37
+ def attributes(text)
38
+ found = {}
39
+ text.to_s.scan(ATTRIBUTE) do |name, double, single, bare|
40
+ found[name.downcase] ||= unescape(double || single || bare || "").strip
41
+ end
42
+ found
43
+ end
44
+
45
+ def escape(text)
46
+ text.to_s.gsub(/[&<>"']/) { |char| ESCAPES[char] }
47
+ end
48
+
49
+ def unescape(text)
50
+ text.to_s.gsub(/&(?:#(\d{1,7})|#[xX]([0-9a-fA-F]{1,6})|([a-zA-Z]+));/) do
51
+ if Regexp.last_match(1) then [Regexp.last_match(1).to_i].pack("U")
52
+ elsif Regexp.last_match(2) then [Regexp.last_match(2).to_i(16)].pack("U")
53
+ else NAMED.fetch(Regexp.last_match(3).downcase, Regexp.last_match(0))
54
+ end
55
+ rescue RangeError
56
+ ""
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,238 @@
1
+ require "optparse"
2
+
3
+ module OnlineWebDirectory
4
+ module Site
5
+ # The command line: connect, verify, status, listing, visits, buy, report, recheck, badge.
6
+ module CLI
7
+ PROOF_PATH = "/.well-known/owd-site.txt".freeze
8
+ NAME = "owd-site".freeze
9
+ BADGE_WORDS = {
10
+ "found" => "We found the badge on your home page. The link from your directory page to your site is now a normal followed link.",
11
+ "wait" => "We looked a moment ago. Try again in ten minutes.",
12
+ "missing" => "We could not find the badge on your home page yet. If your site uses a page cache, clear it, then run this command again."
13
+ }.freeze
14
+ USAGE = <<~TEXT.freeze
15
+ Online Web Directory for your site, version #{VERSION}.
16
+
17
+ owd-site connect YOUR-DOMAIN start connecting a site
18
+ owd-site verify [--platform rails]
19
+ finish connecting, once the proof is being served
20
+ owd-site status pass or fail, score, date checked, what to do next, listing,
21
+ what is paid, prices
22
+ owd-site listing --email E --name N --about A --kind K [--contact C]
23
+ confirm or change the free listing
24
+ owd-site visits requests from AI agents
25
+ owd-site buy monitor|report --email E
26
+ open a payment page
27
+ owd-site report the fix report, once bought
28
+ owd-site recheck ask for a fresh look, with the monitor or the fix report
29
+ owd-site badge ask the service to look for the badge on your home page
30
+
31
+ --file PATH where the private file is kept (default ./.owd-site.json, or OWD_SITE_FILE)
32
+ TEXT
33
+
34
+ module_function
35
+
36
+ # A price in dollars, from the service's own cents.
37
+ def money(cents)
38
+ cents = cents.to_i
39
+ (cents % 100).zero? ? "$#{cents / 100}" : format("$%.2f", cents / 100.0)
40
+ end
41
+
42
+ def day(stamp)
43
+ stamp.to_s[0, 10].to_s
44
+ end
45
+
46
+ def score(value)
47
+ value.nil? ? "not checked yet" : "#{value} out of 100"
48
+ end
49
+
50
+ # What to do next: the service's own words, in the order given, and how to act on each from here.
51
+ def advice_lines(site)
52
+ advice = site["advice"].is_a?(Array) ? site["advice"].select { |item| item.is_a?(Hash) } : []
53
+ return [] if advice.empty?
54
+
55
+ out = ["", "What to do next"]
56
+ advice.each do |item|
57
+ how = case item["action"]
58
+ when "report", "monitor" then "#{NAME} buy #{item["action"]} --email <you@your-domain>"
59
+ when "claim" then item["url"].to_s
60
+ when "listing" then %(#{NAME} listing --email <you@your-domain> --name "<site name>" --about "<what it is>" --kind <kind>)
61
+ when "badge" then "place the HTML from badge_html on your home page, then run: #{NAME} badge"
62
+ else ""
63
+ end
64
+ out.push("", item["title"].to_s)
65
+ out << " #{item["body"]}" unless item["body"].to_s.empty?
66
+ out << " #{item["label"].to_s.empty? ? "" : "#{item["label"]}: "}#{how}" unless how.empty?
67
+ end
68
+ out << ""
69
+ end
70
+
71
+ # One plain line for what the badge check said.
72
+ def badge_line(answer)
73
+ found = answer.is_a?(Hash) ? answer["badge"] : nil
74
+ BADGE_WORDS[%w[found wait].include?(found) ? found : "missing"]
75
+ end
76
+
77
+ # What the service said, in plain words. The free facts are pass or fail, the score and the date.
78
+ # With advice, what to do next follows the free facts.
79
+ def status_lines(site, advice: false)
80
+ prices = site["prices"] || {}
81
+ paid = site["paid"] || {}
82
+ out = ["Site: #{site["host"]}"]
83
+ out << if site["pass"].nil?
84
+ "Can AI agents get in: not checked yet. A new site is looked at within minutes."
85
+ else
86
+ "Can AI agents get in: #{site["pass"] ? "pass" : "fail"}"
87
+ end
88
+ out << "Score: #{score(site["score"])}"
89
+ out << "Checked: #{day(site["checked_at"]).empty? ? "not yet" : day(site["checked_at"])}"
90
+ out.concat(advice_lines(site)) if advice
91
+ listing = site["listing"]
92
+ if listing
93
+ words = %(Listing: #{listing["live"] ? "live" : "not live yet"}, "#{listing["name"]}" (#{listing["kind"]}))
94
+ words += ", founding listing number #{listing["founding_number"]}" if listing["founding_number"]
95
+ out << words
96
+ else
97
+ out << "Listing: not confirmed yet. It is free. Run: listing --email ... --name ... --about ... --kind ..."
98
+ end
99
+ out << if paid["monitor"]
100
+ "Monitor: running#{paid["monitor_until"] ? " until #{day(paid["monitor_until"])}" : ""}"
101
+ else
102
+ "Monitor: not running. #{money(prices["monitor_cents"])} every #{prices["monitor_days"]} days. Run: buy monitor --email ..."
103
+ end
104
+ out << if paid["report"]
105
+ "Fix report: bought. Run: report"
106
+ else
107
+ "Fix report: not bought. #{money(prices["report_cents"])} once. Run: buy report --email ..."
108
+ end
109
+ if paid["verified"]
110
+ out << "Verified claim: yes"
111
+ elsif prices["claim"]
112
+ words = prices["claim_cents"].to_i.positive? ? "Verify #{site["host"]} for #{money(prices["claim_cents"])}" : "Verify this site"
113
+ out << "Verified claim: no. #{words}: #{prices["claim"]}"
114
+ end
115
+ out << "Directory page: #{site["page"]}" if site["page"]
116
+ out
117
+ end
118
+
119
+ def visits_lines(visits)
120
+ out = ["Requests from AI agents, last 7 days: #{visits["week"].to_i}",
121
+ "Requests from AI agents since #{visits["since"]}: #{visits["month"].to_i}"]
122
+ unless visits["detail"]
123
+ out << "Which agents came, which pages they asked for and the count for each day come with the monitor."
124
+ return out
125
+ end
126
+ [["By agent", "agents", "agent"], ["By page", "pages", "path"], ["By day", "days", "day"]].each do |title, name, label|
127
+ out.push("", "#{title}:")
128
+ Array(visits[name]).each { |row| out << " #{row["hits"].to_i} #{row[label]}" }
129
+ end
130
+ out
131
+ end
132
+
133
+ def report_lines(report)
134
+ first = report["score"].nil? ? "Your score is not known yet." : "Your score is #{report["score"]}."
135
+ first += " With every ordinary point fixed it would be #{report["within_reach"]}." unless report["within_reach"].nil?
136
+ out = [first, "Checked: #{day(report["checked_at"]).empty? ? "not yet" : day(report["checked_at"])}"]
137
+ Array(report["lines"]).each do |line|
138
+ out << ""
139
+ out << "[#{line["ok"] ? "ok " : "fix"}] #{line["title"] || line["key"]}: #{line["points"].to_i} of #{line["max"].to_i}#{line["optional"] ? " (optional)" : ""}"
140
+ [%w[Found found], %w[Why why], %w[Fix fix], %w[Sample sample]].each do |label, name|
141
+ out << " #{label}: #{line[name]}" unless line[name].to_s.empty?
142
+ end
143
+ apply = line["apply"] || {}
144
+ if apply["do"] == "robots_allow"
145
+ out << " This gem can make the lines for your robots.txt:"
146
+ Files.robots_lines(apply["bots"]).split("\n").each { |text| out << " #{text}" }
147
+ elsif apply["do"] == "llms_txt"
148
+ out << " This gem can answer /llms.txt for you. See llms.txt in the README."
149
+ end
150
+ end
151
+ out
152
+ end
153
+
154
+ def run(argv, out: $stdout, err: $stderr)
155
+ options = {}
156
+ parser = OptionParser.new do |opts|
157
+ opts.on("--file PATH") { |value| options[:file] = value }
158
+ %i[email name about kind contact platform].each do |name|
159
+ opts.on("--#{name} VALUE") { |value| options[name] = value }
160
+ end
161
+ end
162
+ begin
163
+ words = parser.parse(argv)
164
+ rescue OptionParser::ParseError => e
165
+ err.puts e.message
166
+ return 2
167
+ end
168
+ command = words.shift
169
+ store = Store.new(options[:file])
170
+ client = Client.new(store: store, platform: options[:platform] || "ruby")
171
+
172
+ case command
173
+ when "connect"
174
+ return usage(err) if words.empty?
175
+
176
+ offer = client.connect(words[0])
177
+ raise Error, Client::NO_ANSWER if offer["proof"].to_s.empty? || offer["secret"].to_s.empty?
178
+
179
+ store.update("host" => offer["host"] || Client.clean_host(words[0]), "proof" => offer["proof"], "secret" => offer["secret"])
180
+ out.puts "The proof and its secret are saved in #{store.path}. Keep that file private and out of version control."
181
+ out.puts "If your site runs somewhere else, set this line in its environment and deploy:"
182
+ out.puts ""
183
+ out.puts "OWD_SITE_PROOF=#{offer["proof"]}"
184
+ out.puts ""
185
+ out.puts "The proof must open at https://#{offer["host"]}#{offer["path"] || PROOF_PATH}. It works for one hour (until #{offer["expires_at"]})."
186
+ out.puts "Then run: verify"
187
+ when "verify"
188
+ saved = store.read
189
+ raise Error, "There is no connection to finish. Run connect first." if [saved["host"], saved["proof"], saved["secret"]].any? { |value| value.to_s.empty? }
190
+
191
+ answer = client.verify(saved["host"], saved["proof"], saved["secret"], platform: options[:platform])
192
+ store.update("key" => answer["key"], "proof" => nil, "secret" => nil)
193
+ out.puts "Connected. This is your site key. It is shown once. Set it in the environment where your site runs:"
194
+ out.puts ""
195
+ out.puts "OWD_SITE_KEY=#{answer["key"]}"
196
+ out.puts ""
197
+ out.puts "It is also saved in #{store.path}. You can now remove OWD_SITE_PROOF."
198
+ when "status"
199
+ out.puts status_lines(client.site(fresh: true), advice: true)
200
+ when "listing"
201
+ site = client.listing(email: options[:email], name: options[:name], about: options[:about], kind: options[:kind], contact: options[:contact])
202
+ out.puts "Listing saved."
203
+ out.puts status_lines(site)
204
+ when "visits"
205
+ out.puts visits_lines(client.visits)
206
+ when "buy"
207
+ return usage(err) unless %w[monitor report].include?(words[0]) && options[:email]
208
+
209
+ url = client.order(words[0], options[:email])
210
+ out.puts "Open this page to pay by card:"
211
+ out.puts url
212
+ when "report"
213
+ out.puts report_lines(client.report)
214
+ when "badge"
215
+ out.puts badge_line(client.badge_check)
216
+ when "recheck"
217
+ answer = client.recheck
218
+ out.puts "Score: #{score(answer["score"])}"
219
+ out.puts "Checked: #{day(answer["checked_at"]).empty? ? "not yet" : day(answer["checked_at"])}"
220
+ else
221
+ return usage(err)
222
+ end
223
+ 0
224
+ rescue Error => e
225
+ err.puts e.message
226
+ 1
227
+ rescue SystemCallError => e
228
+ err.puts "The private file could not be read or written: #{e.message}"
229
+ 1
230
+ end
231
+
232
+ def usage(err)
233
+ err.puts USAGE
234
+ 2
235
+ end
236
+ end
237
+ end
238
+ end
@@ -0,0 +1,202 @@
1
+ require "json"
2
+ require "net/http"
3
+ require "uri"
4
+
5
+ module OnlineWebDirectory
6
+ module Site
7
+ # A refusal. `message` holds the service's own words, `status` the HTTP status (0 when there was none).
8
+ class Error < StandardError
9
+ attr_reader :status
10
+
11
+ def initialize(message, status = 0)
12
+ super(message)
13
+ @status = status
14
+ end
15
+ end
16
+
17
+ # Talks to Online Web Directory. Nothing is sent until the owner connects the site.
18
+ class Client
19
+ DEFAULT_API = "https://onlinewebdirectory.net".freeze
20
+ UNREACHABLE = "Online Web Directory could not be reached. Try again in a moment.".freeze
21
+ NO_ANSWER = "Online Web Directory gave no answer. Try again in a moment.".freeze
22
+ NOT_CONNECTED = "This site is not connected yet. Run connect, then verify.".freeze
23
+ STATE_FOR = 600 # seconds the site's answer is kept
24
+
25
+ attr_accessor :api, :timeout, :platform
26
+ attr_reader :store
27
+
28
+ def initialize(api: nil, key: nil, store: nil, timeout: 20, platform: "ruby")
29
+ @api = (api || ENV["OWD_API"] || DEFAULT_API).sub(%r{/+\z}, "")
30
+ @store = store || Store.new
31
+ @timeout = timeout
32
+ @platform = platform
33
+ @given = key
34
+ @key = nil
35
+ @dead = nil
36
+ @looked_at = 0.0
37
+ @state = nil
38
+ @state_at = 0.0
39
+ @lock = Mutex.new
40
+ end
41
+
42
+ # The host as the directory names it: lower case, no scheme, no path, no www.
43
+ def self.clean_host(raw)
44
+ host = raw.to_s.strip.downcase
45
+ host = host.split("://", 2)[1].to_s if host.include?("://")
46
+ host = host.split(%r{[/?#]}, 2)[0].to_s
47
+ host.sub(/\Awww\./, "")
48
+ end
49
+
50
+ # --- the key -------------------------------------------------------
51
+
52
+ # The site key: OWD_SITE_KEY, else the local file. nil when there is none.
53
+ def key
54
+ return @key if @key
55
+ return nil if Time.now.to_f - @looked_at < 30
56
+
57
+ reload
58
+ end
59
+
60
+ # Looks for the key again now.
61
+ def reload
62
+ @looked_at = Time.now.to_f
63
+ @key = [@given, ENV["OWD_SITE_KEY"], @store.get("key")].find { |found| found && !found.empty? && found != @dead }
64
+ end
65
+
66
+ # After a 401: the key is no longer valid, so it is dropped everywhere this gem keeps it.
67
+ def forget_key
68
+ @lock.synchronize do
69
+ dead = @key
70
+ @dead = dead || @dead
71
+ @key = nil
72
+ @state = nil
73
+ begin
74
+ @store.update("key" => nil) if dead && @store.get("key") == dead
75
+ rescue SystemCallError
76
+ nil
77
+ end
78
+ end
79
+ end
80
+
81
+ # --- one call ------------------------------------------------------
82
+
83
+ # One call. Returns the decoded body or raises Error carrying the service's own words.
84
+ def call(method, path, body = nil, keyed: true)
85
+ headers = {
86
+ "Accept" => "application/json",
87
+ "Content-Type" => "application/json",
88
+ "User-Agent" => "onlinewebdirectory-site-ruby/#{VERSION}"
89
+ }
90
+ if keyed
91
+ found = key
92
+ raise Error.new(NOT_CONNECTED, 0) unless found
93
+
94
+ headers["Authorization"] = "Bearer #{found}"
95
+ end
96
+ begin
97
+ uri = URI.parse("#{@api}/v1/#{path.sub(%r{\A/+}, "")}")
98
+ http = Net::HTTP.new(uri.host, uri.port)
99
+ http.use_ssl = uri.scheme == "https"
100
+ http.open_timeout = @timeout
101
+ http.read_timeout = @timeout
102
+ request = (method.to_s.upcase == "POST" ? Net::HTTP::Post : Net::HTTP::Get).new(uri.request_uri, headers)
103
+ request.body = JSON.generate(body) unless body.nil?
104
+ response = http.request(request)
105
+ status = response.code.to_i
106
+ raw = response.body.to_s
107
+ rescue StandardError
108
+ raise Error.new(UNREACHABLE, 0)
109
+ end
110
+ answer = begin
111
+ JSON.parse(raw)
112
+ rescue JSON::ParserError
113
+ nil
114
+ end
115
+ return answer if status >= 200 && status < 300 && answer.is_a?(Hash)
116
+
117
+ forget_key if status == 401 && keyed
118
+ words = answer.is_a?(Hash) ? answer["error"] : nil
119
+ raise Error.new(words && !words.to_s.empty? ? words.to_s : NO_ANSWER, status)
120
+ end
121
+
122
+ # --- joining -------------------------------------------------------
123
+
124
+ # Step one: asks for a proof to serve and a secret to keep.
125
+ def connect(host)
126
+ call("POST", "site/connect", { "host" => self.class.clean_host(host) }, keyed: false)
127
+ end
128
+
129
+ # Step two: the service reads the proof file once and hands back the key.
130
+ def verify(host, proof, secret, platform: nil, version: VERSION)
131
+ answer = call("POST", "site/verify",
132
+ { "host" => self.class.clean_host(host), "proof" => proof, "secret" => secret,
133
+ "platform" => platform || @platform, "version" => version }, keyed: false)
134
+ raise Error.new(NO_ANSWER, 0) if answer["key"].to_s.empty?
135
+
136
+ @dead = nil
137
+ @key = answer["key"].to_s
138
+ remember(answer["site"]) if answer["site"].is_a?(Hash)
139
+ answer
140
+ end
141
+
142
+ # --- the site ------------------------------------------------------
143
+
144
+ # What the service last said, without asking again. nil when nothing is known.
145
+ def last_site
146
+ @state
147
+ end
148
+
149
+ # The site as the service sees it, kept for ten minutes.
150
+ def site(fresh: false)
151
+ return @state if !fresh && @state && Time.now.to_f - @state_at < STATE_FOR
152
+
153
+ remember(call("GET", "site"))
154
+ end
155
+
156
+ # Saves the free listing. Returns the site.
157
+ def listing(email: nil, name: nil, about: nil, kind: nil, contact: nil)
158
+ body = { "email" => email, "name" => name, "about" => about, "kind" => kind, "contact" => contact }.compact
159
+ remember(call("POST", "site/listing", body))
160
+ end
161
+
162
+ # Hands over counts. Returns how many rows were counted.
163
+ def send_visits(day, batch, rows)
164
+ call("POST", "site/visits", { "day" => day, "batch" => batch, "rows" => rows })["counted"].to_i
165
+ end
166
+
167
+ def visits
168
+ call("GET", "site/visits")
169
+ end
170
+
171
+ # Opens a payment. Returns the page to pay on.
172
+ def order(kind, email)
173
+ call("POST", "site/orders", { "kind" => kind, "email" => email })["url"].to_s
174
+ end
175
+
176
+ def report
177
+ call("GET", "site/report")
178
+ end
179
+
180
+ def recheck
181
+ answer = call("POST", "site/recheck")
182
+ remember(answer["site"]) if answer["site"].is_a?(Hash)
183
+ answer
184
+ end
185
+
186
+ # Asks the service to look for the badge on the home page.
187
+ # Returns { "badge" => "found", "missing" or "wait", "site" => ... }.
188
+ def badge_check
189
+ answer = call("POST", "site/badge")
190
+ remember(answer["site"]) if answer["site"].is_a?(Hash)
191
+ answer
192
+ end
193
+
194
+ private
195
+
196
+ def remember(state)
197
+ @state_at = Time.now.to_f
198
+ @state = state
199
+ end
200
+ end
201
+ end
202
+ end
@@ -0,0 +1,55 @@
1
+ module OnlineWebDirectory
2
+ module Site
3
+ # The text this gem can answer for: an llms.txt made from the pages the owner
4
+ # names, and robots.txt lines that let the named AI bots in. Both are off
5
+ # until the owner switches them on. Nothing is written to disk.
6
+ module Files
7
+ module_function
8
+
9
+ # The lines that let each named bot in: `User-agent: X` / `Allow: /`.
10
+ def robots_lines(bots)
11
+ Array(bots).map { |bot| bot.to_s.gsub(/[^A-Za-z0-9._-]/, "") }.reject(&:empty?)
12
+ .map { |name| "User-agent: #{name}\nAllow: /" }.join("\n\n")
13
+ end
14
+
15
+ # The bots a fix report asks to let in (its `robots_allow` line), or [].
16
+ def robots_bots(report)
17
+ lines = report.is_a?(Hash) ? Array(report["lines"]) : []
18
+ lines.each do |line|
19
+ apply = line.is_a?(Hash) ? line["apply"] : nil
20
+ return Array(apply["bots"]).map(&:to_s) if apply.is_a?(Hash) && apply["do"] == "robots_allow"
21
+ end
22
+ []
23
+ end
24
+
25
+ # An llms.txt (see https://llmstxt.org) from the site's name, one line about it and its public pages.
26
+ # `pages` is a list of hashes with title, url and optionally about, or [title, url] pairs.
27
+ def llms_text(name, about = "", pages = [])
28
+ out = ["# #{plain(name).empty? ? "Site" : plain(name)}", ""]
29
+ out.push("> #{plain(about)}", "") unless plain(about).empty?
30
+ out.push("## Main pages", "")
31
+ Array(pages).each do |page|
32
+ if page.is_a?(Hash)
33
+ page = page.transform_keys(&:to_s)
34
+ out << line(page["title"], page["url"], page["about"])
35
+ else
36
+ out << line(*Array(page)[0, 3])
37
+ end
38
+ end
39
+ "#{out.join("\n")}\n"
40
+ end
41
+
42
+ def plain(text)
43
+ text.to_s.gsub(/<[^>]*>/, "").gsub(/\s+/, " ").strip
44
+ end
45
+
46
+ def line(title, url, about = "")
47
+ title = plain(title).tr("[]", " ").strip
48
+ url = url.to_s.gsub(/[\s()<>]/, "")
49
+ about = plain(about)
50
+ about = "#{about[0, 157].rstrip}..." if about.length > 160
51
+ "- [#{title.empty? ? url : title}](#{url})#{about.empty? ? "" : ": #{about}"}"
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,153 @@
1
+ module OnlineWebDirectory
2
+ module Site
3
+ # One site: the client, the counter and the few files this gem answers for.
4
+ # Framework-neutral. The Rack middleware is a thin wrapper around `handle`.
5
+ #
6
+ # Options, all optional:
7
+ # llms_text the whole llms.txt, in the owner's own words
8
+ # llms_pages a list of pages ({ title:, url:, about: }) to make an llms.txt from
9
+ # site_name the heading of a made llms.txt
10
+ # site_about one line under the heading
11
+ # skip path beginnings that are never counted, such as ["/assets/"]
12
+ # every seconds between hand-overs of the counts (default 3600)
13
+ # flush_on_exit hand the counts over when the process stops (default true)
14
+ class Handler
15
+ PROOF_PATH = "/.well-known/owd-site.txt".freeze
16
+ LLMS_PATH = "/llms.txt".freeze
17
+
18
+ attr_reader :client, :store, :visits
19
+
20
+ def initialize(client: nil, store: nil, llms_text: nil, llms_pages: nil, site_name: "", site_about: "",
21
+ skip: [], every: 3600, flush_on_exit: true)
22
+ @store = store || (client ? client.store : Store.new)
23
+ @client = client || Client.new(store: @store)
24
+ @visits = Visits.new(@client, every: every)
25
+ @own_llms = llms_text
26
+ @llms_pages = llms_pages
27
+ @site_name = site_name
28
+ @site_about = site_about
29
+ @skip = Array(skip)
30
+ @flag = Mutex.new
31
+ @working = false
32
+ @tried = 0.0
33
+ at_exit { goodbye } if flush_on_exit
34
+ end
35
+
36
+ # Reads the site now and takes the list of agents to count from it.
37
+ def refresh
38
+ state = @client.site(fresh: true)
39
+ @visits.agents = state["agents"]
40
+ state
41
+ end
42
+
43
+ # The badge for a view, from what the service last said. "" when there is none.
44
+ # It never calls the service, so it cannot slow a page down.
45
+ def badge_html
46
+ Badge.html(@client.last_site || {})
47
+ end
48
+
49
+ # The proof to serve while connecting: OWD_SITE_PROOF, else the local file.
50
+ def proof
51
+ (ENV["OWD_SITE_PROOF"].to_s.empty? ? @store.get("proof") : ENV["OWD_SITE_PROOF"]).to_s.strip
52
+ end
53
+
54
+ # The llms.txt text, or "" when the owner has not switched it on.
55
+ def llms
56
+ return @own_llms.to_s unless @own_llms.to_s.strip.empty?
57
+ return Files.llms_text(@site_name, @site_about, @llms_pages) if @llms_pages && !@llms_pages.empty?
58
+
59
+ ""
60
+ end
61
+
62
+ def robots_lines(bots)
63
+ Files.robots_lines(bots)
64
+ end
65
+
66
+ # Returns [status, headers, body] when this gem answers the request, else nil.
67
+ # A request that is not answered here is counted if an AI agent made it.
68
+ # Counting can never break the request: every failure is swallowed.
69
+ def handle(method, path, user_agent)
70
+ path = Visits.clean_path(path)
71
+ if %w[GET HEAD].include?(method.to_s.upcase)
72
+ if path == PROOF_PATH
73
+ found = proof
74
+ return found.empty? ? nil : text(found)
75
+ end
76
+ if path == LLMS_PATH
77
+ found = llms
78
+ return text(found) unless found.empty?
79
+ end
80
+ end
81
+ @visits.count(user_agent, path) unless @skip.any? { |start| path.start_with?(start.to_s) }
82
+ tick
83
+ nil
84
+ rescue StandardError
85
+ nil
86
+ end
87
+
88
+ # Hands the counts over now.
89
+ def flush
90
+ @visits.flush
91
+ end
92
+
93
+ private
94
+
95
+ def text(body)
96
+ body = body.to_s.dup.force_encoding("UTF-8")
97
+ [200, { "content-type" => "text/plain; charset=utf-8", "content-length" => body.bytesize.to_s,
98
+ "cache-control" => "no-store", "x-robots-tag" => "noindex" }, body]
99
+ end
100
+
101
+ # From the request path: starts a background thread when the agent list is
102
+ # missing or old, or when the counts are due. Never waits for it.
103
+ def tick
104
+ return unless @client.key
105
+
106
+ now = Time.now.to_f
107
+ stale = if @visits.agents_at.positive?
108
+ now - @visits.agents_at >= [@visits.every, 600].max
109
+ else
110
+ now - @tried >= 60
111
+ end
112
+ due = @visits.due?(now)
113
+ return unless stale || due
114
+
115
+ @flag.synchronize do
116
+ return if @working
117
+
118
+ @working = true
119
+ end
120
+ @tried = now
121
+ begin
122
+ Thread.new { work(due) }
123
+ rescue StandardError
124
+ @working = false
125
+ end
126
+ end
127
+
128
+ def work(due)
129
+ begin
130
+ refresh
131
+ rescue StandardError
132
+ nil
133
+ end
134
+ begin
135
+ @visits.flush if due
136
+ rescue StandardError
137
+ nil
138
+ end
139
+ ensure
140
+ @working = false
141
+ end
142
+
143
+ def goodbye
144
+ return if @visits.counts.empty? && @visits.pending.empty?
145
+
146
+ @client.timeout = [@client.timeout, 5].min
147
+ @visits.flush
148
+ rescue StandardError
149
+ nil
150
+ end
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,28 @@
1
+ module OnlineWebDirectory
2
+ module Site
3
+ # Rack middleware. Serves the proof file while the site connects, counts
4
+ # requests from AI agents, and optionally answers /llms.txt.
5
+ #
6
+ # use OnlineWebDirectory::Site::Middleware
7
+ class Middleware
8
+ attr_reader :site
9
+
10
+ def initialize(app, site: nil, **options)
11
+ @app = app
12
+ @site = site || (options.empty? ? Site.default : Handler.new(**options))
13
+ end
14
+
15
+ def call(env)
16
+ answer = begin
17
+ @site.handle(env["REQUEST_METHOD"], "#{env["SCRIPT_NAME"]}#{env["PATH_INFO"]}", env["HTTP_USER_AGENT"])
18
+ rescue StandardError
19
+ nil
20
+ end
21
+ return @app.call(env) unless answer
22
+
23
+ status, headers, body = answer
24
+ [status, headers, [env["REQUEST_METHOD"].to_s.upcase == "HEAD" ? "" : body]]
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,54 @@
1
+ require "json"
2
+ require "securerandom"
3
+
4
+ module OnlineWebDirectory
5
+ module Site
6
+ # The small private file that holds the proof, the secret and the key.
7
+ # It is made with mode 0600. Keep it out of version control.
8
+ class Store
9
+ FILE_NAME = ".owd-site.json".freeze
10
+
11
+ attr_reader :path
12
+
13
+ def initialize(path = nil)
14
+ @path = path || ENV["OWD_SITE_FILE"] || File.join(Dir.pwd, FILE_NAME)
15
+ end
16
+
17
+ def read
18
+ data = JSON.parse(File.read(@path, encoding: "UTF-8"))
19
+ data.is_a?(Hash) ? data : {}
20
+ rescue SystemCallError, JSON::ParserError
21
+ {}
22
+ end
23
+
24
+ def get(name)
25
+ value = read[name.to_s]
26
+ value.is_a?(String) && !value.empty? ? value : nil
27
+ end
28
+
29
+ # Sets the named values. A value of nil removes the name.
30
+ def update(changes)
31
+ data = read
32
+ changes.each do |name, value|
33
+ value.nil? ? data.delete(name.to_s) : data[name.to_s] = value
34
+ end
35
+ write(data)
36
+ data
37
+ end
38
+
39
+ def write(data)
40
+ temp = File.join(File.dirname(File.expand_path(@path)), ".owd-site.#{SecureRandom.hex(6)}")
41
+ begin
42
+ File.open(temp, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |out|
43
+ out.write(JSON.pretty_generate(data.sort.to_h))
44
+ out.write("\n")
45
+ end
46
+ File.chmod(0o600, temp)
47
+ File.rename(temp, @path)
48
+ ensure
49
+ File.unlink(temp) if File.exist?(temp)
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,5 @@
1
+ module OnlineWebDirectory
2
+ module Site
3
+ VERSION = "1.0.0".freeze
4
+ end
5
+ end
@@ -0,0 +1,130 @@
1
+ require "securerandom"
2
+
3
+ module OnlineWebDirectory
4
+ module Site
5
+ # Counts requests from AI agents and crawlers. Only the agent's name, the
6
+ # page path and the day are kept: no address, no visitor, nothing about people.
7
+ # One per process.
8
+ class Visits
9
+ MAX_ROWS = 500
10
+ PER_CALL = 200
11
+ OTHER = "(other pages)".freeze
12
+ PATH_LENGTH = 191
13
+
14
+ attr_reader :agents, :agents_at, :counts, :pending, :every
15
+ attr_accessor :last_flush
16
+
17
+ def self.utc_day(now = Time.now)
18
+ now.utc.strftime("%Y-%m-%d")
19
+ end
20
+
21
+ # The path only: no query string, so nothing a visitor typed is kept.
22
+ def self.clean_path(raw)
23
+ path = raw.to_s.dup.force_encoding("UTF-8").scrub("?").split(/[?#]/, 2)[0].to_s
24
+ (path.start_with?("/") ? path : "/")[0, PATH_LENGTH]
25
+ end
26
+
27
+ def initialize(client, every: 3600)
28
+ @client = client
29
+ @every = every
30
+ @agents = {}
31
+ @agents_at = 0.0
32
+ @counts = {}
33
+ @pending = []
34
+ @last_flush = Time.now.to_f
35
+ @lock = Mutex.new
36
+ @sending = Mutex.new
37
+ end
38
+
39
+ # Takes the `agents` map from the site: name to a lower-case word found in the user agent.
40
+ def agents=(map)
41
+ return unless map.is_a?(Hash)
42
+
43
+ @agents = map.each_with_object({}) { |(name, word), out| out[name.to_s] = word.to_s.downcase unless word.to_s.empty? }
44
+ @agents_at = Time.now.to_f
45
+ end
46
+
47
+ # The agent a user agent belongs to, or "" when it is not one we count.
48
+ def agent(user_agent)
49
+ return "" if user_agent.nil? || user_agent.empty? || @agents.empty?
50
+
51
+ text = user_agent.to_s.downcase
52
+ @agents.each { |name, word| return name if text.include?(word) }
53
+ ""
54
+ end
55
+
56
+ # Counts this request if an AI agent made it. Never counts when no key is set.
57
+ def count(user_agent, path, now = Time.now)
58
+ return false unless @client.key
59
+
60
+ name = agent(user_agent)
61
+ return false if name.empty?
62
+
63
+ day = self.class.utc_day(now)
64
+ row = [day, name, self.class.clean_path(path)]
65
+ @lock.synchronize do
66
+ # Past the cap, new pages are counted together, so nobody can grow
67
+ # the table by asking for made-up addresses.
68
+ row = [day, name, OTHER] if !@counts.key?(row) && @counts.size >= MAX_ROWS
69
+ @counts[row] = @counts.fetch(row, 0) + 1
70
+ end
71
+ true
72
+ end
73
+
74
+ # Whether it is time to hand the counts over: an hour has passed, or the table is full.
75
+ def due?(now = Time.now.to_f)
76
+ return false if @counts.empty? && @pending.empty?
77
+
78
+ waited = now - @last_flush
79
+ waited >= @every || (@counts.size >= MAX_ROWS && waited >= [600, @every].min)
80
+ end
81
+
82
+ # Hands the counts to the directory. A batch that did not arrive is sent
83
+ # again under the same name, so it is never counted twice.
84
+ def flush
85
+ result = { sent: 0, dropped: 0, kept: 0 }
86
+ return result unless @client.key && @sending.try_lock
87
+
88
+ begin
89
+ @last_flush = Time.now.to_f
90
+ waiting = @lock.synchronize do
91
+ cut if @pending.empty?
92
+ @pending.dup
93
+ end
94
+ waiting.each do |batch|
95
+ begin
96
+ @client.send_visits(batch["day"], batch["batch"], batch["rows"])
97
+ result[:sent] += 1
98
+ rescue Error => e
99
+ break unless e.status == 422 # anything else waits for the next hour
100
+
101
+ result[:dropped] += 1 # the service refused the batch itself
102
+ end
103
+ @lock.synchronize { @pending.delete_if { |other| other.equal?(batch) } }
104
+ end
105
+ result[:kept] = @pending.size
106
+ result
107
+ ensure
108
+ @sending.unlock
109
+ end
110
+ end
111
+
112
+ private
113
+
114
+ # Turns the counts into batches. Each batch gets a name once and keeps it until it is sent.
115
+ def cut
116
+ oldest = self.class.utc_day(Time.now - 2 * 86_400)
117
+ days = {}
118
+ @counts.each do |(day, agent, path), hits|
119
+ (days[day] ||= []) << { "agent" => agent, "path" => path, "hits" => hits } if day >= oldest
120
+ end
121
+ @counts = {}
122
+ days.keys.sort.each do |day|
123
+ days[day].sort_by { |row| -row["hits"] }.each_slice(PER_CALL) do |rows|
124
+ @pending << { "batch" => SecureRandom.uuid, "day" => day, "rows" => rows }
125
+ end
126
+ end
127
+ end
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,29 @@
1
+ # Online Web Directory for Ruby sites.
2
+ #
3
+ # See whether AI agents can get into your site, confirm your free directory
4
+ # listing, and count the AI agents that request your pages.
5
+ require_relative "site/version"
6
+ require_relative "site/store"
7
+ require_relative "site/client"
8
+ require_relative "site/visits"
9
+ require_relative "site/badge"
10
+ require_relative "site/files"
11
+ require_relative "site/handler"
12
+ require_relative "site/middleware"
13
+ require_relative "site/cli"
14
+
15
+ module OnlineWebDirectory
16
+ module Site
17
+ @default_lock = Mutex.new
18
+
19
+ # The one Handler shared by the middleware and the view helpers in this process.
20
+ def self.default
21
+ @default_lock.synchronize { @default ||= Handler.new }
22
+ end
23
+
24
+ # The badge for a view, from what the service last said. "" when there is none.
25
+ def self.badge_html
26
+ default.badge_html
27
+ end
28
+ end
29
+ end
metadata ADDED
@@ -0,0 +1,57 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: onlinewebdirectory-site
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Online Web Directory
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: See whether AI agents can get into your site, confirm your free directory
13
+ listing, and count the AI agents that request your pages. Rack middleware and a
14
+ command line. No dependencies.
15
+ executables:
16
+ - owd-site
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - exe/owd-site
23
+ - lib/onlinewebdirectory/site.rb
24
+ - lib/onlinewebdirectory/site/badge.rb
25
+ - lib/onlinewebdirectory/site/cli.rb
26
+ - lib/onlinewebdirectory/site/client.rb
27
+ - lib/onlinewebdirectory/site/files.rb
28
+ - lib/onlinewebdirectory/site/handler.rb
29
+ - lib/onlinewebdirectory/site/middleware.rb
30
+ - lib/onlinewebdirectory/site/store.rb
31
+ - lib/onlinewebdirectory/site/version.rb
32
+ - lib/onlinewebdirectory/site/visits.rb
33
+ homepage: https://onlinewebdirectory.net/
34
+ licenses:
35
+ - MIT
36
+ metadata:
37
+ homepage_uri: https://onlinewebdirectory.net/
38
+ source_code_uri: https://github.com/onlinewebdirectory/site-integrations/tree/main/ruby
39
+ documentation_uri: https://github.com/onlinewebdirectory/site-integrations/tree/main/ruby#readme
40
+ rdoc_options: []
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '2.7'
48
+ required_rubygems_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '0'
53
+ requirements: []
54
+ rubygems_version: 4.0.16
55
+ specification_version: 4
56
+ summary: Connect a Ruby site to Online Web Directory.
57
+ test_files: []