Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

131 linesCodeBlameRaw
1import { env } from "cloudflare:workers";
2import { data } from "react-router";
3
4import { notifyClient, type NotifyPreferencesChange, type PresenceChange, type PushDevice, type PushSubscriptionJson } from "@g1t/contracts";
5import type { SoundSettingsChange } from "@g1t/contracts/sounds";
6
7import type { Route } from "./+types/api";
8import { repoFor } from "../../lib/access.server";
9import { identity } from "../../lib/services.server";
10import { assertSameOrigin, requireUser, roleIn } from "../../lib/session.server";
11
12function client() {
13 if (!env.NOTIFY) throw data({ error: "Notifications are not set up here." }, { status: 503 });
14 return notifyClient(env.NOTIFY);
15}
16
17/**
18 * The signed-in person's notification settings, as JSON: `GET` their
19 * status (with `?endpoint=` for whether this browser gets pushes, and how
20 * many phones do), `POST` a change: `subscribe`, `unsubscribe`,
21 * `register_device` and `unregister_device` (the phone app, with its Expo
22 * push token), `preferences`, `test`, `presence` (your status, being away,
23 * Do Not Disturb), `sounds` (what you hear when chat moves, kept with
24 * the account by identity), or `watch_repo`, for a repository page that
25 * updates live: its tabs then hear what changes there (`repo`, its
26 * `owner/name`), once the person is found to be able to read it
27 * (lib/repo-live.ts); `watch_repos` the same for several at once (`repos`,
28 * at most WATCH_REPOS_MAX: Home watches its workspace's); `watch_workspace`
29 * for a workspace's Work pages (`workspace`, its slug): its members' tabs
30 * then hear what changes to its work items.
31 *
32 * The phone app calls this with its access token and no `Origin`, which
33 * the same-origin check lets through (lib/same-origin.ts).
34 */
35export async function loader({ context, request }: Route.LoaderArgs) {
36 const user = requireUser(context, request);
37 const endpoint = new URL(request.url).searchParams.get("endpoint");
38 const status = await client().status(user, endpoint);
39 return Response.json(status, { headers: { "cache-control": "no-store" } });
40}
41
42type Sent = {
43 intent?: string;
44 subscription?: PushSubscriptionJson & { expirationTime?: number | null };
45 endpoint?: string;
46 device?: PushDevice;
47 token?: string;
48 preferences?: NotifyPreferencesChange;
49 change?: PresenceChange | SoundSettingsChange;
50 repo?: string;
51 repos?: unknown;
52 workspace?: string;
53};
54
55/** The most repositories one `watch_repos` asks for (notify keeps 50 per person). */
56const WATCH_REPOS_MAX = 25;
57
58/** Watches `path` (`owner/name`) for `user` when they can read it; the repository's id, or null. */
59async function watchOne(context: Route.ActionArgs["context"], notify: ReturnType<typeof client>, user: ReturnType<typeof requireUser>, path: string) {
60 // Only a repository they can read: the same lookup its pages make.
61 const [owner, name, ...rest] = path.split("/");
62 if (!owner || !name || rest.length) return null;
63 const found = await repoFor(context, { owner, repo: name });
64 if (!found.ok) return null;
65 const repo = found.value;
66 const watched = await notify.watchRepo(user, repo.id, `${repo.namespace}/${repo.name}`);
67 return { ...watched, repo_id: repo.id };
68}
69
70export async function action({ context, request }: Route.ActionArgs) {
71 assertSameOrigin(request);
72 const user = requireUser(context, request);
73 const sent = (await request.json().catch(() => ({}))) as Sent;
74 const notify = client();
75 switch (sent.intent) {
76 case "subscribe": {
77 const s = sent.subscription;
78 if (!s?.endpoint || !s.keys?.p256dh || !s.keys?.auth) return Response.json({ ok: false }, { status: 400 });
79 const subscription: PushSubscriptionJson = { endpoint: s.endpoint, keys: { p256dh: s.keys.p256dh, auth: s.keys.auth } };
80 return Response.json(await notify.subscribe(user, subscription, request.headers.get("user-agent")));
81 }
82 case "unsubscribe":
83 return Response.json(await notify.unsubscribe(user, String(sent.endpoint ?? "")));
84 case "register_device": {
85 const d = sent.device;
86 if (typeof d?.token !== "string" || (d.platform !== "android" && d.platform !== "ios")) return Response.json({ ok: false }, { status: 400 });
87 const device: PushDevice = { token: d.token, platform: d.platform, name: typeof d.name === "string" ? d.name : null };
88 const registered = await notify.registerDevice(user, device);
89 // The service checks the token is Expo's; `off` is this g1t sending phones nothing (PHONE_PUSH=off), not a mistake.
90 return Response.json(registered, { status: registered.ok || registered.off ? 200 : 400 });
91 }
92 case "unregister_device":
93 return Response.json(await notify.unregisterDevice(user, String(sent.token ?? "")));
94 case "preferences":
95 return Response.json(await notify.setPreferences(user, sent.preferences ?? {}));
96 case "test":
97 return Response.json(await notify.test(user));
98 case "sounds": {
99 const saved = await identity.setSoundSettings(user, (sent.change ?? {}) as SoundSettingsChange);
100 if (!saved.ok) return Response.json({ ok: false, error: saved.error.message }, { status: 400 });
101 return Response.json(saved.value);
102 }
103 case "presence": {
104 // Set by hand here: a calendar's or an integration's comes through their own door.
105 const change = (sent.change ?? {}) as PresenceChange;
106 const status = change.status ? { ...change.status, source: "manual" as const } : change.status;
107 return Response.json(await notify.setPresence(user, { ...change, ...("status" in change ? { status } : {}) }));
108 }
109 case "watch_repo": {
110 const path = String(sent.repo ?? "");
111 if (path.split("/").length !== 2) return Response.json({ ok: false }, { status: 400 });
112 const watched = await watchOne(context, notify, user, path);
113 return watched ? Response.json(watched) : Response.json({ ok: false }, { status: 404 });
114 }
115 case "watch_repos": {
116 const paths = Array.isArray(sent.repos) ? [...new Set(sent.repos.filter((path): path is string => typeof path === "string"))] : [];
117 if (paths.length === 0 || paths.length > WATCH_REPOS_MAX) return Response.json({ ok: false }, { status: 400 });
118 const watched = (await Promise.all(paths.map((path) => watchOne(context, notify, user, path).catch(() => null)))).filter((one) => one?.ok);
119 return Response.json({ ok: watched.length > 0, repo_ids: watched.map((one) => one!.repo_id) });
120 }
121 case "watch_workspace": {
122 const slug = String(sent.workspace ?? "").toLowerCase();
123 if (!slug) return Response.json({ ok: false }, { status: 400 });
124 // Only a workspace they belong to: what changes to its work items is its members'.
125 if (roleIn(user, slug) == null) return Response.json({ ok: false }, { status: 404 });
126 return Response.json(await notify.watchWorkspace(user, slug));
127 }
128 default:
129 return Response.json({ ok: false }, { status: 400 });
130 }
131}