commit
Fix CORS
diff --git a/README.md b/README.md
deleted file mode 100644
index 06a3827..0000000
--- a/README.md
+++ /dev/null
@@ -1,90 +0,0 @@
-<div align="center">
- <h1>CDN</h1>
-
- <p>Clove's personal asset host — images, 3D models, fonts, and sound effects — with a small directory browser and an SSO-gated upload page. A Cloudflare Worker in front of an R2 bucket, at <a href="https://m.doughmination.gay">m.doughmination.gay</a>.</p>
-</div>
-
-## What this is
-
-A Cloudflare Worker that does three jobs:
-
-1. **Serves assets** out of the `cdn` R2 bucket for every other Doughmination site. A request for `/img/foo.png` returns the object `img/foo.png`, with range and conditional-request support so audio/video seek properly.
-2. **Browses itself.** `index.html` fetches `/api/list` (every object in the bucket) and renders folder navigation client-side via the URL hash (e.g. `#/f/Comic-Code`).
-3. **Takes uploads.** `/upload` is gated by the Doughmination SSO (`auth-server/`). Anyone the SSO lets sign in to the `cdn` client can drop files into any folder.
-
-## Layout
-
-```
-cdn/
-├── src/
-│ ├── main.ts Routing: worker routes → static site → R2
-│ ├── auth.ts OIDC sign-in against the SSO (/login, /auth/callback, /logout)
-│ ├── files.ts R2: serve, list, upload
-│ ├── cors.ts CORS allowlist (echoes an allowed Origin back)
-│ ├── genshin.ts GET /genshin/ui/<file>.png → cached enka.network/ui/* proxy
-│ └── views.ts Small server-rendered message pages
-├── public/ The site itself (deployed as Workers static assets)
-│ ├── index.html Directory browser
-│ ├── upload.html Upload page (+ upload.js)
-│ ├── licence.html Rendered licence page (LICENCE.md is served by the worker)
-│ ├── 404.html Not-found page
-│ ├── style.css Shared theme (see "Styling" below)
-│ ├── script.js Browser: folder navigation, filter, copy links
-│ ├── sfx.js UI sounds script, hotlinked by the other sites
-│ └── .well-known/ security.txt, ssh.txt, etc.
-├── assets/ The old in-repo assets, waiting to be copied into R2
-├── scripts/ Model conversion helpers (unrelated to the worker)
-└── wrangler.jsonc
-```
-
-## How the pieces fit
-
-- **Request order:** CORS → worker routes (`/login`, `/auth/*`, `/upload`, `/api/*`, `/genshin/ui/*`, `/LICENCE.md`, `/.well-known/change-password`) → a static file from `public/` → an R2 object → `404.html`. Static files win over R2 objects, so uploads to a path that a site file already uses are refused.
-- **Sign-in:** a standard OIDC authorization-code flow with PKCE, run server-side as a confidential client. The id_token is checked against the SSO's JWKS, then the worker sets its own 12-hour session cookie (an HS256 JWT signed with `SESSION_SECRET`). The worker does no group checks of its own: the SSO only issues codes to accounts in the client's allowed groups, so any valid session may upload. There is no server-side session state.
-- **Uploads:** `PUT /api/files/<path>` with the file as the raw body. It requires a signed-in session and a same-origin `Origin` header, and it won't replace an existing file unless the page's "Replace" box is ticked (`?overwrite=1`). Workers cap request bodies at 100 MB (Free/Pro plans), which limits single uploads to that size.
-- **CORS:** `Access-Control-Allow-Origin` can only be one origin, so `src/cors.ts` keeps an allowlist of the Doughmination domains and echoes back the request's `Origin` when it matches.
-- **Genshin UI proxy:** `src/genshin.ts` fetches `enka.network/ui/<file>.png` once, then serves it from Cloudflare's edge cache (30-day immutable). The API hands out icon URLs pointing here so the Discord bot's Genshin character card can pull splash art / weapon / artifact icons without rate-limiting Enka.
-- **Caching:** files are served with `Cache-Control: public, max-age=86400`, and `/api/list` is cached for 60 seconds. URLs may change at any time, so nothing is cached longer.
-
-## Setup
-
-1. **R2:** create the bucket: `npx wrangler r2 bucket create cdn`.
-2. **SSO:** in the SSO admin (`https://auth.doughmination.gay/admin`):
- - create a group `cdn-upload` and add yourself to it
- - create a **confidential** client with id `cdn`, redirect URI `https://m.doughmination.gay/auth/callback`, and allowed group `cdn-upload`. That allow-list is the only thing deciding who can upload, so don't leave it empty
- - the uploading account needs a verified email, which the SSO requires before it issues codes
-3. **Secrets:**
- ```sh
- npx wrangler secret put OIDC_CLIENT_SECRET # shown once when the client was created
- npx wrangler secret put SESSION_SECRET # openssl rand -base64 32
- ```
-4. **Deploy:** `npm install && npm run deploy`. Then move the `m.doughmination.gay` custom domain from the old Pages project to the worker (or uncomment `routes` in `wrangler.jsonc`), and delete the Pages project.
-5. **Copy the old assets:** everything under `assets/` goes into the bucket with the same paths. For example, `assets/img/bg/main.png` becomes the key `img/bg/main.png`. The dashboard upload works, or:
- ```sh
- cd assets && find . -type f -printf '%P\n' | while IFS= read -r f; do
- npx wrangler r2 object put "cdn/$f" --file "$f" --remote
- done
- ```
- Once they're in R2, `assets/` can be deleted from the repo.
-
-**Local dev:** copy `.dev.vars.example` to `.dev.vars`, then run `npm run dev` (port 8788). Point it at a local auth-server on 8787 that has a `cdn` client with redirect URI `http://localhost:8788/auth/callback`. Local R2 starts empty.
-
-## Styling
-
-The CDN uses the **same look as every other Doughmination site** (see the monorepo `AGENTS.md` → "Uniform styling") — the terminal/clunky redesign:
-
-- Dark trans-pink palette tokens (`--accent: #f5a9b8`, `--bg: #0a0b10`, …), unchanged.
-- **IBM Plex Mono**, loaded from Google Fonts — replaced the old self-hosted Comic Code face.
-- The trans-flag gradient title animation was dropped for a solid `.trans-title` heading with a thin static `.flag-stripe` accent bar above it.
-- Square corners everywhere (`border-radius: 0`) — no more rounded panels/buttons.
-- No emoji in the UI: the folder/file/upload glyphs in `script.js` are small inline SVG icons instead of 📁/📄/⬇.
-
-The one deliberate exception: **no UI sounds here.** `sfx.js` and the `sfx/` files are hosted for the *other* sites to use; the CDN itself stays silent.
-
-## Please don't hotlink
-
-These URLs can change at any time without warning. Anything pointing here may break — mirror what you need instead.
-
-## Licence
-
-Licensed under the **Doughmination Authorised Source Licence (DASL-1.0)**. See [LICENCE.md](./LICENCE.md).
diff --git a/scripts/README.md b/scripts/README.md
deleted file mode 100644
index 0ad164e..0000000
--- a/scripts/README.md
+++ /dev/null
@@ -1,48 +0,0 @@
-# MMD → glb converter
-
-Converts MikuMikuDanceFR `.pmx` models (e.g. the official HoYoverse Genshin
-releases) into web-ready `.glb` for the `/genshin` gallery. Target renderer is
-`<model-viewer>` (standard PBR), so only geometry, normals, UVs and each
-material's **base** texture are kept — sphere maps, toon ramps and morphs are
-dropped (model-viewer can't display them anyway). Handedness is converted from
-MMD (left-handed) to glTF (right-handed).de
-
-## Folders
-
-- `models-src/` — raw model downloads live here. **Not** under `public/`, so the
- `.pmx` + textures are never served to the web. Drop each extracted model folder
- in here (keep each `.pmx` next to its texture folder).
-- `public/models/` — the converted `.glb` files that the site actually serves.
-
-## One-time setup
-
-```bash
-python3 -m venv .venv && source .venv/bin/activate
-pip install -r scripts/requirements.txt
-```
-
-## Convert a model
-
-Run from the project root:
-
-```bash
-python3 scripts/pmx2glb.py "models-src/<folder>/<model>.pmx" "public/models/<name>.glb"
-```
-
-Example:
-
-```bash
-python3 scripts/pmx2glb.py "models-src/paimon/派蒙1.0.pmx" "public/models/paimon.glb"
-```
-
-Then add a card in `src/app/genshin/page.tsx` pointing `model` at the new file.
-
-## Notes
-
-- If a `.rar` won't extract in Finder, install "The Unarchiver" from the App
- Store, or extract with `libarchive` in Python.
-- Chinese/Japanese texture filenames are handled automatically.
-- Textures larger than 2048px are downscaled to keep `.glb` sizes reasonable
- (tweak `MAX_TEX` in `pmx2glb.py` to change this).
-- The script monkey-patches `pymeshio` to read "extended UV" vertices that newer
- Genshin models use — stock pymeshio errors on them.
diff --git a/scripts/pmx2glb.py b/scripts/pmx2glb.py
deleted file mode 100644
index d2d61d8..0000000
--- a/scripts/pmx2glb.py
+++ /dev/null
@@ -1,269 +0,0 @@
-#!/usr/bin/env python3
-# personal/scripts/pmx2glb.py
-# Copyright (c) 2026 Clove Nytrix Doughmination Twilight
-# Licensed under the DASL-1.0 Licence.
-# See LICENCE.md in the project root for full licence information.
-
-"""pmx2glb.py — convert an MMD .pmx model to a self-contained .glb.
-
-Target renderer is <model-viewer> (standard PBR), so we deliberately keep only
-what PBR can show: geometry, normals, UVs and each material's *base* texture.
-Sphere maps, toon ramps and morphs are dropped (model-viewer can't display them
-anyway). Handedness is converted MMD left-handed -> glTF right-handed by negating
-Z and reversing triangle winding.
-"""
-import io, json, os, struct, sys, glob
-from PIL import Image
-from pymeshio import common, pmx as pmxmod
-from pymeshio.pmx import reader
-
-# --- Patch pymeshio: support "extended UV" vertices (extra vec4 UV sets that
-# newer Genshin models carry). Stock pymeshio raises on them (and its exception
-# is itself buggy). We store the count and skip the extra UV floats per vertex. ---
-_orig_init = reader.Reader.__init__
-
-
-def _patched_init(self, ios, text_encoding, extended_uv, vertex_index_size,
- texture_index_size, material_index_size, bone_index_size,
- morph_index_size, rigidbody_index_size):
- common.BinaryReader.__init__(self, ios)
- self.extended_uv = extended_uv
- self.read_text = self.get_read_text(text_encoding)
- if vertex_index_size <= 2:
- self.read_vertex_index = lambda: self.read_uint(vertex_index_size)
- else:
- self.read_vertex_index = lambda: self.read_int(vertex_index_size)
- self.read_texture_index = lambda: self.read_int(texture_index_size)
- self.read_material_index = lambda: self.read_int(material_index_size)
- self.read_bone_index = lambda: self.read_int(bone_index_size)
- self.read_morph_index = lambda: self.read_int(morph_index_size)
- self.read_rigidbody_index = lambda: self.read_int(rigidbody_index_size)
-
-
-def _patched_read_vertex(self):
- pos = self.read_vector3()
- nrm = self.read_vector3()
- uv = self.read_vector2()
- for _ in range(4 * getattr(self, "extended_uv", 0)):
- self.read_float() # discard extra UV channels
- return pmxmod.Vertex(pos, nrm, uv, self.read_deform(), self.read_float())
-
-
-reader.Reader.__init__ = _patched_init
-reader.Reader.read_vertex = _patched_read_vertex
-
-MAX_TEX = 2048 # cap texture dimension to keep glb sizes sane
-
-
-def find_texture(pmx_dir, rel):
- rel = rel.replace("\\", "/")
- cand = os.path.normpath(os.path.join(pmx_dir, rel))
- if os.path.isfile(cand):
- return cand
- # case-insensitive / loose fallback
- base = os.path.basename(rel).lower()
- for root, _dirs, files in os.walk(pmx_dir):
- for f in files:
- if f.lower() == base:
- return os.path.join(root, f)
- return None
-
-
-def load_png_bytes(path):
- im = Image.open(path).convert("RGBA")
- if max(im.size) > MAX_TEX:
- s = MAX_TEX / max(im.size)
- im = im.resize((max(1, int(im.size[0] * s)), max(1, int(im.size[1] * s))))
- # A texture only counts as "transparent" if it has real cut-out regions
- # (pixels that are actually see-through), not merely a fully-opaque alpha
- # channel. Many MMD PNGs carry an all-opaque alpha; treating those as
- # transparent makes <model-viewer> depth-sort them and the model renders
- # see-through / inside-out. Threshold at 128 = genuine holes only.
- lo = im.getchannel("A").getextrema()[0]
- has_cutout = lo < 128
- buf = io.BytesIO()
- im.save(buf, format="PNG")
- return buf.getvalue(), has_cutout
-
-
-def pad4(b, fill=b"\x00"):
- r = (4 - (len(b) % 4)) % 4
- return b + fill * r if r else b
-
-
-def convert(pmx_path, out_path):
- pmx_dir = os.path.dirname(pmx_path)
- m = reader.read_from_file(pmx_path)
- verts = m.vertices
-
- # --- attribute buffers (Z negated for LH->RH) ---
- pos = bytearray(); nrm = bytearray(); uv = bytearray()
- pmin = [1e30, 1e30, 1e30]; pmax = [-1e30, -1e30, -1e30]
- for v in verts:
- px, py, pz = v.position.x, v.position.y, -v.position.z
- nx, ny, nz = v.normal.x, v.normal.y, -v.normal.z
- pos += struct.pack("<3f", px, py, pz)
- nrm += struct.pack("<3f", nx, ny, nz)
- uv += struct.pack("<2f", v.uv.x, v.uv.y)
- for k, val in enumerate((px, py, pz)):
- pmin[k] = min(pmin[k], val); pmax[k] = max(pmax[k], val)
-
- # --- unique textures -> embedded PNG bufferViews ---
- tex_cache = {} # pmx texture_index -> (image_index, has_alpha)
- images = [] # list of (png_bytes,)
- for ti, rel in enumerate(m.textures):
- p = find_texture(pmx_dir, rel)
- if not p:
- continue
- try:
- data, has_cutout = load_png_bytes(p)
- except Exception as e:
- print(f" ! texture skip {rel}: {e}")
- continue
- tex_cache[ti] = (len(images), has_cutout)
- images.append(data)
-
- # --- per-material index runs (winding reversed) ---
- idx = m.indices
- mat_prims = [] # (index_bytes, count, gltf_material_dict)
- off = 0
- for mat in m.materials:
- n = mat.vertex_count
- run = idx[off:off + n]
- off += n
- ib = bytearray()
- for t in range(0, len(run), 3):
- a, b, c = run[t], run[t + 1], run[t + 2]
- ib += struct.pack("<3I", a, c, b) # reverse winding
- col = mat.diffuse_color
- alpha = getattr(mat, "alpha", 1.0)
- pbr = {
- "baseColorFactor": [1.0, 1.0, 1.0, float(alpha)],
- "metallicFactor": 0.0,
- "roughnessFactor": 0.9,
- }
- # Transparency policy that survives a real-time PBR renderer:
- # - texture with genuine cut-outs -> MASK (no depth sorting needed)
- # - uniformly semi-transparent material (mat.alpha < 1) -> BLEND
- # - everything else -> OPAQUE
- # This avoids the see-through/inside-out look you get when every
- # alpha-channel texture is naively marked BLEND.
- alpha_mode = "OPAQUE"
- alpha_cutoff = None
- if mat.texture_index in tex_cache:
- img_i, has_cutout = tex_cache[mat.texture_index]
- pbr["baseColorTexture"] = {"index": img_i}
- if has_cutout:
- alpha_mode = "MASK"
- alpha_cutoff = 0.5
- else:
- pbr["baseColorFactor"] = [col.r, col.g, col.b, float(alpha)]
- if alpha < 1.0:
- alpha_mode = "BLEND"
- alpha_cutoff = None
- gmat = {
- "name": (mat.name or f"mat{len(mat_prims)}")[:40],
- "pbrMetallicRoughness": pbr,
- "doubleSided": True,
- "alphaMode": alpha_mode,
- }
- if alpha_cutoff is not None:
- gmat["alphaCutoff"] = alpha_cutoff
- mat_prims.append((bytes(ib), len(run), gmat))
-
- # ---- assemble single binary buffer ----
- blob = bytearray()
- bviews = []
-
- def add_view(data, target=None):
- data = pad4(bytes(data))
- bv = {"buffer": 0, "byteOffset": len(blob), "byteLength": len(data)}
- if target:
- bv["target"] = target
- blob.extend(data)
- bviews.append(bv)
- return len(bviews) - 1
-
- pos_bv = add_view(pos, 34962)
- nrm_bv = add_view(nrm, 34962)
- uv_bv = add_view(uv, 34962)
-
- accessors = [
- {"bufferView": pos_bv, "componentType": 5126, "count": len(verts),
- "type": "VEC3", "min": pmin, "max": pmax},
- {"bufferView": nrm_bv, "componentType": 5126, "count": len(verts), "type": "VEC3"},
- {"bufferView": uv_bv, "componentType": 5126, "count": len(verts), "type": "VEC2"},
- ]
-
- primitives = []
- materials = []
- for ib, count, gmat in mat_prims:
- if count == 0:
- continue
- ibv = add_view(ib, 34963)
- acc = len(accessors)
- accessors.append({"bufferView": ibv, "componentType": 5125,
- "count": count, "type": "SCALAR"})
- materials.append(gmat)
- primitives.append({
- "attributes": {"POSITION": 0, "NORMAL": 1, "TEXCOORD_0": 2},
- "indices": acc, "material": len(materials) - 1,
- })
-
- gltf_images, gltf_textures = [], []
- for i, data in enumerate(images):
- ibv = add_view(data)
- gltf_images.append({"bufferView": ibv, "mimeType": "image/png"})
- gltf_textures.append({"source": i, "sampler": 0})
-
- gltf = {
- "asset": {"version": "2.0", "generator": "pmx2glb"},
- "scene": 0,
- "scenes": [{"nodes": [0]}],
- "nodes": [{"mesh": 0, "name": m.name or "model"}],
- "meshes": [{"name": m.name or "model", "primitives": primitives}],
- "materials": materials,
- "buffers": [{"byteLength": len(blob)}],
- "bufferViews": bviews,
- "accessors": accessors,
- }
- if gltf_images:
- gltf["images"] = gltf_images
- gltf["textures"] = gltf_textures
- gltf["samplers"] = [{"magFilter": 9729, "minFilter": 9987,
- "wrapS": 10497, "wrapT": 10497}]
-
- json_chunk = pad4(json.dumps(gltf, ensure_ascii=False).encode("utf-8"), b" ")
- bin_chunk = pad4(bytes(blob))
-
- def chunk(ctype, data):
- return struct.pack("<II", len(data), ctype) + data
-
- jc = chunk(0x4E4F534A, json_chunk)
- bc = chunk(0x004E4942, bin_chunk)
- total = 12 + len(jc) + len(bc)
- header = struct.pack("<III", 0x46546C67, 2, total)
- with open(out_path, "wb") as f:
- f.write(header + jc + bc)
-
- print(f" -> {os.path.basename(out_path)}: "
- f"{len(verts)} verts, {sum(c for _, c, _ in mat_prims)//3} tris, "
- f"{len(materials)} prims, {len(images)} textures, "
- f"{total/1024/1024:.2f} MB")
-
-
-if __name__ == "__main__":
- if len(sys.argv) < 2:
- print("usage: python3 scripts/pmx2glb.py <input.pmx> [output.glb]")
- print(" if output is omitted, writes public/models/<input-name>.glb")
- sys.exit(1)
- pmx = sys.argv[1]
- if len(sys.argv) >= 3:
- out = sys.argv[2]
- else:
- # default: public/models/<pmx-filename>.glb (relative to project root)
- stem = os.path.splitext(os.path.basename(pmx))[0]
- out = os.path.join("public", "models", stem + ".glb")
- os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
- print(f" converting {os.path.basename(pmx)} -> {out}")
- convert(pmx, out)
diff --git a/scripts/rename.py b/scripts/rename.py
deleted file mode 100644
index ecf17a7..0000000
--- a/scripts/rename.py
+++ /dev/null
@@ -1,159 +0,0 @@
-#!/usr/bin/env python3
-
-import json
-import re
-import time
-from pathlib import Path
-from urllib.request import Request, urlopen
-from urllib.error import HTTPError, URLError
-
-# Set this to True once you're happy with the output.
-RENAME = True
-
-API = "https://api.pluralkit.me/v2/members/"
-USER_AGENT = "PluralKit Avatar Renamer/1.0"
-
-IMAGE_EXTENSIONS = {".webp", ".png", ".jpg", ".jpeg"}
-
-
-def get_member(member_id):
- url = API + member_id
-
- request = Request(
- url,
- headers={
- "User-Agent": USER_AGENT
- }
- )
-
- try:
- with urlopen(request, timeout=10) as response:
- return json.load(response)
-
- except HTTPError as e:
- if e.code == 404:
- print(f" [!] Member {member_id} does not exist")
- else:
- print(f" [!] API error for {member_id}: HTTP {e.code}")
- return None
-
- except URLError as e:
- print(f" [!] Network error for {member_id}: {e}")
- return None
-
-
-def sanitise_filename(name):
- # Remove characters that aren't valid/useful in filenames.
- name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', name)
-
- # Avoid accidental leading/trailing whitespace.
- name = name.strip()
-
- # Avoid Windows-reserved names too, just in case.
- if name.upper() in {
- "CON", "PRN", "AUX", "NUL",
- "COM1", "COM2", "COM3", "COM4", "COM5",
- "COM6", "COM7", "COM8", "COM9",
- "LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
- "LPT6", "LPT7", "LPT8", "LPT9",
- }:
- name = "_" + name
-
- return name or "unknown"
-
-
-def main():
- directory = Path.cwd()
-
- files = sorted(
- p for p in directory.iterdir()
- if p.is_file()
- and p.suffix.lower() in IMAGE_EXTENSIONS
- and p.name.startswith("avatar-")
- )
-
- if not files:
- print("No avatar files found.")
- return
-
- print(f"Found {len(files)} avatar(s).\n")
-
- planned = []
-
- for index, file in enumerate(files):
- # avatar-abbxvw.webp -> abbxvw
- member_id = file.stem.removeprefix("avatar-")
-
- print(f"{file.name}")
- print(f" Member ID: {member_id}")
-
- member = get_member(member_id)
-
- if member is None:
- print(" -> SKIPPED\n")
- continue
-
- name = member.get("name")
-
- if not name:
- print(" -> Member has no name, skipped\n")
- continue
-
- name = sanitise_filename(name)
-
- destination = directory / f"{name}{file.suffix.lower()}"
-
- # Deal with duplicate member names.
- if destination.exists() and destination != file:
- counter = 2
-
- while True:
- candidate = directory / f"{name} ({counter}){file.suffix.lower()}"
-
- if not candidate.exists():
- destination = candidate
- break
-
- counter += 1
-
- print(f" Name: {name}")
- print(f" Rename: {file.name} -> {destination.name}")
-
- planned.append((file, destination))
-
- print()
-
- # PluralKit currently allows 10 GET requests/sec.
- # 0.12 gives us a little breathing room.
- time.sleep(0.12)
-
- print("=" * 60)
-
- if not planned:
- print("Nothing to rename.")
- return
-
- if not RENAME:
- print("DRY RUN — no files were changed.")
- print()
- print("If everything looks correct, change:")
- print()
- print(" RENAME = False")
- print()
- print("to:")
- print()
- print(" RENAME = True")
- return
-
- print("Renaming files...\n")
-
- for source, destination in planned:
- try:
- source.rename(destination)
- print(f"[OK] {source.name} -> {destination.name}")
- except OSError as e:
- print(f"[!] Failed to rename {source.name}: {e}")
-
-
-if __name__ == "__main__":
- main()
diff --git a/scripts/requirements.txt b/scripts/requirements.txt
deleted file mode 100644
index 0b32a9d..0000000
--- a/scripts/requirements.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-pymeshio==3.0.1
-pygltflib>=1.16
-Pillow>=10.0
diff --git a/scripts/update_avatars.py b/scripts/update_avatars.py
deleted file mode 100644
index c0de426..0000000
--- a/scripts/update_avatars.py
+++ /dev/null
@@ -1,135 +0,0 @@
-#!/usr/bin/env python3
-"""
-Update PluralKit member avatar_urls to point at the CDN copies in pk/avatars.
-
-Matches each <name>.png file in pk/avatars/ to a system member by name
-(exact match, case-insensitive; falls back to fuzzy matching with a
-confirmation prompt), then PATCHes that member's avatar_url to:
-
- https://m.doughmination.gay/pk/avatars/<name>.png
-
-Run from anywhere; it always looks at pk/avatars/ next to the repo root
-(one level up from this script's scripts/ folder).
-Requires the `requests` package.
-"""
-
-import difflib
-import getpass
-import sys
-from pathlib import Path
-
-import requests
-
-API_BASE = "https://api.pluralkit.me/v2"
-CDN_BASE = "https://m.doughmination.gay/pk/avatars"
-AVATARS_DIR = Path(__file__).resolve().parent.parent / "pk" / "avatars"
-FUZZY_CUTOFF = 0.6 # difflib similarity threshold for suggesting a fuzzy match
-
-
-def get_members(token: str) -> list[dict]:
- resp = requests.get(
- f"{API_BASE}/systems/@me/members",
- headers={"Authorization": token},
- timeout=30,
- )
- resp.raise_for_status()
- return resp.json()
-
-
-def find_match(stem: str, members: list[dict], by_name: dict[str, dict]) -> dict | None:
- lower = stem.lower()
-
- # exact match on name or display_name (case-insensitive)
- if lower in by_name:
- return by_name[lower]
-
- # fuzzy fallback, confirmed interactively
- candidates = difflib.get_close_matches(lower, by_name.keys(), n=3, cutoff=FUZZY_CUTOFF)
- if not candidates:
- return None
-
- print(f"\n No exact match for '{stem}'. Closest candidates:")
- options = [by_name[c] for c in candidates]
- for i, m in enumerate(options, start=1):
- label = m["name"]
- if m.get("display_name") and m["display_name"].lower() != m["name"].lower():
- label += f" (display: {m['display_name']})"
- print(f" {i}. {label} [{m['id']}]")
- print(" 0. skip")
-
- choice = input(" Pick a match [0]: ").strip()
- if not choice or choice == "0":
- return None
- try:
- idx = int(choice)
- if 1 <= idx <= len(options):
- return options[idx - 1]
- except ValueError:
- pass
- print(" Invalid choice, skipping.")
- return None
-
-
-def main() -> int:
- token = getpass.getpass("PluralKit authorization token: ").strip()
- if not token:
- print("No token given, aborting.")
- return 1
-
- try:
- members = get_members(token)
- except requests.HTTPError as e:
- print(f"Failed to fetch members: {e}")
- return 1
-
- by_name: dict[str, dict] = {}
- for m in members:
- by_name.setdefault(m["name"].lower(), m)
- if m.get("display_name"):
- by_name.setdefault(m["display_name"].lower(), m)
-
- png_files = sorted(AVATARS_DIR.glob("*.png"))
- if not png_files:
- print("No .png files found here.")
- return 1
-
- updated, skipped = [], []
-
- for path in png_files:
- stem = path.stem
- member = find_match(stem, members, by_name)
- if member is None:
- print(f"[skip] {path.name} -> no member match")
- skipped.append(path.name)
- continue
-
- url = f"{CDN_BASE}/{path.name}"
- confirm = input(
- f"[match] {path.name} -> {member['name']} [{member['id']}] set avatar_url? [Y/n] "
- ).strip().lower()
- if confirm == "n":
- print(" skipped by user")
- skipped.append(path.name)
- continue
-
- resp = requests.patch(
- f"{API_BASE}/members/{member['id']}",
- headers={"Authorization": token},
- json={"avatar_url": url},
- timeout=30,
- )
- if resp.status_code == 200:
- print(f" updated -> {url}")
- updated.append(path.name)
- else:
- print(f" FAILED ({resp.status_code}): {resp.text}")
- skipped.append(path.name)
-
- print(f"\nDone. Updated {len(updated)}, skipped {len(skipped)}.")
- if skipped:
- print("Skipped:", ", ".join(skipped))
- return 0
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/src/cors.ts b/src/cors.ts
index ed0bbcc..96d2dfa 100644
--- a/src/cors.ts
+++ b/src/cors.ts
@@ -9,36 +9,14 @@ import type { AppEnv } from "./env";
const ALLOWED: string[] = [
// Mine
- "clovelib.win",
- "clove-portfolio.win",
- "cuddle-blahaj.win",
"doughmination.co.uk",
"doughmination.gay",
- "doughmination.info",
- "doughmination.me",
- "doughmination.net",
- "doughmination.online",
- "doughmination.org",
- "doughmination.site",
- "doughmination.systems",
- "doughmination.tech",
- "doughmination.uk",
- "doughmination.win",
- "doughmination.xyz",
"imlesbian.fyi",
- "transgamers.org",
- "yuri-lover.win",
+ "pkviewer.xyz",
- // gf
- "ariare.es",
- "ari.rip",
+ // Other Sites
"gaybot.site",
- "girlsnetwork.dev",
- "kib.lol",
- "stupid.cat",
- "thesafespawn.net",
-
- // Friends — add domains here
+ "bwah.dev",
];
// Exact origins for local development (scheme + host + port must match)