juggalo_icp 0.2.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: b3422958f8e54128b77818030f609f259a47c18a9051911b12ae9f46771b6c04
4
+ data.tar.gz: d995714cdbee15f24a027c3ddd87f448e436cc0557744e699eae2ba113769f65
5
+ SHA512:
6
+ metadata.gz: c14fa5a814e86f839103bc3dacb656c89be0a2adbbf72090fc79c91591ceecee362e5923cca1c5d9d052f708f1e68efbab082dc56ed4fffb2e3f628a4fe2105c
7
+ data.tar.gz: c7d7a90da6193f7d5ae3de86b92a6b2a4909c425423ed96300bed781474b1553685e5d4a725983b5eb51a037c758779d3059d03875ae54863af8585602f83497
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 the ruby_wasm_builder authors
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,139 @@
1
+ # juggalo_icp
2
+
3
+ Serve a [Rack](https://github.com/rack/rack) app from a Ruby canister on the
4
+ Internet Computer, through the IC HTTP gateway. For canisters packed by
5
+ [ruby_wasm_builder](https://gitlab.com/phrug/ruby_wasm_builder) from 0.7.0.
6
+
7
+ Pure Ruby, no dependencies. It works the same on the `minimal` and `full`
8
+ Builds: it names no standard library, no C extension and no `Encoding`
9
+ constant.
10
+
11
+ ## Carrying it
12
+
13
+ A canister has no `bundle install`. Carry the gem's files in your Application,
14
+ as you carry Rack:
15
+
16
+ ```bash
17
+ gem fetch juggalo_icp && gem unpack juggalo_icp-*.gem
18
+ cp -r juggalo_icp-*/lib my_app/vendor/juggalo_icp
19
+ ```
20
+
21
+ ```ruby
22
+ # app.rb
23
+ $LOAD_PATH.unshift(File.join(__dir__, "vendor/juggalo_icp"))
24
+ require "juggalo_icp"
25
+ ```
26
+
27
+ To move to a newer version, unpack it and copy its `lib/` again.
28
+
29
+ ## Declaring and serving the gateway's methods
30
+
31
+ From ruby_wasm_builder 0.8.0, one word in `ic-interface.rb` declares the
32
+ gateway's types and both methods:
33
+
34
+ ```ruby
35
+ # ic-interface.rb
36
+ http_gateway
37
+ ```
38
+
39
+ On 0.7.0, write them out (this is what the word declares):
40
+
41
+ ```ruby
42
+ type :HeaderField, Tuple[Text, Text]
43
+ type :HttpRequest, record(method: Text, url: Text, headers: Vec[:HeaderField], body: Blob,
44
+ certificate_version: Opt[Nat16])
45
+ type :HttpUpdateRequest, record(method: Text, url: Text, headers: Vec[:HeaderField], body: Blob)
46
+ type :HttpResponse, record(status_code: Nat16, headers: Vec[:HeaderField], body: Blob, upgrade: Opt[Bool])
47
+
48
+ query :http_request, takes: [:HttpRequest], returns: :HttpResponse
49
+ update :http_request_update, takes: [:HttpUpdateRequest], returns: :HttpResponse
50
+ ```
51
+
52
+ Then hand both to your app:
53
+
54
+ ```ruby
55
+ # app.rb
56
+ APP = ->(env) { [200, { "content-type" => "text/plain" }, ["hello from #{env['PATH_INFO']}"]] }
57
+
58
+ def http_request(req) = RubyWasmIcRack.query(APP, req)
59
+ def http_request_update(req) = RubyWasmIcRack.update(APP, req)
60
+ ```
61
+
62
+ ## What it does
63
+
64
+ - **The env:** `REQUEST_METHOD`, `PATH_INFO`, `QUERY_STRING`, every header as
65
+ `HTTP_*` (`CONTENT_TYPE` as Rack names it), a repeated header joined with
66
+ `, `, and `rack.input` over the body. The rest is built from what the
67
+ gateway actually hands the canister, not from what a client could write:
68
+ - `CONTENT_LENGTH` is the body's size in bytes, whatever `content-length`
69
+ the client sent or didn't send. A body arrives whole, and the gateway
70
+ passes `content-length` on only if the client set it. It's unset for an
71
+ empty body.
72
+ - `SERVER_NAME`, `SERVER_PORT` and `rack.url_scheme` come from `host`.
73
+ `localhost`, `*.localhost` and loopback (`127.0.0.1`, `[::1]`) give
74
+ `http` on the port written there, so `<id>.localhost:8000` builds full
75
+ URLs that work locally. Any other host gives `https` on 443.
76
+ `x-forwarded-proto` and `x-forwarded-port` are never read: no gateway
77
+ sets them, and the gateway's cache doesn't key on them.
78
+ - `REMOTE_ADDR` is `0.0.0.0`. No client address reaches a canister.
79
+ - **Client-written headers.** The gateway passes the client's headers on
80
+ unchanged, and adds no `x-forwarded-for`, `x-real-ip` or `forwarded`
81
+ of its own. If one arrives, the client wrote it. They reach the app as
82
+ `HTTP_*`, unchecked, so `request.remote_ip` in Rails (which prefers
83
+ `X-Forwarded-For`) is whatever the client says, or `0.0.0.0`. Don't key a
84
+ rate limit or an audit trail on it.
85
+ - **The response:** a header whose value is an Array, or lines joined by
86
+ `"\n"` (Rack 3), goes out as one header each, so two `set-cookie` headers
87
+ arrive as two. The body is joined and closed.
88
+ - **Upgrades.** The gateway calls `http_request` as a query, and a query keeps
89
+ nothing it writes. So `RubyWasmIcRack.query` answers only `GET`, `HEAD` and `OPTIONS`
90
+ and asks the gateway to upgrade everything else, which then calls
91
+ `http_request_update` through consensus. A `GET` that writes says so with the
92
+ response header `x-ic-upgrade` (any value); the query upgrades it, and the
93
+ header is never sent on.
94
+ - **`rack.input`** is a small reader of its own (`read`, `gets`, `each`,
95
+ `rewind`). For a `StringIO`, as Rack's own servers give, redefine
96
+ `RubyWasmIcRack.input`:
97
+
98
+ ```ruby
99
+ module RubyWasmIcRack
100
+ def self.input(bytes) = StringIO.new(bytes.b)
101
+ end
102
+ ```
103
+
104
+ ## On the `minimal` Build
105
+
106
+ Rack and Roda need four libraries `minimal` lacks: `Encoding::UTF_8` and its
107
+ two siblings, `date` (only because `time` requires it), `strscan` and
108
+ `stringio`. The [`ic_minimal`](../ic_minimal) gem carries pure-Ruby stand-ins
109
+ for them, for a `minimal` canister only. `juggalo_icp` itself needs none of them.
110
+
111
+ Carry only the files of Rack your routes load, and check every carried file's
112
+ magic comment: `minimal` knows only `utf-8`, `us-ascii` and `ascii-8bit` by
113
+ those names, and Rack 3.1's `rack/utils.rb` says `# encoding: binary`, which
114
+ traps the install. Change that word to `ascii-8bit`.
115
+
116
+ ## Not yet
117
+
118
+ - **Certified responses.** Until the canister certifies its replies, the
119
+ gateway refuses a plain query's reply on the certified domain
120
+ (`<id>.icp0.io`) and serves it on `<id>.raw.icp0.io`. An upgraded request is
121
+ served on either. So a public page is served raw, or by upgrading every
122
+ `GET` (one update per page view).
123
+ - File uploads (Tempfile) and streaming responses.
124
+
125
+ ## Development
126
+
127
+ ```bash
128
+ bundle install
129
+ bundle exec rake # the specs, on MRI, with no canister
130
+ ```
131
+
132
+ The specs build envs and responses from gateway records on MRI. What only a
133
+ canister behind a real gateway can show is played by
134
+ [ruby_wasm_builder](https://gitlab.com/phrug/ruby_wasm_builder)'s suite,
135
+ `spec/gems/juggalo_icp_spec.rb`. That spec installs the published gem
136
+ and plays the 0.7.0 `rack_adapter` and `roda_on_minimal` Scripts with its
137
+ `lib/` in place of the Challenges' own copies.
138
+
139
+ MIT licensed.
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyWasmIcRack
4
+ VERSION = "0.2.0"
5
+ end
@@ -0,0 +1,161 @@
1
+ # juggalo_icp: serves a Rack app (anything answering call(env) with
2
+ # [status, headers, body]) from the IC HTTP gateway's two methods, in a Ruby
3
+ # canister packed by ruby_wasm_builder. Pure Ruby with no dependency, the same
4
+ # on the `minimal` and `full` Builds: it names no standard library, no C
5
+ # extension and no Encoding constant. rack.input is a small reader of its own
6
+ # unless the Application redefines RubyWasmIcRack.input (a StringIO, say).
7
+ #
8
+ # Taken from the builder's 0.7.0 Challenges (rack_adapter, roda_on_minimal),
9
+ # which keep their own copies; this gem moves on its own versions.
10
+ #
11
+ # A query can't keep a write, so http_request answers only the safe methods
12
+ # (GET, HEAD, OPTIONS) and asks the gateway to upgrade everything else to
13
+ # http_request_update. An app whose GET writes says so with the response
14
+ # header `x-ic-upgrade`, and the query upgrades that too; the header is never
15
+ # sent on.
16
+ #
17
+ # The env is built from what the gateway hands over and nothing it doesn't
18
+ # vouch for (0.2.0). CONTENT_LENGTH is the body's own size, never a client's
19
+ # header. REMOTE_ADDR is "0.0.0.0", since no client address reaches a
20
+ # canister. The scheme and port come from `host` alone: http on the port
21
+ # written there (80 if none) for localhost, *.localhost and loopback; https on
22
+ # 443 otherwise, since a public gateway listens there and nowhere else. A client's x-forwarded-* is passed
23
+ # on as HTTP_X_FORWARDED_* but never read, because the gateway's cache keys on
24
+ # authority, path and query only.
25
+ require_relative "juggalo_icp/version"
26
+
27
+ module RubyWasmIcRack
28
+ SAFE = %w[GET HEAD OPTIONS].freeze
29
+ UPGRADE = "x-ic-upgrade"
30
+ # No client address reaches a canister: a valid address, trusted by no proxy
31
+ # list, that reads as unknown.
32
+ REMOTE_ADDR = "0.0.0.0"
33
+ LOOPBACK = %w[localhost 127.0.0.1 [::1]].freeze
34
+
35
+ # rack.input over the body's bytes: what Rack 3 asks of an input stream.
36
+ class Input
37
+ def initialize(bytes)
38
+ @bytes = bytes.b
39
+ @pos = 0
40
+ end
41
+
42
+ def read(length = nil, buffer = nil)
43
+ rest = @bytes.byteslice(@pos, @bytes.bytesize - @pos) || "".b
44
+ chunk = length ? rest.byteslice(0, length) : rest
45
+ @pos += chunk.bytesize
46
+ return nil if length && length.positive? && chunk.empty?
47
+
48
+ buffer ? buffer.replace(chunk) : chunk
49
+ end
50
+
51
+ def gets
52
+ return nil if @pos >= @bytes.bytesize
53
+
54
+ stop = @bytes.index("\n", @pos)
55
+ line = @bytes.byteslice(@pos, (stop ? stop + 1 : @bytes.bytesize) - @pos)
56
+ @pos += line.bytesize
57
+ line
58
+ end
59
+
60
+ def each
61
+ while (line = gets)
62
+ yield line
63
+ end
64
+ end
65
+
66
+ def rewind = @pos = 0
67
+ def close = nil
68
+ end
69
+
70
+ module_function
71
+
72
+ # rack.input over the body. An Application may redefine it (roda_on_minimal
73
+ # gives a StringIO).
74
+ def input(bytes) = Input.new(bytes)
75
+
76
+ def env(req)
77
+ path, query = req[:url].split("?", 2)
78
+ name, port = authority(header(req, "host").to_s)
79
+ local = local?(name)
80
+ scheme = local ? "http" : "https"
81
+ body = req[:body]
82
+ env = {
83
+ "REQUEST_METHOD" => req[:method],
84
+ "SCRIPT_NAME" => "",
85
+ "PATH_INFO" => path.to_s.empty? ? "/" : path,
86
+ "QUERY_STRING" => query.to_s,
87
+ "SERVER_NAME" => name,
88
+ "SERVER_PORT" => local ? port || "80" : "443",
89
+ "SERVER_PROTOCOL" => "HTTP/1.1",
90
+ "REMOTE_ADDR" => REMOTE_ADDR,
91
+ "rack.url_scheme" => scheme,
92
+ "rack.input" => input(body),
93
+ "rack.errors" => $stderr
94
+ }
95
+ req[:headers].each do |hname, value|
96
+ key = hname.upcase.tr("-", "_")
97
+ next if key == "CONTENT_LENGTH" # the body's bytes say, below
98
+
99
+ key = "HTTP_#{key}" unless key == "CONTENT_TYPE"
100
+ env[key] = env.key?(key) ? "#{env[key]}, #{value}" : value
101
+ end
102
+ env["CONTENT_LENGTH"] = body.bytesize.to_s unless body.empty?
103
+ env
104
+ end
105
+
106
+ # The name and the port (nil if none, or not digits) written in a `host`
107
+ # header. An IPv6 address keeps its brackets.
108
+ def authority(host)
109
+ if host.start_with?("[")
110
+ close = host.index("]") || (host.length - 1)
111
+ name = host[0..close]
112
+ rest = host[(close + 1)..].to_s
113
+ port = rest.start_with?(":") ? rest[1..] : nil
114
+ else
115
+ name, port = host.split(":", 2)
116
+ end
117
+ port = nil unless port && !port.empty? && port.each_char.all? { |c| c >= "0" && c <= "9" }
118
+ [name.to_s, port]
119
+ end
120
+
121
+ # A gateway on this machine (PocketIC's, or a local network's) speaks http.
122
+ def local?(name)
123
+ name = name.downcase
124
+ LOOPBACK.include?(name) || name.end_with?(".localhost")
125
+ end
126
+
127
+ def header(req, name) = req[:headers].find { |n, _| n.downcase == name }&.last
128
+
129
+ # The gateway's response record from a Rack response. A header's value may
130
+ # be an Array, or lines joined by "\n" (Rack 3): one header each.
131
+ def response(status, headers, body)
132
+ pairs = headers.flat_map do |name, value|
133
+ Array(value).flat_map { |v| v.to_s.split("\n") }.map { |v| [name.to_s.downcase, v] }
134
+ end
135
+ bytes = +"".b
136
+ body.each { |part| bytes << part.b }
137
+ { status_code: Integer(status), headers: pairs, body: bytes, upgrade: nil }
138
+ ensure
139
+ body.close if body.respond_to?(:close)
140
+ end
141
+
142
+ def upgrade = { status_code: 200, headers: [], body: "".b, upgrade: true }
143
+
144
+ # http_request: the query.
145
+ def query(app, req)
146
+ return upgrade unless SAFE.include?(req[:method])
147
+
148
+ status, headers, body = app.call(env(req))
149
+ if headers.keys.any? { |k| k.to_s.downcase == UPGRADE }
150
+ body.close if body.respond_to?(:close)
151
+ return upgrade
152
+ end
153
+ response(status, headers, body)
154
+ end
155
+
156
+ # http_request_update: the update, after an upgrade.
157
+ def update(app, req)
158
+ status, headers, body = app.call(env(req))
159
+ response(status, headers.reject { |k, _| k.to_s.downcase == UPGRADE }, body)
160
+ end
161
+ end
metadata ADDED
@@ -0,0 +1,45 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: juggalo_icp
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - graial
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Use this gem to run rack and roda on the ruby.wasm build for Internet
13
+ Computer.
14
+ email:
15
+ - graial@paglalayag.net
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - lib/juggalo_icp.rb
23
+ - lib/juggalo_icp/version.rb
24
+ homepage: https://github.com/graial/juggalo_icp
25
+ licenses:
26
+ - MIT
27
+ metadata: {}
28
+ rdoc_options: []
29
+ require_paths:
30
+ - lib
31
+ required_ruby_version: !ruby/object:Gem::Requirement
32
+ requirements:
33
+ - - ">="
34
+ - !ruby/object:Gem::Version
35
+ version: 3.3.3
36
+ required_rubygems_version: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ requirements: []
42
+ rubygems_version: 4.0.20
43
+ specification_version: 4
44
+ summary: Run rack and roda on the ruby.wasm build for IC!
45
+ test_files: []