@riebeckite/webmention-cloudflare 0.0.6

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright Rerurate_514
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,99 @@
1
+ # @riebeckite/webmention-cloudflare
2
+
3
+ Cloudflare Worker, D1, and KV runtime for
4
+ [`@riebeckite/plugin-webmention`](../../plugins/webmention/README.md). The generic
5
+ plugin defines the storage seam; this package owns bindings and storage.
6
+
7
+ [日本語](./README_ja.md)
8
+
9
+ ## Architecture
10
+
11
+ `d1Storage` / `kvStorage` implement the generic `WebmentionProvider` contract so
12
+ the same site can mount the plugin's `endpoints` inside its own Worker and pass
13
+ a binding-backed provider. `createWorker` is an optional standalone receiver
14
+ for a separate Worker deployment: it validates input, verifies that the source
15
+ links to the target, stores the mention, and serves the verified-mention feed.
16
+ D1 and KV live in infrastructure and are never imported by
17
+ `@riebeckite/plugin-webmention`.
18
+
19
+ ## Storage adapters
20
+
21
+ - **`D1WebmentionStorage`**: one row per verified `(source, target)` pair with
22
+ upsert on conflict. Supports `store` and `query` (per-target and all-mention
23
+ reads, with `?since=`). Targets are stored in canonical comparison form.
24
+ - **`KvWebmentionStorage`**: store-only. KV has no listing or atomic update, so
25
+ reads deliberately throw `UnsupportedWebmentionQueryError` (the Worker
26
+ returns `501`). KV keys are capped at 512 bytes; use D1 for long URLs.
27
+
28
+ There is no default adapter. Bind and construct exactly one per Worker.
29
+
30
+ ## Using the plugin on the site Worker
31
+
32
+ ```ts
33
+ import { webmention } from "@riebeckite/plugin-webmention";
34
+ import { d1Storage } from "@riebeckite/webmention-cloudflare";
35
+
36
+ export interface Env {
37
+ WEBMENTION_DB: D1Database;
38
+ }
39
+
40
+ export const config = defineConfig({
41
+ plugins: [webmention({ provider: d1Storage(env.WEBMENTION_DB) })],
42
+ });
43
+ ```
44
+
45
+ `mountRiebeckiteEndpoints` then mounts `POST /webmentions` and
46
+ `GET /webmentions`, and verified mentions render near articles at build time.
47
+
48
+ ## Standalone receiver
49
+
50
+ ```ts
51
+ import { createWorker, d1Storage } from "@riebeckite/webmention-cloudflare";
52
+
53
+ interface Env {
54
+ WEBMENTION_DB: D1Database;
55
+ }
56
+
57
+ export default {
58
+ fetch: (request: Request, env: Env) =>
59
+ createWorker({
60
+ storage: d1Storage(env.WEBMENTION_DB),
61
+ allowedTargets: ["https://www.example.com/"],
62
+ }).fetch(request),
63
+ };
64
+ ```
65
+
66
+ The standalone receiver knows only the targets in `allowedTargets`; it has no
67
+ content manifest, so feed entries carry no article summary. When the receiver
68
+ shares the site Worker, prefer the plugin's `endpoints` so mentions are matched
69
+ to published entries.
70
+
71
+ ## Endpoints and validation
72
+
73
+ - `POST /webmentions` accepts `source` and `target` as form-encoded or JSON
74
+ (8–64 KiB body cap), requires the target to be an allowed absolute URL, and
75
+ verifies the source links to it before storing. Responses: `202` accepted,
76
+ `400` with an `error` code, `503` when storage cannot write.
77
+ - `GET /webmentions?target=&limit=&since=` returns
78
+ `{ version, generatedAt, count, mentions }`. Requires storage with the
79
+ `query` capability, otherwise `501`.
80
+
81
+ The default source fetcher blocks loopback and private-network hosts, caps the
82
+ response size, and times out. Webmention senders are servers, so
83
+ `allowMissingOrigin` defaults to `true`; browser origins remain denied unless
84
+ explicitly listed.
85
+
86
+ ## D1 schema and deployment
87
+
88
+ Workers must not migrate D1 during a request. Apply the schema before
89
+ deploying:
90
+
91
+ ```sh
92
+ pnpm exec wrangler d1 execute WEBMENTION_DB --file node_modules/@riebeckite/webmention-cloudflare/migrations/0001_webmentions.sql
93
+ pnpm exec wrangler deploy
94
+ ```
95
+
96
+ ## See also
97
+
98
+ - [@riebeckite/plugin-webmention](../../plugins/webmention/README.md)
99
+ - [Analytics Cloudflare runtime](../analytics-cloudflare/README.md)
package/README_ja.md ADDED
@@ -0,0 +1,98 @@
1
+ # @riebeckite/webmention-cloudflare
2
+
3
+ [`@riebeckite/plugin-webmention`](../../plugins/webmention/README_ja.md) のための
4
+ Cloudflare Worker・D1・KV ランタイムです。汎用プラグインが storage の境界を定義し、
5
+ このパッケージがバインディングとストレージを所有します。
6
+
7
+ [English](./README.md)
8
+
9
+ ## アーキテクチャ
10
+
11
+ `d1Storage` / `kvStorage` は汎用 `WebmentionProvider` 契約を実装するため、同じ
12
+ サイトの Worker 内でプラグインの `endpoints` をマウントし、バインディング由来の
13
+ provider を渡せます。`createWorker` は別 Worker 配置向けの任意の単体レシーバーで、
14
+ 入力を検証し、送信元がターゲットへリンクしていることを確認し、メンションを保存して
15
+ 検証済みメンションのフィードを返します。D1 と KV は infrastructure にあり、
16
+ `@riebeckite/plugin-webmention` から import されることはありません。
17
+
18
+ ## ストレージ adapter
19
+
20
+ - **`D1WebmentionStorage`**: 検証済み `(source, target)` ペアごとに 1 行を保持し、
21
+ 競合時は upsert します。`store` と `query`(ターゲット別・全件、`?since=` 対応)を
22
+ サポートします。ターゲットは比較用の正規形で保存されます。
23
+ - **`KvWebmentionStorage`**: store 専用です。KV には一覧取得や原子的更新がないため、
24
+ 読み取りは意図的に `UnsupportedWebmentionQueryError` を投げ(Worker は `501`)、
25
+ `query` capability を公開しません。KV のキーは 512 バイト上限のため、長い URL には
26
+ D1 を使ってください。
27
+
28
+ 既定の adapter はありません。Worker ごとに 1 つを明示的に選んでください。
29
+
30
+ ## サイト Worker でプラグインを使う
31
+
32
+ ```ts
33
+ import { webmention } from "@riebeckite/plugin-webmention";
34
+ import { d1Storage } from "@riebeckite/webmention-cloudflare";
35
+
36
+ export interface Env {
37
+ WEBMENTION_DB: D1Database;
38
+ }
39
+
40
+ export const config = defineConfig({
41
+ plugins: [webmention({ provider: d1Storage(env.WEBMENTION_DB) })],
42
+ });
43
+ ```
44
+
45
+ `mountRiebeckiteEndpoints` が `POST /webmentions` と `GET /webmentions` をマウントし、
46
+ 検証済みメンションはビルド時に記事の近くへ描画されます。
47
+
48
+ ## 単体レシーバー
49
+
50
+ ```ts
51
+ import { createWorker, d1Storage } from "@riebeckite/webmention-cloudflare";
52
+
53
+ interface Env {
54
+ WEBMENTION_DB: D1Database;
55
+ }
56
+
57
+ export default {
58
+ fetch: (request: Request, env: Env) =>
59
+ createWorker({
60
+ storage: d1Storage(env.WEBMENTION_DB),
61
+ allowedTargets: ["https://www.example.com/"],
62
+ }).fetch(request),
63
+ };
64
+ ```
65
+
66
+ 単体レシーバーは `allowedTargets` のターゲットしか知らず、content manifest を
67
+ 持たないため、フィードの要素に記事サマリーは付きません。サイト Worker と同居する
68
+ 場合はプラグインの `endpoints` を使い、公開 entry とメンションを対応付けてください。
69
+
70
+ ## エンドポイントと検証
71
+
72
+ - `POST /webmentions` は `source` と `target` をフォームまたは JSON(8〜64 KiB 上限)
73
+ で受け取り、ターゲットが許可された絶対 URL であることを要求し、保存前に送信元が
74
+ リンクしていることを検証します。応答は `202`(受理)、`400`(`error` コード付き)、
75
+ 書き込み不能時の `503` です。
76
+ - `GET /webmentions?target=&limit=&since=` は
77
+ `{ version, generatedAt, count, mentions }` を返します。`query` capability を持たない
78
+ ストレージでは `501` を返します。
79
+
80
+ 既定の送信元 fetcher は loopback とプライベートネットワーク宛てを拒否し、本文サイズを
81
+ 制限し、タイムアウトします。Webmention の送信元はサーバーであるため
82
+ `allowMissingOrigin` は既定で `true` です。ブラウザ origin は明示的に列挙しない限り
83
+ 拒否されます。
84
+
85
+ ## D1 スキーマとデプロイ
86
+
87
+ Worker はリクエスト中に D1 をマイグレーションしてはいけません。デプロイ前にスキーマを
88
+ 適用してください。
89
+
90
+ ```sh
91
+ pnpm exec wrangler d1 execute WEBMENTION_DB --file node_modules/@riebeckite/webmention-cloudflare/migrations/0001_webmentions.sql
92
+ pnpm exec wrangler deploy
93
+ ```
94
+
95
+ ## 関連
96
+
97
+ - [@riebeckite/plugin-webmention](../../plugins/webmention/README_ja.md)
98
+ - [Analytics Cloudflare ランタイム](../analytics-cloudflare/README_ja.md)
@@ -0,0 +1,7 @@
1
+ export type { WebmentionStorage } from "./src/domain/webmention/storage.js";
2
+ export type { D1Database } from "./src/infrastructure/d1/d1_types.js";
3
+ export { D1WebmentionStorage, d1Storage, } from "./src/infrastructure/d1/d1_webmention_storage.js";
4
+ export type { KvNamespace } from "./src/infrastructure/kv/kv_webmention_storage.js";
5
+ export { KvWebmentionStorage, kvStorage, } from "./src/infrastructure/kv/kv_webmention_storage.js";
6
+ export type { WebmentionCorsOptions, WebmentionWorker, WebmentionWorkerOptions, } from "./src/presentation/worker/create_worker.js";
7
+ export { createWorker } from "./src/presentation/worker/create_worker.js";
package/dist/index.js ADDED
@@ -0,0 +1,301 @@
1
+ // src/infrastructure/d1/d1_webmention_storage.ts
2
+ import {
3
+ assertWebmentionQuerySupported,
4
+ urlComparisonKey,
5
+ WEBMENTION_CAPABILITIES
6
+ } from "@riebeckite/plugin-webmention";
7
+ var SELECT_COLUMNS = `source, target, type, verified_at, published_at,
8
+ title, excerpt, author_name, author_url, author_photo`;
9
+ var D1WebmentionStorage = class {
10
+ constructor(database) {
11
+ this.database = database;
12
+ }
13
+ database;
14
+ capabilities = new Set(WEBMENTION_CAPABILITIES);
15
+ async store(mention) {
16
+ await this.database.prepare(
17
+ `INSERT INTO webmentions (
18
+ source, target, type, verified_at, published_at,
19
+ title, excerpt, author_name, author_url, author_photo
20
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
21
+ ON CONFLICT(source, target) DO UPDATE SET
22
+ type = excluded.type,
23
+ verified_at = excluded.verified_at,
24
+ published_at = excluded.published_at,
25
+ title = excluded.title,
26
+ excerpt = excluded.excerpt,
27
+ author_name = excluded.author_name,
28
+ author_url = excluded.author_url,
29
+ author_photo = excluded.author_photo`
30
+ ).bind(
31
+ mention.source,
32
+ urlComparisonKey(mention.target),
33
+ mention.type,
34
+ mention.verifiedAt,
35
+ mention.publishedAt ?? null,
36
+ mention.title ?? null,
37
+ mention.excerpt ?? null,
38
+ mention.author?.name ?? null,
39
+ mention.author?.url ?? null,
40
+ mention.author?.photo ?? null
41
+ ).run();
42
+ }
43
+ async query(query) {
44
+ assertWebmentionQuerySupported(this, query);
45
+ const limit = clampLimit(query.limit);
46
+ if (query.type === "mentions_for_target") {
47
+ const result2 = await this.database.prepare(
48
+ `SELECT ${SELECT_COLUMNS} FROM webmentions
49
+ WHERE target = ?
50
+ ORDER BY COALESCE(published_at, verified_at) DESC, source ASC
51
+ LIMIT ?`
52
+ ).bind(urlComparisonKey(query.target), limit).all();
53
+ return {
54
+ type: query.type,
55
+ target: query.target,
56
+ mentions: (result2.results ?? []).map(toMention)
57
+ };
58
+ }
59
+ if (query.since === void 0) {
60
+ const result2 = await this.database.prepare(
61
+ `SELECT ${SELECT_COLUMNS} FROM webmentions
62
+ ORDER BY COALESCE(published_at, verified_at) DESC, source ASC
63
+ LIMIT ?`
64
+ ).bind(limit).all();
65
+ return {
66
+ type: query.type,
67
+ mentions: (result2.results ?? []).map(toMention)
68
+ };
69
+ }
70
+ const result = await this.database.prepare(
71
+ `SELECT ${SELECT_COLUMNS} FROM webmentions
72
+ WHERE verified_at >= ?
73
+ ORDER BY COALESCE(published_at, verified_at) DESC, source ASC
74
+ LIMIT ?`
75
+ ).bind(query.since, limit).all();
76
+ return {
77
+ type: query.type,
78
+ mentions: (result.results ?? []).map(toMention)
79
+ };
80
+ }
81
+ };
82
+ function d1Storage(database) {
83
+ return new D1WebmentionStorage(database);
84
+ }
85
+ function toMention(row) {
86
+ const author = row.author_name === null && row.author_url === null && row.author_photo === null ? void 0 : {
87
+ ...row.author_name === null ? {} : { name: row.author_name },
88
+ ...row.author_url === null ? {} : { url: row.author_url },
89
+ ...row.author_photo === null ? {} : { photo: row.author_photo }
90
+ };
91
+ return {
92
+ source: row.source,
93
+ target: row.target,
94
+ type: row.type,
95
+ verifiedAt: row.verified_at,
96
+ ...row.published_at === null ? {} : { publishedAt: row.published_at },
97
+ ...row.title === null ? {} : { title: row.title },
98
+ ...row.excerpt === null ? {} : { excerpt: row.excerpt },
99
+ ...author === void 0 ? {} : { author }
100
+ };
101
+ }
102
+ function clampLimit(limit) {
103
+ if (limit === void 0) return 100;
104
+ return Math.min(Math.max(limit, 1), 1e3);
105
+ }
106
+
107
+ // src/infrastructure/kv/kv_webmention_storage.ts
108
+ import {
109
+ UnsupportedWebmentionQueryError
110
+ } from "@riebeckite/plugin-webmention";
111
+ var KvWebmentionStorage = class {
112
+ constructor(namespace) {
113
+ this.namespace = namespace;
114
+ }
115
+ namespace;
116
+ capabilities = /* @__PURE__ */ new Set(["store"]);
117
+ async store(mention) {
118
+ await this.namespace.put(
119
+ keyFor(mention.target, mention.source),
120
+ JSON.stringify(mention)
121
+ );
122
+ }
123
+ async query(query) {
124
+ throw new UnsupportedWebmentionQueryError(query, "query");
125
+ }
126
+ };
127
+ function kvStorage(namespace) {
128
+ return new KvWebmentionStorage(namespace);
129
+ }
130
+ function keyFor(target, source) {
131
+ return `webmention:${encodeURIComponent(target)}:${encodeURIComponent(source)}`;
132
+ }
133
+
134
+ // src/presentation/worker/create_worker.ts
135
+ import {
136
+ createWebmentionSourceFetcher,
137
+ parseWebmentionRequestBody,
138
+ UnsupportedWebmentionQueryError as UnsupportedWebmentionQueryError2,
139
+ urlComparisonKey as urlComparisonKey2,
140
+ verifyWebmention
141
+ } from "@riebeckite/plugin-webmention";
142
+ var MAX_REQUEST_BODY_BYTES = 64 * 1024;
143
+ var DEFAULT_FEED_LIMIT = 50;
144
+ function createWorker(options) {
145
+ const fetchSource = options.fetchSource ?? createWebmentionSourceFetcher({
146
+ timeoutMs: options.timeoutMs,
147
+ maxBytes: options.maxBytes,
148
+ userAgent: options.userAgent,
149
+ allowPrivateHosts: options.allowPrivateHosts
150
+ });
151
+ const allowedTargets = new Set(
152
+ options.allowedTargets.map((target) => urlComparisonKey2(target))
153
+ );
154
+ return {
155
+ async fetch(request) {
156
+ const originResponse = corsResponse(request, options.cors);
157
+ if (originResponse) return originResponse;
158
+ const corsHeaders = responseCorsHeaders(request, options.cors);
159
+ if (request.method === "OPTIONS") {
160
+ return new Response(null, { status: 204, headers: corsHeaders });
161
+ }
162
+ const url = new URL(request.url);
163
+ if (url.pathname !== "/webmentions") {
164
+ return json({ error: "not_found" }, 404, corsHeaders);
165
+ }
166
+ if (request.method === "POST") {
167
+ return receive(
168
+ request,
169
+ options.storage,
170
+ allowedTargets,
171
+ fetchSource,
172
+ corsHeaders
173
+ );
174
+ }
175
+ if (request.method === "GET") {
176
+ return feed(url, options.storage, corsHeaders);
177
+ }
178
+ return json({ error: "method_not_allowed" }, 405, corsHeaders);
179
+ }
180
+ };
181
+ }
182
+ async function receive(request, storage, allowedTargets, fetchSource, headers) {
183
+ if (!storage.capabilities.has("store")) {
184
+ return json({ error: "storage_unavailable" }, 503, headers);
185
+ }
186
+ const length = Number(request.headers.get("content-length"));
187
+ if (Number.isFinite(length) && length > MAX_REQUEST_BODY_BYTES) {
188
+ return json({ error: "payload_too_large" }, 413, headers);
189
+ }
190
+ const body = await request.text();
191
+ if (new TextEncoder().encode(body).byteLength > MAX_REQUEST_BODY_BYTES) {
192
+ return json({ error: "payload_too_large" }, 413, headers);
193
+ }
194
+ const requestHeaders = {};
195
+ request.headers.forEach((value, key) => {
196
+ requestHeaders[key.toLowerCase()] = value;
197
+ });
198
+ const params = parseWebmentionRequestBody(body, requestHeaders);
199
+ if (params === null) return json({ error: "invalid_request" }, 400, headers);
200
+ const { source, target } = params;
201
+ if (!source || !target) {
202
+ return json({ error: "missing_source_or_target" }, 400, headers);
203
+ }
204
+ if (!allowedTargets.has(urlComparisonKey2(target))) {
205
+ return json({ error: "target_not_found" }, 400, headers);
206
+ }
207
+ const verification = await verifyWebmention({ source, target, fetchSource });
208
+ if ("reason" in verification) {
209
+ return json({ error: verification.reason }, 400, headers);
210
+ }
211
+ try {
212
+ await storage.store(verification.mention);
213
+ } catch {
214
+ return json({ error: "storage_unavailable" }, 503, headers);
215
+ }
216
+ return json({ status: "accepted" }, 202, headers);
217
+ }
218
+ async function feed(url, storage, headers) {
219
+ if (!storage.capabilities.has("query")) {
220
+ return json({ error: "unsupported_query" }, 501, headers);
221
+ }
222
+ const target = url.searchParams.get("target");
223
+ const limit = parseLimit(url.searchParams.get("limit"));
224
+ const since = url.searchParams.get("since") ?? void 0;
225
+ let mentions;
226
+ try {
227
+ if (target !== null && target !== "") {
228
+ const result = await storage.query({
229
+ type: "mentions_for_target",
230
+ target,
231
+ limit
232
+ });
233
+ mentions = result.mentions;
234
+ } else {
235
+ const result = await storage.query({
236
+ type: "all_mentions",
237
+ limit,
238
+ since
239
+ });
240
+ mentions = result.mentions;
241
+ }
242
+ } catch (error) {
243
+ if (error instanceof UnsupportedWebmentionQueryError2) {
244
+ return json({ error: "unsupported_query" }, 501, headers);
245
+ }
246
+ return json({ error: "storage_unavailable" }, 503, headers);
247
+ }
248
+ return json(
249
+ {
250
+ version: "1",
251
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
252
+ count: mentions.length,
253
+ mentions
254
+ },
255
+ 200,
256
+ headers
257
+ );
258
+ }
259
+ function parseLimit(value) {
260
+ if (value === null || value.trim() === "") return DEFAULT_FEED_LIMIT;
261
+ const parsed = Number(value);
262
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 1e3) {
263
+ return DEFAULT_FEED_LIMIT;
264
+ }
265
+ return parsed;
266
+ }
267
+ function corsResponse(request, cors) {
268
+ const origin = request.headers.get("origin");
269
+ if (origin === null) {
270
+ return cors?.allowMissingOrigin === false ? json({ error: "origin_required" }, 403) : void 0;
271
+ }
272
+ const allowed = cors?.allowedOrigins;
273
+ const originAllowed = allowed === "any" || Array.isArray(allowed) && allowed.includes(origin);
274
+ if (!originAllowed) return json({ error: "origin_not_allowed" }, 403);
275
+ return void 0;
276
+ }
277
+ function responseCorsHeaders(request, cors) {
278
+ const headers = new Headers({ Vary: "Origin" });
279
+ const origin = request.headers.get("origin");
280
+ if (origin && (cors?.allowedOrigins === "any" || cors?.allowedOrigins?.includes(origin))) {
281
+ headers.set(
282
+ "Access-Control-Allow-Origin",
283
+ cors.allowedOrigins === "any" ? "*" : origin
284
+ );
285
+ headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
286
+ headers.set("Access-Control-Allow-Headers", "Content-Type");
287
+ }
288
+ return headers;
289
+ }
290
+ function json(value, status, headers = new Headers()) {
291
+ const output = new Headers(headers);
292
+ output.set("Content-Type", "application/json; charset=utf-8");
293
+ return new Response(JSON.stringify(value), { status, headers: output });
294
+ }
295
+ export {
296
+ D1WebmentionStorage,
297
+ KvWebmentionStorage,
298
+ createWorker,
299
+ d1Storage,
300
+ kvStorage
301
+ };
@@ -0,0 +1,6 @@
1
+ import type { WebmentionProvider } from "@riebeckite/plugin-webmention";
2
+ /**
3
+ * Runtime-owned Webmention storage boundary. Select exactly one adapter per
4
+ * Worker; the generic plugin never imports this package.
5
+ */
6
+ export type WebmentionStorage = WebmentionProvider;
@@ -0,0 +1,11 @@
1
+ /** Minimal structural subset of the Cloudflare D1 binding used by the adapter. */
2
+ export interface D1PreparedStatement {
3
+ bind(...values: readonly unknown[]): D1PreparedStatement;
4
+ all<T = Record<string, unknown>>(): Promise<{
5
+ results?: T[];
6
+ }>;
7
+ run(): Promise<unknown>;
8
+ }
9
+ export interface D1Database {
10
+ prepare(query: string): D1PreparedStatement;
11
+ }
@@ -0,0 +1,17 @@
1
+ import { type WebmentionMention, type WebmentionQuery, type WebmentionQueryResult } from "@riebeckite/plugin-webmention";
2
+ import type { WebmentionStorage } from "../../domain/webmention/storage.js";
3
+ import type { D1Database } from "./d1_types.js";
4
+ /**
5
+ * D1-backed Webmention storage. One row per verified `(source, target)` pair;
6
+ * repeated deliveries upsert. Targets are stored in canonical comparison form
7
+ * so trailing-slash and fragment differences converge.
8
+ */
9
+ export declare class D1WebmentionStorage implements WebmentionStorage {
10
+ private readonly database;
11
+ readonly capabilities: Set<"store" | "query">;
12
+ constructor(database: D1Database);
13
+ store(mention: WebmentionMention): Promise<void>;
14
+ query(query: WebmentionQuery): Promise<WebmentionQueryResult>;
15
+ }
16
+ /** Creates a D1-backed storage adapter from a Worker binding. */
17
+ export declare function d1Storage(database: D1Database): WebmentionStorage;
@@ -0,0 +1,24 @@
1
+ import { type WebmentionMention, type WebmentionQuery, type WebmentionQueryResult } from "@riebeckite/plugin-webmention";
2
+ import type { WebmentionStorage } from "../../domain/webmention/storage.js";
3
+ export interface KvNamespace {
4
+ get(key: string): Promise<string | null>;
5
+ put(key: string, value: string): Promise<void>;
6
+ }
7
+ /**
8
+ * Minimal KV storage. KV has no listing or atomic update, so it stores one
9
+ * JSON value per `(target, source)` pair and deliberately does not advertise
10
+ * the `query` capability; feed reads throw `UnsupportedWebmentionQueryError`
11
+ * and the Worker returns `501`. Use D1 when the feed must be served.
12
+ *
13
+ * KV keys are capped at 512 bytes, so very long source/target URLs may fail to
14
+ * store. Prefer D1 for arbitrary URLs.
15
+ */
16
+ export declare class KvWebmentionStorage implements WebmentionStorage {
17
+ private readonly namespace;
18
+ readonly capabilities: Set<"store">;
19
+ constructor(namespace: KvNamespace);
20
+ store(mention: WebmentionMention): Promise<void>;
21
+ query(query: WebmentionQuery): Promise<WebmentionQueryResult>;
22
+ }
23
+ /** Creates a KV-backed, store-only storage adapter from a binding. */
24
+ export declare function kvStorage(namespace: KvNamespace): WebmentionStorage;
@@ -0,0 +1,35 @@
1
+ import { type WebmentionSourceFetcher } from "@riebeckite/plugin-webmention";
2
+ import type { WebmentionStorage } from "../../domain/webmention/storage.js";
3
+ export type WebmentionCorsOptions = Readonly<{
4
+ /** Explicit browser origins, or "any". Browser clients are not typical. */
5
+ allowedOrigins?: readonly string[] | "any";
6
+ /**
7
+ * Allow requests without an `Origin` header. Defaults to `true` because
8
+ * Webmention senders are servers, not browsers.
9
+ */
10
+ allowMissingOrigin?: boolean;
11
+ }>;
12
+ export type WebmentionWorkerOptions = Readonly<{
13
+ /** One explicitly selected runtime storage adapter. */
14
+ storage: WebmentionStorage;
15
+ /** Absolute target URLs accepted by this receiver. No default. */
16
+ allowedTargets: readonly string[];
17
+ /** Source fetcher override, mainly for tests. */
18
+ fetchSource?: WebmentionSourceFetcher;
19
+ cors?: WebmentionCorsOptions;
20
+ timeoutMs?: number;
21
+ maxBytes?: number;
22
+ userAgent?: string;
23
+ allowPrivateHosts?: boolean;
24
+ }>;
25
+ export type WebmentionWorker = Readonly<{
26
+ fetch(request: Request): Promise<Response>;
27
+ }>;
28
+ /**
29
+ * Creates a standalone Webmention receiver. It verifies sources, stores them
30
+ * through the selected adapter, and serves a verified-mention feed. It does
31
+ * not render articles or know about the content manifest; feed entries carry
32
+ * no article summary. When the receiver shares the site Worker, prefer the
33
+ * plugin's `endpoints` so mentions can be matched to published entries.
34
+ */
35
+ export declare function createWorker(options: WebmentionWorkerOptions): WebmentionWorker;
@@ -0,0 +1,18 @@
1
+ CREATE TABLE IF NOT EXISTS webmentions (
2
+ source TEXT NOT NULL,
3
+ target TEXT NOT NULL,
4
+ type TEXT NOT NULL,
5
+ verified_at TEXT NOT NULL,
6
+ published_at TEXT,
7
+ title TEXT,
8
+ excerpt TEXT,
9
+ author_name TEXT,
10
+ author_url TEXT,
11
+ author_photo TEXT,
12
+ PRIMARY KEY (source, target)
13
+ );
14
+
15
+ CREATE INDEX IF NOT EXISTS idx_webmentions_target ON webmentions (target);
16
+
17
+ CREATE INDEX IF NOT EXISTS idx_webmentions_verified_at
18
+ ON webmentions (verified_at);
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@riebeckite/webmention-cloudflare",
3
+ "version": "0.0.6",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "source": "./index.ts",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "dependencies": {
17
+ "@riebeckite/plugin-webmention": "0.0.6"
18
+ },
19
+ "devDependencies": {
20
+ "tsx": "^4.22.4"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "files": [
26
+ "LICENSE",
27
+ "README.md",
28
+ "README_ja.md",
29
+ "migrations",
30
+ "dist"
31
+ ],
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/Rerurate514/riebeckite.git",
35
+ "directory": "packages/integrations/webmention-cloudflare"
36
+ },
37
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
38
+ "bugs": {
39
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
40
+ },
41
+ "description": "Cloudflare Workers, D1, and KV runtime for Riebeckite Webmentions.",
42
+ "keywords": [
43
+ "riebeckite",
44
+ "webmention",
45
+ "cloudflare",
46
+ "workers",
47
+ "d1",
48
+ "kv"
49
+ ],
50
+ "engines": {
51
+ "node": "^20.19.0 || >=22.12.0"
52
+ },
53
+ "sideEffects": false,
54
+ "scripts": {
55
+ "build": "node ../../../scripts/build_package.mjs",
56
+ "test": "node --import tsx --test \"test/*.test.ts\""
57
+ }
58
+ }