diff --git a/jsr.json b/jsr.json index ac97bf3b..8aae9cf0 100644 --- a/jsr.json +++ b/jsr.json @@ -1,8 +1,9 @@ { "name": "@jmondi/oauth2-server", - "version": "3.3.1", + "version": "3.4.0-next.3", "exports": { ".": "./src/index.ts", + "./vanilla": "./src/adapters/vanilla.ts", "./express": "./src/adapters/express.ts", "./fastify": "./src/adapters/fastify.ts", "./vanilla": "./src/adapters/vanilla.ts" diff --git a/package.json b/package.json index 24495931..ee5bcd8f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@jmondi/oauth2-server", - "version": "3.3.1", + "version": "3.4.0-next.3", "type": "module", "author": "Jason Raimondi ", "funding": "https://github.com/sponsors/jasonraimondi", @@ -19,6 +19,7 @@ }, "exports": { ".": "./src/index.ts", + "./vanilla": "./src/adapters/vanilla.ts", "./express": "./src/adapters/express.ts", "./fastify": "./src/adapters/fastify.ts" }, @@ -32,6 +33,11 @@ "require": "./dist/index.cjs", "types": "./dist/index.d.ts" }, + "./vanilla": { + "import": "./dist/vanilla.js", + "require": "./dist/vanilla.cjs", + "types": "./dist/vanilla.d.ts" + }, "./express": { "import": "./dist/express.js", "require": "./dist/express.cjs", @@ -88,6 +94,7 @@ "tsup": { "entry": { "index": "./src/index.ts", + "vanilla": "./src/adapters/vanilla.ts", "express": "./src/adapters/express.ts", "fastify": "./src/adapters/fastify.ts" }, diff --git a/src/adapters/vanilla.ts b/src/adapters/vanilla.ts new file mode 100644 index 00000000..fad369dc --- /dev/null +++ b/src/adapters/vanilla.ts @@ -0,0 +1,57 @@ +import { OAuthRequest } from "../requests/request.js"; +import { OAuthResponse } from "../responses/response.js"; +import { ErrorType, OAuthException } from "../exceptions/oauth.exception.js"; + +export function responseFromVanilla(res: Response): OAuthResponse { + const headers: Record = {}; + Object.entries(res.headers).forEach(([key, value]) => { + headers[key] = value; + }); + + return new OAuthResponse({ + headers: headers, + }); +} + +export function requestFromVanilla(req: Request): OAuthRequest { + const url = new URL(req.url); + const query: Record = {}; + url.searchParams.forEach((value, key) => { + query[key] = value; + }); + + let body: Record = {}; + if (req.body != null) { + body = JSON.parse(req.body.toString()); + } + + const headers: Record = {}; + Object.entries(req.headers).forEach(([key, value]) => { + headers[key] = value; + }); + + return new OAuthRequest({ + query: query, + body: body, + headers: headers, + }); +} + +export function responseToVanilla(oauthResponse: OAuthResponse): Response { + if (oauthResponse.status === 302) { + if (!oauthResponse.headers.location) { + throw new OAuthException(`missing redirect location`, ErrorType.InvalidRequest); + } + return new Response(null, { + status: 302, + headers: { + Location: oauthResponse.headers.location, + }, + }); + } + + return new Response(JSON.stringify(oauthResponse.body), { + status: oauthResponse.status, + headers: oauthResponse.headers, + }); +}