From 52e28067d86bdfa1193c7ad581c789d13c04b3f9 Mon Sep 17 00:00:00 2001 From: oitsjustjose Date: Tue, 31 Dec 2024 16:19:05 -0600 Subject: [PATCH] Modrinth OAuth support --- backend/src/app/controllers/job/put.ts | 6 +- backend/src/app/models/Job.ts | 4 +- frontend/src/App.css | 10 +++ frontend/src/components/Help/Info.jsx | 21 +++---- frontend/src/pages/Home.jsx | 86 +++++++++++++++----------- frontend/src/shared/index.js | 41 ++++++++++++ processor/src/common.py | 3 +- processor/src/mgmt_tools.py | 3 +- processor/src/x_fast_provider.py | 10 +-- processor/src/x_slow_provider.py | 7 +-- 10 files changed, 125 insertions(+), 66 deletions(-) create mode 100644 frontend/src/shared/index.js diff --git a/backend/src/app/controllers/job/put.ts b/backend/src/app/controllers/job/put.ts index defd9f5..ba71cb8 100644 --- a/backend/src/app/controllers/job/put.ts +++ b/backend/src/app/controllers/job/put.ts @@ -16,7 +16,7 @@ const getNextQueuePlace = async () => { export default async (req: Request, res: Response) => { try { if ( - !req.body.githubPat || + !req.body.oauthToken || !req.body.curseforgeSlug || !req.body.modrinthId ) { @@ -25,7 +25,7 @@ export default async (req: Request, res: Response) => { .send( [ "Missing a required parameter in the JSON body", - "Required params: githubPat: string, curseforgeSlug: string, modrinthId: string", + "Required params: oauthToken: string, curseforgeSlug: string, modrinthId: string", ].join(" ") ); } @@ -33,7 +33,7 @@ export default async (req: Request, res: Response) => { const fern = new Fernet(process.env.SECRET); const newJob = new Job({ - githubPat: fern.encrypt(req.body.githubPat), + oauthToken: fern.encrypt(req.body.oauthToken), curseforgeSlug: req.body.curseforgeSlug, modrinthId: req.body.modrinthId, queuePlace: await getNextQueuePlace(), diff --git a/backend/src/app/models/Job.ts b/backend/src/app/models/Job.ts index 3e6357a..1ba37ca 100644 --- a/backend/src/app/models/Job.ts +++ b/backend/src/app/models/Job.ts @@ -4,7 +4,7 @@ import Status from "../status"; export type JobType = Document & { jobId: string; - githubPat: string; + oauthToken: string; curseforgeSlug: string; modrinthId: string; logs: string; @@ -18,7 +18,7 @@ const JobSchema = new Schema({ default: shortid.generate, required: true, }, - githubPat: { + oauthToken: { type: String, required: true, }, diff --git a/frontend/src/App.css b/frontend/src/App.css index 750ea4a..c96ebe4 100644 --- a/frontend/src/App.css +++ b/frontend/src/App.css @@ -65,3 +65,13 @@ button.info svg { button svg { vertical-align: top; } + +button.modrinth { + background-color: #1bd96a; + color: black; +} + +button.modrinth:hover { + background-color: #14a551; + color: black; +} diff --git a/frontend/src/components/Help/Info.jsx b/frontend/src/components/Help/Info.jsx index a24d8b6..6da0009 100644 --- a/frontend/src/components/Help/Info.jsx +++ b/frontend/src/components/Help/Info.jsx @@ -1,6 +1,7 @@ import React, { useState } from 'react'; -import { Modal, Image } from 'react-bootstrap'; +import { Modal, Image, Button } from 'react-bootstrap'; import ThirdPartyHelp from '../../img/cftpd.png'; +import { DoModrinthOauth } from '../../shared'; export default ({ dark, override, propagateOnHide }) => { const [show, setShow] = useState(!window.localStorage.getItem('info-dismissed')); @@ -31,18 +32,6 @@ export default ({ dark, override, propagateOnHide }) => {

+ +
+ +
); diff --git a/frontend/src/pages/Home.jsx b/frontend/src/pages/Home.jsx index c6b3729..4da3747 100644 --- a/frontend/src/pages/Home.jsx +++ b/frontend/src/pages/Home.jsx @@ -8,17 +8,65 @@ import OutputLog from '../components/OutputLog'; import Info from '../components/Help/Info'; import HeaderImg from '../img/ctm.png'; import ModrinthProjId from '../components/Help/ModrinthProjId'; +import { DoModrinthOauth, GetModrinthOauth, ModrinthOauthCallbackHandler } from '../shared'; export default () => { const [dark, setDark] = useState(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches); const [modals, setModals] = useState({ info: false, mpid: false }); const [jobId, setJobId] = useState(window.localStorage.getItem('last-jobid')); const [formData, setFormData] = useState({ - githubPat: '', curseforgeSlug: '', modrinthId: '', }); + const makeJob = async (evt) => { + evt && evt.preventDefault(); + if (!formData.curseforgeSlug.length) return; + if (!formData.modrinthId.length) return; + + /* OAuth block to verify we're logged in */ + const oauthToken = GetModrinthOauth(); + if (!oauthToken) { + DoModrinthOauth(formData.curseforgeSlug, formData.modrinthId); + return; + } + + const body = { + curseforgeSlug: formData.curseforgeSlug, + modrinthId: formData.modrinthId, + oauthToken, + }; + + const resp = await fetch('/api/v1/jobs', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + + if (resp && resp.ok) { + const data = await resp.text(); + setJobId(data); + window.localStorage.setItem('last-jobid', data); + } + }; + + useEffect(() => { // Handle the Modrinth OAuth callback + const newFormData = ModrinthOauthCallbackHandler(); + if (!newFormData) return () => { }; + + setFormData({ ...newFormData }); + makeJob(); + + // Push state w/o URLQuery to avoid infinite reload of the page + if (window.history.pushState) { + const url = new URL(window.location.href); + url.search = ''; + window.history.pushState({ path: url.toString() }, '', url.toString()); + } + + return () => { }; + }, [ModrinthOauthCallbackHandler, setFormData, makeJob]); + useEffect(() => { // DARK MODE STUFF HERE // Set initial state before even bothering with the update state window.document.scrollingElement.setAttribute('data-bs-theme', dark ? 'dark' : 'light'); @@ -36,25 +84,6 @@ export default () => { return () => pref.removeEventListener('change', onChange); }, [dark, setDark]); - const makeJob = async (evt) => { - evt.preventDefault(); - if (!formData.githubPat.length) return; - if (!formData.curseforgeSlug.length) return; - if (!formData.modrinthId.length) return; - - const resp = await fetch('/api/v1/jobs', { - method: 'PUT', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(formData), - }); - - if (resp && resp.ok) { - const data = await resp.text(); - setJobId(data); - window.localStorage.setItem('last-jobid', data); - } - }; - return (
{ igrator

- - GitHub Personal Access Token - setFormData({ - ...formData, - githubPat: x.target.value, - })} - /> - - This value is encrypted from end-to-end and even in storage - - - CurseForge Project Slug { + const uri = new URL(`${window.location.origin}${window.location.pathname}`); + curseforgeSlug && curseforgeSlug.length && uri.searchParams.set('curseforgeSlug', curseforgeSlug); + modrinthId && curseforgeSlug.length && uri.searchParams.set('modrinthId', modrinthId); + return `https://modrinth.com/auth/authorize?client_id=50zijYLk&redirect_uri=${encodeURIComponent(uri.toString())}&scope=PROJECT_WRITE+VERSION_CREATE`; +}; + +export const GetModrinthOauth = () => window.localStorage.getItem(OAUTH_KEY); + +/** + * + * @param {string | null} curseforgeSlug + * @param {string | null} modrinthId + * @returns + */ +export const DoModrinthOauth = (curseforgeSlug, modrinthId) => { + const uri = CreateModrinthUri(curseforgeSlug, modrinthId); + window.location.href = uri; +}; + +/** + * Handles Modrinth's callback after OAuth is completed + */ +export const ModrinthOauthCallbackHandler = () => { + const params = new URLSearchParams(window.location.search); + if (!params.has('code')) return null; + + window.localStorage.setItem(OAUTH_KEY, params.get('code')); + params.delete('code'); + + const ret = Object.fromEntries(params); + return Object.keys(ret).length ? ret : null; +}; diff --git a/processor/src/common.py b/processor/src/common.py index 99eff5e..0ed22e5 100644 --- a/processor/src/common.py +++ b/processor/src/common.py @@ -2,6 +2,7 @@ Houses commonly used dataclasses and Enums Author: oitsjustjose @ modrinth/curseforge/twitter """ + from dataclasses import dataclass from enum import Enum from typing import List @@ -23,7 +24,7 @@ class Status(Enum): class Job: """A single job""" - github_pat: str + oauth_token: str curseforge_slug: str modrinth_id: str job_id: str = "" diff --git a/processor/src/mgmt_tools.py b/processor/src/mgmt_tools.py index e1c6a09..d72e445 100644 --- a/processor/src/mgmt_tools.py +++ b/processor/src/mgmt_tools.py @@ -2,6 +2,7 @@ Houses API Tools when communicating with the RESTful API Author: oitsjustjose @ modrinth/curseforge/twitter """ + from os import environ as env from typing import Dict, List, Union @@ -54,7 +55,7 @@ class MgmtApiHelper: def _dict_to_job(self, data: Dict) -> Job: """Converts a dictionary (from mongo) into a Job""" return Job( - github_pat=self._fernet.decrypt(data["githubPat"]), + oauth_token=self._fernet.decrypt(data["oauthToken"]), curseforge_slug=data["curseforgeSlug"], modrinth_id=data["modrinthId"], logs=data["logs"] if "logs" in data else [], diff --git a/processor/src/x_fast_provider.py b/processor/src/x_fast_provider.py index 4854f62..e08ff32 100644 --- a/processor/src/x_fast_provider.py +++ b/processor/src/x_fast_provider.py @@ -97,7 +97,7 @@ class FastProvider(MgmtApiLogger): response = requests.post( "https://api.modrinth.com/v2/version", timeout=30, - headers={"Authorization": self._job.github_pat}, + headers={"Authorization": self._job.oauth_token}, files=[ ("data", (None, payload, None)), ("files", (jar_fn, jar_data, "application/octet-stream")), @@ -179,9 +179,7 @@ class FastProvider(MgmtApiLogger): status = ( Status.PARTIAL_FAIL if any_succ and any_fail - else Status.SUCCESS - if any_succ and not any_fail - else Status.FAIL + else Status.SUCCESS if any_succ and not any_fail else Status.FAIL ) return status @@ -206,5 +204,7 @@ class FastProvider(MgmtApiLogger): return "downloadUrl" in data[0] return False except TimeoutError: - self.logmsg("🕜 Timed out determining if Mod supports third party downloads") + self.logmsg( + "🕜 Timed out determining if Mod supports third party downloads" + ) return False diff --git a/processor/src/x_slow_provider.py b/processor/src/x_slow_provider.py index c16b6bf..822b6cd 100644 --- a/processor/src/x_slow_provider.py +++ b/processor/src/x_slow_provider.py @@ -4,6 +4,7 @@ @description: A SLOW working mod migrator from Curse to Modrinth This one is used if you're a jerk and disable third party launchers """ + import json from os import environ as env from os import makedirs, path @@ -219,7 +220,7 @@ class SlowProvider(MgmtApiLogger): response = requests.post( "https://api.modrinth.com/v2/version", timeout=30, - headers={"Authorization": self._job.github_pat}, + headers={"Authorization": self._job.oauth_token}, files=[ ("data", (None, payload, None)), ("files", (fpath, jar_data, "application/octet-stream")), @@ -263,9 +264,7 @@ class SlowProvider(MgmtApiLogger): status = ( Status.PARTIAL_FAIL if any_succ and any_fail - else Status.SUCCESS - if any_succ and not any_fail - else Status.FAIL + else Status.SUCCESS if any_succ and not any_fail else Status.FAIL ) rmdir(f"./out/{self._job.curseforge_slug}") return status