@cherwell/emdash-shortlinks 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First release.
6
+
7
+ - **Links:** to a URL or an entry, readable random or custom codes, UTM tags, expiry, enable and disable. Codes can be per site or shared.
8
+ - **QR codes:** PNG, generated on your site.
9
+ - **Reports:** clicks per day, QR scans, top countries and referrers. Bots and repeats aren't counted.
10
+ - **Site route:** `@cherwell/emdash-shortlinks/astro`.
11
+ - **For teams and tools:**
12
+ - JSON API with cursors
13
+ - MCP tools
14
+ - signed webhooks with retries
15
+ - CSV import and export
16
+ - custom fields
17
+ - audit trail
18
+ - **Settings** for code length and alphabet, reserved codes, redirect status, repeat window, what is recorded, time zone and QR style.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cherwell Studio
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.
package/README.md CHANGED
@@ -1,3 +1,199 @@
1
- # Temporary Holding Version
1
+ # Short Links for EmDash
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <img src="assets/icon.png" alt="" width="96" align="right">
4
+
5
+ **Short, trackable links and QR codes for print, social and email, served from your own site.**
6
+
7
+ Short, trackable links and QR codes for print, social and email. Each link points at a web address or at an entry on your site, and follows the entry if its address changes. Reports show clicks, QR scans, countries and referrers per day. No cookies, no IP addresses kept, bots counted separately.
8
+
9
+ - **Links and codes.** Random codes leave out lookalike characters (no 0/o or 1/l/i), or you choose your own. Links can carry UTM tags and expire on a set date. Disable a link without losing its numbers.
10
+ - **QR codes.** A PNG for every link, made on your own site with no outside service. Scans are counted separately from clicks.
11
+ - **Reports.** Clicks per day with a 30-day chart, plus top countries and referrers. People are counted once a minute per address. Bots, link previews and prefetches don't count as clicks.
12
+ - **Safe redirects.** The link's own UTM tags always win, so a visitor can't rewrite a campaign. Only allow-listed visitor parameters pass through (`ref`, `gclid`, `fbclid` and others), so links can't be used to send parameters to partner sites.
13
+ - **Several sites.** When one install serves several sites, codes can belong to one site (`visit` on one site, `visit` on another) or be shared by every site. Each site can have its own short domain.
14
+ - **For teams and tools:**
15
+ - a JSON API with cursor paging
16
+ - MCP tools for AI agents
17
+ - signed webhooks
18
+ - CSV import (in the background) and export
19
+ - custom fields on links
20
+ - an audit trail of every change
21
+
22
+ ## Documentation
23
+
24
+ - [Overview](docs/overview.md): what it does and who it is for
25
+ - [Installation](docs/install.md): add the plugin, wire the site route, check it works
26
+ - [FAQ](docs/faq.md): privacy, QR codes, bots, importing, several sites
27
+ - [Reference](docs/reference.md): generated list of settings, routes, MCP tools and storage
28
+ - [llms.txt](llms.txt): a summary for AI agents
29
+
30
+ ## Install
31
+
32
+ From the EmDash registry: **Admin ▸ Plugins ▸ Browse**, search for *Short Links*, and approve its capabilities.
33
+
34
+ From npm, for the site route:
35
+
36
+ ```sh
37
+ npm install @cherwell/emdash-shortlinks
38
+ ```
39
+
40
+ ```ts
41
+ // astro.config.mjs: only if you install the plugin from npm rather than the registry
42
+ import shortlinks from "@cherwell/emdash-shortlinks";
43
+ emdash({ plugins: [shortlinks] }); // or sandboxed: [shortlinks] on Workers Paid
44
+ ```
45
+
46
+ The site needs the npm package for the route below even when the plugin comes from the registry.
47
+
48
+ Then add the route that serves links. EmDash doesn't let a plugin redirect to another site, so your site does the redirect:
49
+
50
+ ```ts
51
+ // src/pages/s/[code].ts
52
+ import { shortlinkRoute } from "@cherwell/emdash-shortlinks/astro";
53
+
54
+ export const { GET, HEAD } = shortlinkRoute({ key: import.meta.env.SHORTLINKS_KEY });
55
+ ```
56
+
57
+ Set `SHORTLINKS_KEY` to a long random value. Then enter the same value as the plugin's **Server key** setting. Without it, the plugin answers nothing, so nobody can inflate your numbers by calling it directly.
58
+
59
+ When one install serves several sites, scope codes by site (`ctx.locals.site` is whatever your middleware sets):
60
+
61
+ ```ts
62
+ export const { GET, HEAD } = shortlinkRoute({
63
+ key: import.meta.env.SHORTLINKS_KEY,
64
+ scope: (ctx) => ctx.locals.site?.key,
65
+ });
66
+ ```
67
+
68
+ `shortlinkRoute` also takes `fallback` (where to go if the plugin can't be reached, default `/`) and `pluginId` (default `shortlinks`). Live links answer with the **Redirect status** setting (`302` unless you change it); missing, disabled and expired ones always get a `302`. Every answer has `Cache-Control: no-store`, `X-Robots-Tag: noindex, nofollow` and an `X-Shortlink` header of `active`, `inactive` or `missing`. It only ever redirects to an `http(s)` address or a path on your own site, and trims over-long query strings and headers rather than failing the redirect.
69
+
70
+ ## Settings
71
+
72
+ | Setting | Default | What it does |
73
+ |---|---|---|
74
+ | Path | `/s/` | The path your site serves links on. It must match where you put the route. |
75
+ | Fallback | `/` | Where a missing, disabled or expired link goes. |
76
+ | Visitor parameters | `ref,gclid,fbclid,msclkid,utm_content,utm_term` | Query parameters passed through to the destination. |
77
+ | Public address | the site address | The origin used in QR codes and copy links, for example a short domain. |
78
+ | Per-site addresses | none | JSON, for example `{"north": "https://exm.pl"}`. |
79
+ | Server key | none | The site route's key. Required. |
80
+ | Webhook signing secret | none | Signs webhook requests. |
81
+ | Keep statistics | 24 months | Older monthly statistics are deleted. |
82
+ | Keep audit trail | 365 days | |
83
+ | Host calls per background run | 28 | The call budget for cron runs (imports, webhook deliveries). 28 suits a Cloudflare sandbox; raise it when running in-process. |
84
+ | Custom fields | none | JSON field definitions. See below. |
85
+ | Length of random codes (`codeLength`) | 7 | 4 to 32. Shorter codes are easier to type but easier to guess. |
86
+ | Characters random codes use (`codeAlphabet`) | `abcdefghjkmnpqrstuvwxyz23456789` | Lowercase letters and digits only, at least 10 different ones; anything else is ignored. The default leaves out lookalikes. |
87
+ | Reserved codes (`reservedCodes`) | none | Comma-separated codes nobody can create, for example `admin,login` when links are served at the root of a domain. |
88
+ | Redirect status (`redirectStatus`) | `302` | `301`, `302`, `307` or `308` for live links. A permanent redirect (`301`/`308`) tells search engines the short link is the destination's address; responses still carry `no-store`, so browsers ask each time and clicks keep counting. |
89
+ | Repeat window (`repeatSeconds`) | 60 | A person's repeat click on the same link from the same address within this many seconds isn't counted. `0` counts every click. |
90
+ | Record countries (`recordCountries`) | on | Turn off to keep no country codes. |
91
+ | Record referring sites (`recordReferrers`) | on | Turn off to keep no referrer hostnames. |
92
+ | Time zone (`timeZone`) | `UTC` | An IANA zone such as `Europe/London`. Daily statistics follow its calendar days, and a link set to expire on a date works until the end of that day there. Unknown zones fall back to UTC. Changing it doesn't move clicks already recorded. |
93
+ | QR error correction (`qrLevel`) | `M` | `L`, `M`, `Q` or `H`. Use `H` if you'll print a logo over the code. |
94
+ | QR pixels per module (`qrScale`) | 8 | 1 to 40. Raise it for large print. |
95
+ | QR quiet zone (`qrMargin`) | 4 | Light modules around the code, 0 to 16. Four is the standard; use less only if your design adds its own margin. |
96
+
97
+ Out-of-range values fall back to the nearest allowed value (or the default, for text), so a typo can't break redirects.
98
+
99
+ ### Custom fields
100
+
101
+ Add your own fields to links (shown in the admin, validated, and exported):
102
+
103
+ ```json
104
+ [
105
+ { "key": "costCentre", "label": "Cost centre", "type": "select", "options": ["Marketing", "Events"] },
106
+ { "key": "printRun", "label": "Print run", "type": "number" }
107
+ ]
108
+ ```
109
+
110
+ Types: `text`, `longtext`, `number`, `date`, `select`, `multiselect`, `boolean`, `email`, `url`, `phone`. Add `"required": true` to make a field mandatory.
111
+
112
+ ## Capabilities
113
+
114
+ | Capability | Why |
115
+ |---|---|
116
+ | `content:read` | To resolve links that point at an entry, so they follow it when its address changes. |
117
+ | `network:request:unrestricted` | To deliver webhooks to addresses you enter. |
118
+
119
+ ## API
120
+
121
+ Private routes are under `/_emdash/api/plugins/shortlinks/` and need an editor's session or an API token. Every response is `{ ok: true, … }` or `{ ok: false, error: CODE, fields? }`.
122
+
123
+ | Route | Input | Returns |
124
+ |---|---|---|
125
+ | `links/list` | `campaign?`, `status?`, `scope?`, `cursor?`, `limit?` (≤ 100) | `links`, `cursor` |
126
+ | `links/get` | `code`, `scope?`, `days?` (≤ 366) | `link`, `report` (daily series, total, QR, bots, countries, referrers) |
127
+ | `links/create` | `target`, `code?`, `scope?`, `title?`, `campaign?`, `utmSource?`, `utmMedium?`, `utmCampaign?`, `expiresOn?`, `custom?` | `link` |
128
+ | `links/update` | `code`, `scope?`, `changes` (any create field except code and scope, plus `status`) | `link` |
129
+ | `links/delete` | `code`, `scope?` | — |
130
+
131
+ Error codes:
132
+
133
+ - `INVALID_INPUT` (with `fields`)
134
+ - `TARGET_INVALID`
135
+ - `ENTRY_NOT_FOUND`
136
+ - `CODE_INVALID`
137
+ - `CODE_TAKEN`
138
+ - `CODE_RESERVED`
139
+ - `CODE_EXHAUSTED`
140
+ - `NOT_FOUND`
141
+ - `FORBIDDEN`
142
+ - `INTERNAL`
143
+
144
+ ### MCP tools
145
+
146
+ Turn them on in **Admin ▸ Plugins ▸ Short Links ▸ MCP**.
147
+
148
+ - **Read:** `shortlinks_list`, `shortlink_get`
149
+ - **Marked destructive** (an agent must confirm, because they change what visitors see): `shortlink_create`, `shortlink_update`, `shortlink_delete`
150
+
151
+ ## Webhooks
152
+
153
+ Add endpoints on the **Webhooks** page (administrators only; editors can see the page and its delivery log). The events are `shortlink.created`, `shortlink.updated` and `shortlink.deleted`. Use `shortlink.*` or `*` to subscribe to several.
154
+
155
+ Each delivery is a JSON `POST`:
156
+
157
+ ```json
158
+ { "id": "whd_…", "event": "shortlink.created", "createdAt": "2026-12-01T09:00:00.000Z",
159
+ "data": { "code": "spring", "path": "/s/spring", "target": "https://…", "status": "active", … } }
160
+ ```
161
+
162
+ **Headers:**
163
+
164
+ - `X-Webhook-Event`
165
+ - `X-Webhook-Id`, which stays the same across retries, so you can deduplicate on it
166
+ - `X-Webhook-Signature: t=<unix>,v1=<hex>`
167
+
168
+ **To verify a delivery,** compute HMAC-SHA256 of `"<t>.<raw body>"` using your signing secret, compare it with `v1`, and reject requests where `t` is more than five minutes old.
169
+
170
+ **Retries:** failed deliveries are retried after 1, 5 and 30 minutes, then 2, 6, 12 and 24 hours, before they're marked failed. Retry them from the **Webhooks** page.
171
+
172
+ ## Limits
173
+
174
+ - **Work runs in batches.** In a sandbox each request may make about 30 calls to EmDash, so each request and background run stops at a budget (28 calls by default). Imports run in the background, a few rows a minute, and you can push them along from the **Import and export** page. Exports stop at 2,000 links per download (100 more for each call **Host calls per background run** allows above 28, for in-process installs).
175
+ - **Approximate counting.** Counts are approximate under very heavy, simultaneous traffic to a single link. A repeat from the same address within the repeat window (a minute by default) isn't counted. Totals are exact otherwise.
176
+ - **No visitor data.** Countries come from Cloudflare's own header; referrers are recorded as hostnames only.
177
+
178
+ ## Privacy
179
+
180
+ The plugin stores no personal data about visitors: no IP addresses, cookies or full referrer URLs. To drop repeat clicks, a truncated SHA-256 hash of the IP address becomes part of a rate-limit row in the plugin's `rate_limits` storage, one row per link and address, reused each window. The minute cron deletes expired rows, and the daily cron clears keys earlier versions kept in plugin KV. Set **Repeat window** to `0` to keep none, and turn off **Record countries** or **Record referring sites** to keep less. Links record the EmDash user id of whoever made them, never their email.
181
+
182
+ ## Upgrading
183
+
184
+ 1.0 is the first release. Future changes to stored data migrate automatically when the plugin is activated or updated.
185
+
186
+ ## Development
187
+
188
+ In this monorepo:
189
+
190
+ ```sh
191
+ pnpm --filter @cherwell/emdash-shortlinks validate
192
+ pnpm --filter @cherwell/emdash-shortlinks typecheck
193
+ pnpm --filter @cherwell/emdash-shortlinks test
194
+ pnpm --filter @cherwell/emdash-shortlinks build
195
+ ```
196
+
197
+ ## Licence
198
+
199
+ MIT © Cherwell Studio
Binary file
Binary file
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><g transform="translate(0 0)">
2
+ <defs><linearGradient id="t" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#BE123C"/><stop offset="1" stop-color="#881337"/></linearGradient></defs>
3
+ <rect width="512" height="512" rx="112.64" fill="url(#t)"/>
4
+ <rect x="1" y="1" width="510" height="510" rx="111.64" fill="none" stroke="#fff" stroke-opacity=".14" stroke-width="2"/>
5
+ <g transform="translate(102.4 102.4) scale(12.799999999999999)" fill="none" stroke="#fff" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><path d="M14 20l6-6"/><path d="M15.5 14H20v4.5"/></g>
6
+ </g></svg>
@@ -0,0 +1,43 @@
1
+ //#region src/astro.d.ts
2
+ /**
3
+ * Site side of Short Links: the /s/<code> route.
4
+ *
5
+ * // src/pages/s/[code].ts
6
+ * import { shortlinkRoute } from "@cherwell/emdash-shortlinks/astro";
7
+ * export const { GET, HEAD } = shortlinkRoute({ key: import.meta.env.SHORTLINKS_KEY });
8
+ *
9
+ * When one install serves several sites, pass the site so codes can be scoped per site:
10
+ * shortlinkRoute({ key, scope: (ctx) => ctx.locals.site?.key })
11
+ *
12
+ * EmDash won't let a plugin route redirect off-site, so this route asks the
13
+ * plugin (in-process, with a server key) and redirects itself.
14
+ */
15
+ interface RouteContext {
16
+ params: Record<string, string | undefined>;
17
+ request: Request;
18
+ url: URL;
19
+ locals: Record<string, unknown> & {
20
+ emdash?: {
21
+ handlePublicPluginApiRoute?: (id: string, method: string, path: string, req: Request) => Promise<{
22
+ data?: unknown;
23
+ }>;
24
+ };
25
+ };
26
+ clientAddress?: string;
27
+ }
28
+ interface ShortlinkRouteOptions {
29
+ /** The plugin's server key (same value as its "Server key" setting). */
30
+ key: string | undefined;
31
+ /** Site key for per-site codes, when one install serves several sites. */
32
+ scope?: (ctx: RouteContext) => string | undefined | null;
33
+ /** Where to go if the plugin can't be reached. */
34
+ fallback?: string;
35
+ /** Plugin id, if installed under another one. */
36
+ pluginId?: string;
37
+ }
38
+ declare function shortlinkRoute(opts: ShortlinkRouteOptions): {
39
+ GET: (ctx: RouteContext) => Promise<Response>;
40
+ HEAD: (ctx: RouteContext) => Promise<Response>;
41
+ };
42
+ //#endregion
43
+ export { ShortlinkRouteOptions, shortlinkRoute };
@@ -0,0 +1,95 @@
1
+ //#region src/astro.ts
2
+ const BOT = /bot|crawl|spider|slurp|facebookexternalhit|whatsapp|slack|discord|telegram|twitter|linkedin|preview|embedly|headless|lighthouse|monitor|curl|wget|python-requests|go-http|scanner|safelinks|proofpoint|mimecast|barracuda/i;
3
+ function human(req) {
4
+ const ua = req.headers.get("user-agent");
5
+ const purpose = `${req.headers.get("sec-purpose") ?? ""}${req.headers.get("purpose") ?? ""}`.toLowerCase();
6
+ return !!ua && !BOT.test(ua) && !purpose.includes("prefetch") && !purpose.includes("prerender");
7
+ }
8
+ /** A same-site path, never one a browser reads as another host ("//host" or "/\\host"). */
9
+ const sitePath = (p) => p.startsWith("/") && !/^\/[/\\]/.test(p);
10
+ /** Only redirect to http(s) URLs or same-site paths. */
11
+ function safeLocation(url, fallback) {
12
+ if (typeof url !== "string" || !url) return fallback;
13
+ if (sitePath(url)) return url;
14
+ try {
15
+ const u = new URL(url);
16
+ return u.protocol === "https:" || u.protocol === "http:" ? u.toString() : fallback;
17
+ } catch {
18
+ return fallback;
19
+ }
20
+ }
21
+ const REDIRECTS = new Set([
22
+ 301,
23
+ 302,
24
+ 307,
25
+ 308
26
+ ]);
27
+ /** Long query strings are cut at a parameter boundary rather than refused. */
28
+ const clipQuery = (q) => q.length <= 2e3 ? q : q.slice(0, q.lastIndexOf("&", 2e3) + 1 || 2e3);
29
+ function shortlinkRoute(opts) {
30
+ const fallback = opts.fallback ?? "/";
31
+ const pluginId = opts.pluginId ?? "shortlinks";
32
+ const handler = async (ctx) => {
33
+ const code = (ctx.params.code ?? "").toLowerCase();
34
+ const call = ctx.locals.emdash?.handlePublicPluginApiRoute;
35
+ let location = fallback;
36
+ let status = "missing";
37
+ let redirect = 302;
38
+ if (opts.key && call && /^[a-z0-9][a-z0-9-]{2,31}$/.test(code)) {
39
+ const url = new URL(ctx.request.url);
40
+ url.pathname = `/_emdash/api/plugins/${pluginId}/resolve`;
41
+ url.search = "";
42
+ const cf = ctx.request.cf;
43
+ const body = {
44
+ code,
45
+ scope: opts.scope?.(ctx) ?? "",
46
+ query: clipQuery(ctx.url.search.slice(1)),
47
+ method: ctx.request.method,
48
+ visitor: {
49
+ userAgent: ctx.request.headers.get("user-agent")?.slice(0, 500) ?? null,
50
+ ip: ctx.clientAddress ?? ctx.request.headers.get("cf-connecting-ip"),
51
+ referer: ctx.request.headers.get("referer")?.slice(0, 2e3) ?? null,
52
+ country: cf?.country ?? ctx.request.headers.get("cf-ipcountry"),
53
+ human: human(ctx.request)
54
+ }
55
+ };
56
+ try {
57
+ const data = (await call(pluginId, "POST", "resolve", new Request(url, {
58
+ method: "POST",
59
+ headers: {
60
+ "content-type": "application/json",
61
+ "x-server-key": opts.key
62
+ },
63
+ body: JSON.stringify(body)
64
+ })))?.data;
65
+ status = data?.status ?? "missing";
66
+ let target = safeLocation(data?.url, fallback);
67
+ if (data?.entry && /^https?:/.test(target)) {
68
+ const t = new URL(target);
69
+ target = `${t.pathname}${t.search}${t.hash}`;
70
+ if (!sitePath(target)) target = fallback;
71
+ }
72
+ location = target;
73
+ if (status === "active" && REDIRECTS.has(Number(data?.redirect))) redirect = Number(data?.redirect);
74
+ } catch {
75
+ location = fallback;
76
+ }
77
+ }
78
+ return new Response(null, {
79
+ status: redirect,
80
+ headers: {
81
+ Location: location,
82
+ "Cache-Control": "no-store",
83
+ "X-Robots-Tag": "noindex, nofollow",
84
+ "X-Shortlink": status
85
+ }
86
+ });
87
+ };
88
+ return {
89
+ GET: handler,
90
+ HEAD: handler
91
+ };
92
+ }
93
+
94
+ //#endregion
95
+ export { shortlinkRoute };
@@ -0,0 +1,5 @@
1
+ // Auto-generated by emdash-plugin build. Do not edit.
2
+ import type { PluginDescriptor } from "emdash";
3
+
4
+ declare const descriptor: PluginDescriptor;
5
+ export default descriptor;