Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ storybook-static

.cache
.netlify
.wrangler
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ yarn storybook
yarn build-storybook
```

## Cloudflare beta deployment

The beta Worker serves the Vite build and handles the NotifyComp token endpoint. Its custom domain is
`beta.competitiongroups.com`; production remains on Netlify until the main-domain cutover.

```bash
yarn build
yarn cf:dev
yarn cf:deploy
```

Set `COMPETITION_GROUPS_JWT_SECRET` as a Cloudflare Worker secret before testing NotifyComp login,
remote access, or assignment notifications. Do not commit it or put it in Vite environment variables.

During `yarn dev`, NotifyComp token requests are proxied to
`https://www.competitiongroups.com`, so production WCA sign-in and NotifyComp
authorization work without running Netlify Functions locally. The deployed
Expand Down
170 changes: 170 additions & 0 deletions cloudflare/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
interface Env {
ASSETS: { fetch(request: Request): Promise<Response> };
COMPETITION_GROUPS_JWT_SECRET: string;
COMPETITION_GROUPS_JWT_AUDIENCE?: string;
COMPETITION_GROUPS_JWT_ISSUER?: string;
WCA_ORIGIN?: string;
}

interface WcaUser {
id: number;
name?: string;
}

interface WcaCompetition {
id?: string;
organizers?: WcaUser[];
delegates?: WcaUser[];
competition?: WcaCompetition;
}

interface WcaMeResponse {
me?: WcaUser;
ongoing_competitions?: WcaCompetition[];
upcoming_competitions?: WcaCompetition[];
}

const TOKEN_PATH = '/api/notify-comp-token';
const REMOTE_SCOPE = 'notifycomp.remote';
const PUSH_SCOPE = 'assignment_notifications';
const REMOTE_TOKEN_TTL_SECONDS = 12 * 60 * 60;
const PUSH_TOKEN_TTL_SECONDS = 10 * 60;
const responseHeaders = {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
};

const jsonResponse = (status: number, body?: Record<string, unknown>) =>
new Response(body ? JSON.stringify(body) : null, { status, headers: responseHeaders });

const base64Url = (bytes: Uint8Array) => {
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
};

const encodeBase64Url = (value: string) => base64Url(new TextEncoder().encode(value));

const signJwt = async (claims: Record<string, unknown>, secret: string) => {
const encodedHeader = encodeBase64Url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
const encodedPayload = encodeBase64Url(JSON.stringify(claims));
const unsignedToken = `${encodedHeader}.${encodedPayload}`;
const key = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign'],
);
const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(unsignedToken));

return `${unsignedToken}.${base64Url(new Uint8Array(signature))}`;
};

const getCompetitionManagers = (competition: WcaCompetition) => {
const data = competition.competition || competition;
return [...(data.organizers || []), ...(data.delegates || [])];
};

const isListedCompetitionManager = (competition: WcaCompetition, userId: number) =>
getCompetitionManagers(competition).some((user) => Number(user.id) === Number(userId));

const getManagedCompetitionIds = (competitions: WcaCompetition[], userId: number) =>
competitions
.filter((competition) => isListedCompetitionManager(competition, userId))
.map((competition) => competition.id)
.filter((id): id is string => Boolean(id));

const handleTokenRequest = async (request: Request, env: Env) => {
if (request.method === 'OPTIONS') return jsonResponse(204);
if (request.method !== 'POST') return jsonResponse(405, { message: 'Method not allowed' });
if (!env.COMPETITION_GROUPS_JWT_SECRET) {
return jsonResponse(500, { message: 'Notification token secret is not configured' });
}

let body: { accessToken?: string; competitionId?: string; scope?: string };
try {
body = (await request.json()) as typeof body;
} catch {
return jsonResponse(400, { message: 'Invalid JSON body' });
}

const { accessToken, competitionId, scope } = body;
const tokenScope = scope === REMOTE_SCOPE ? REMOTE_SCOPE : PUSH_SCOPE;
if (!accessToken) return jsonResponse(400, { message: 'Missing WCA access token' });
if (tokenScope === REMOTE_SCOPE && !competitionId) {
return jsonResponse(400, { message: 'Missing competition ID for remote token' });
}

const wcaOrigin = env.WCA_ORIGIN || 'https://www.worldcubeassociation.org';
const meParams =
tokenScope === REMOTE_SCOPE ? '?upcoming_competitions=true&ongoing_competitions=true' : '';
const meResponse = await fetch(`${wcaOrigin}/api/v0/me${meParams}`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (!meResponse.ok) return jsonResponse(401, { message: 'Invalid WCA access token' });

const {
me,
ongoing_competitions = [],
upcoming_competitions = [],
} = (await meResponse.json()) as WcaMeResponse;
if (!me?.id) return jsonResponse(401, { message: 'Unable to resolve WCA user' });

let remoteCompetitionIds: string[] = [];
if (tokenScope === REMOTE_SCOPE) {
const competitionResponse = await fetch(
`${wcaOrigin}/api/v0/competitions/${encodeURIComponent(competitionId!)}`,
{ headers: { Authorization: `Bearer ${accessToken}` } },
);
if (!competitionResponse.ok) {
return jsonResponse(competitionResponse.status === 404 ? 404 : 502, {
message: 'Unable to verify competition remote access',
});
}

const competition = (await competitionResponse.json()) as WcaCompetition;
if (!isListedCompetitionManager(competition, me.id)) {
return jsonResponse(403, {
message: 'Only listed competition delegates and organizers can use Live Activities Remote',
});
}

remoteCompetitionIds = [
...new Set([
competitionId!,
...getManagedCompetitionIds([...ongoing_competitions, ...upcoming_competitions], me.id),
]),
];
}

const now = Math.floor(Date.now() / 1000);
const token = await signJwt(
{
aud: env.COMPETITION_GROUPS_JWT_AUDIENCE || 'notifycomp',
competitionIds: tokenScope === REMOTE_SCOPE ? remoteCompetitionIds : undefined,
exp: now + (tokenScope === REMOTE_SCOPE ? REMOTE_TOKEN_TTL_SECONDS : PUSH_TOKEN_TTL_SECONDS),
iat: now,
iss: env.COMPETITION_GROUPS_JWT_ISSUER || 'competitiongroups.com',
name: me.name,
scope: tokenScope,
scopes: [tokenScope],
sub: `wca:${me.id}`,
wcaUserId: me.id,
wcaUserIds: [me.id],
},
env.COMPETITION_GROUPS_JWT_SECRET,
);

return jsonResponse(200, { token });
};

export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === TOKEN_PATH) return handleTokenRequest(request, env);
return env.ASSETS.fetch(request);
},
};
5 changes: 5 additions & 0 deletions netlify.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
[[redirects]]
from = "/api/notify-comp-token"
to = "/.netlify/functions/notify-comp-token"
status = 200

[[redirects]]
from = "/*"
to = "/index.html"
Expand Down
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"cf:dev": "wrangler dev",
"cf:preview": "wrangler preview",
"cf:deploy": "wrangler deploy",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build",
"test": "jest",
Expand Down Expand Up @@ -95,7 +98,8 @@
"surge": "^0.23.1",
"ts-jest": "^29.3.4",
"ts-node": "^10.9.2",
"typescript-eslint": "^8.32.1"
"typescript-eslint": "^8.32.1",
"wrangler": "4.166.0"
},
"browserslist": {
"production": [
Expand Down
2 changes: 1 addition & 1 deletion src/lib/notifications/assignmentNotifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {

const NOTIFY_COMP_ORIGIN =
import.meta.env.VITE_NOTIFY_COMP_ORIGIN ?? 'https://api.notifycomp.com/api';
const NOTIFY_COMP_TOKEN_URL = '/.netlify/functions/notify-comp-token';
const NOTIFY_COMP_TOKEN_URL = '/api/notify-comp-token';
const ENABLED_STORAGE_KEY = 'assignmentNotifications.enabled';
const SERVICE_WORKER_TIMEOUT_MS = 10000;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { getStoredWcaAccessToken } from '@/lib/wcaAccessToken';
import { useAuth } from '../AuthProvider';
import { NotifyCompRemoteAuthContext } from './NotifyCompRemoteAuthContext';

const NOTIFY_COMP_TOKEN_URL = '/.netlify/functions/notify-comp-token';
const NOTIFY_COMP_TOKEN_URL = '/api/notify-comp-token';
const PENDING_REMOTE_COMPETITION_ID_KEY = 'notifyComp.pendingRemoteCompetitionId';
const REMOTE_SCOPE = 'notifycomp.remote';

Expand Down
2 changes: 1 addition & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export default defineConfig(({ mode }) => ({
server: {
proxy: {
// Use the deployed token issuer when running without Netlify Dev.
'^/\\.netlify/functions/notify-comp-token(?:\\?|$)': {
'^/api/notify-comp-token(?:\\?|$)': {
target:
loadEnv(mode, process.cwd(), 'NOTIFY_COMP_').NOTIFY_COMP_TOKEN_ORIGIN ||
'https://www.competitiongroups.com',
Expand Down
18 changes: 18 additions & 0 deletions wrangler.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "competition-groups-beta",
"main": "./cloudflare/worker.ts",
"compatibility_date": "2026-11-23",
"routes": [
{
"pattern": "beta.competitiongroups.com",
"custom_domain": true,
},
],
"assets": {
"directory": "./dist/",
"binding": "ASSETS",
"not_found_handling": "single-page-application",
"run_worker_first": ["/api/notify-comp-token"],
},
}
Loading
Loading