mirror of
https://github.com/roleypoly/roleypoly.git
synced 2025-06-17 01:59:08 +00:00
big overhaul (#474)
* miniflare init * feat(api): add tests * chore: more tests, almost 100% * add sessions/state spec * add majority of routes and datapaths, start on interactions * nevermind, no interactions * nevermind x2, tweetnacl is bad but SubtleCrypto has what we need apparently * simplify interactions verify * add brute force interactions tests * every primary path API route is refactored! * automatically import from legacy, or die trying. * check that we only fetch legacy once, ever * remove old-src, same some historic pieces * remove interactions & worker-utils package, update misc/types * update some packages we don't need specific pinning for anymore * update web references to API routes since they all changed * fix all linting issues, upgrade most packages * fix tests, divorce enzyme where-ever possible * update web, fix integration issues * pre-build api * fix tests * move api pretest to api package.json instead of CI * remove interactions from terraform, fix deploy side configs * update to tf 1.1.4 * prevent double writes to worker in GCS, port to newer GCP auth workflow * fix api.tf var refs, upgrade node action * change to curl-based script upload for worker script due to terraform provider limitations * oh no, cloudflare freaked out :(
This commit is contained in:
parent
b644a38aa7
commit
3291f9aacc
183 changed files with 9853 additions and 9924 deletions
53
packages/api/src/sessions/create.spec.ts
Normal file
53
packages/api/src/sessions/create.spec.ts
Normal file
|
@ -0,0 +1,53 @@
|
|||
jest.mock('../utils/discord');
|
||||
|
||||
import { AuthTokenResponse } from '@roleypoly/types';
|
||||
import { parseEnvironment } from '../utils/config';
|
||||
import { getTokenGuilds, getTokenUser } from '../utils/discord';
|
||||
import { getBindings } from '../utils/testHelpers';
|
||||
import { createSession } from './create';
|
||||
|
||||
const mockGetTokenGuilds = getTokenGuilds as jest.Mock;
|
||||
const mockGetTokenUser = getTokenUser as jest.Mock;
|
||||
|
||||
it('creates a session from tokens', async () => {
|
||||
const config = parseEnvironment(getBindings());
|
||||
|
||||
const tokens: AuthTokenResponse = {
|
||||
access_token: 'test-access-token',
|
||||
refresh_token: 'test-refresh-token',
|
||||
expires_in: 3600,
|
||||
scope: 'identify guilds',
|
||||
token_type: 'Bearer',
|
||||
};
|
||||
|
||||
mockGetTokenUser.mockReturnValueOnce({
|
||||
id: 'test-user-id',
|
||||
username: 'test-username',
|
||||
discriminator: 'test-discriminator',
|
||||
avatar: 'test-avatar',
|
||||
bot: false,
|
||||
});
|
||||
|
||||
mockGetTokenGuilds.mockReturnValueOnce([]);
|
||||
|
||||
const session = await createSession(config, tokens);
|
||||
|
||||
expect(session).toEqual({
|
||||
sessionID: expect.any(String),
|
||||
user: {
|
||||
id: 'test-user-id',
|
||||
discriminator: 'test-discriminator',
|
||||
avatar: 'test-avatar',
|
||||
bot: false,
|
||||
username: 'test-username',
|
||||
},
|
||||
guilds: [],
|
||||
tokens,
|
||||
});
|
||||
|
||||
expect(mockGetTokenUser).toBeCalledWith(tokens.access_token);
|
||||
expect(mockGetTokenGuilds).toBeCalledWith(tokens.access_token);
|
||||
|
||||
const savedSession = await config.kv.sessions.get(session?.sessionID || '');
|
||||
expect(savedSession).toEqual(session);
|
||||
});
|
31
packages/api/src/sessions/create.ts
Normal file
31
packages/api/src/sessions/create.ts
Normal file
|
@ -0,0 +1,31 @@
|
|||
import { Config } from '@roleypoly/api/src/utils/config';
|
||||
import { getTokenGuilds, getTokenUser } from '@roleypoly/api/src/utils/discord';
|
||||
import { getID } from '@roleypoly/api/src/utils/id';
|
||||
import { AuthTokenResponse, SessionData } from '@roleypoly/types';
|
||||
|
||||
export const createSession = async (
|
||||
config: Config,
|
||||
tokens: AuthTokenResponse
|
||||
): Promise<SessionData | null> => {
|
||||
const [user, guilds] = await Promise.all([
|
||||
getTokenUser(tokens.access_token),
|
||||
getTokenGuilds(tokens.access_token),
|
||||
]);
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sessionID = getID();
|
||||
|
||||
const session: SessionData = {
|
||||
sessionID,
|
||||
user,
|
||||
guilds,
|
||||
tokens,
|
||||
};
|
||||
|
||||
await config.kv.sessions.put(sessionID, session, config.retention.session);
|
||||
|
||||
return session;
|
||||
};
|
172
packages/api/src/sessions/middleware.spec.ts
Normal file
172
packages/api/src/sessions/middleware.spec.ts
Normal file
|
@ -0,0 +1,172 @@
|
|||
import { Router } from 'itty-router';
|
||||
import { Context } from '../utils/context';
|
||||
import { json } from '../utils/response';
|
||||
import { configContext, makeSession } from '../utils/testHelpers';
|
||||
import { requireSession, withAuthMode, withSession } from './middleware';
|
||||
|
||||
it('detects anonymous auth mode via middleware', async () => {
|
||||
const [, context] = configContext();
|
||||
const router = Router();
|
||||
const testFn = jest.fn();
|
||||
|
||||
router.all('*', withAuthMode).get('/', (request, context) => {
|
||||
expect(context.authMode.type).toBe('anonymous');
|
||||
testFn();
|
||||
return json({});
|
||||
});
|
||||
|
||||
await router.handle(new Request('http://test.local/'), context);
|
||||
|
||||
expect(testFn).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('detects bearer auth mode via middleware', async () => {
|
||||
const [, context] = configContext();
|
||||
const testFn = jest.fn();
|
||||
|
||||
const token = 'abc123';
|
||||
const router = Router();
|
||||
router.all('*', withAuthMode).get('/', (request, context) => {
|
||||
expect(context.authMode.type).toBe('bearer');
|
||||
expect(context.authMode.sessionId).toBe(token);
|
||||
testFn();
|
||||
return json({});
|
||||
});
|
||||
|
||||
await router.handle(
|
||||
new Request('http://test.local/', {
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
}),
|
||||
context
|
||||
);
|
||||
|
||||
expect(testFn).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('detects bot auth mode via middleware', async () => {
|
||||
const testFn = jest.fn();
|
||||
const [, context] = configContext();
|
||||
|
||||
const token = 'abc123';
|
||||
const router = Router();
|
||||
router.all('*', withAuthMode).get('/', (request, context) => {
|
||||
expect(context.authMode.type).toBe('bot');
|
||||
expect(context.authMode.identity).toBe(token);
|
||||
testFn();
|
||||
return json({});
|
||||
});
|
||||
|
||||
await router.handle(
|
||||
new Request('http://test.local/', {
|
||||
headers: {
|
||||
authorization: `Bot ${token}`,
|
||||
},
|
||||
}),
|
||||
context
|
||||
);
|
||||
|
||||
expect(testFn).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sets Context.session via withSession middleware', async () => {
|
||||
const testFn = jest.fn();
|
||||
const [config, context] = configContext();
|
||||
|
||||
const session = await makeSession(config);
|
||||
|
||||
const router = Router();
|
||||
router.all('*', withAuthMode, withSession).get('/', (request, context: Context) => {
|
||||
expect(context.session).toBeDefined();
|
||||
expect(context.session!.sessionID).toBe(session.sessionID);
|
||||
testFn();
|
||||
return json({});
|
||||
});
|
||||
|
||||
await router.handle(
|
||||
new Request('http://test.local/', {
|
||||
headers: {
|
||||
authorization: `Bearer ${session.sessionID}`,
|
||||
},
|
||||
}),
|
||||
context
|
||||
);
|
||||
expect(testFn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not set Context.session when session is invalid', async () => {
|
||||
const testFn = jest.fn();
|
||||
const [, context] = configContext();
|
||||
|
||||
const router = Router();
|
||||
router.all('*', withAuthMode, withSession).get('/', (request, context: Context) => {
|
||||
expect(context.session).not.toBeDefined();
|
||||
testFn();
|
||||
return json({});
|
||||
});
|
||||
|
||||
await router.handle(
|
||||
new Request('http://test.local/', {
|
||||
headers: {
|
||||
authorization: `Bearer abc123`,
|
||||
},
|
||||
}),
|
||||
context
|
||||
);
|
||||
|
||||
expect(testFn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('errors with 401 when requireSession is coupled with invalid session', async () => {
|
||||
const [, context] = configContext();
|
||||
const router = Router();
|
||||
|
||||
const testFn = jest.fn();
|
||||
router
|
||||
.all('*', withAuthMode, withSession, requireSession)
|
||||
.get('/', (request, context: Context) => {
|
||||
testFn();
|
||||
return json({});
|
||||
});
|
||||
|
||||
const response = await router.handle(
|
||||
new Request('http://test.local/', {
|
||||
headers: {
|
||||
authorization: `Bearer abc123`,
|
||||
},
|
||||
}),
|
||||
context
|
||||
);
|
||||
|
||||
expect(testFn).not.toHaveBeenCalled();
|
||||
expect(response.status).toBe(401);
|
||||
});
|
||||
|
||||
it('passes through when requireSession is coupled with a valid session', async () => {
|
||||
const [config, context] = configContext();
|
||||
|
||||
const session = await makeSession(config);
|
||||
const router = Router();
|
||||
|
||||
const testFn = jest.fn();
|
||||
router
|
||||
.all('*', withAuthMode, withSession, requireSession)
|
||||
.get('/', (request, context: Context) => {
|
||||
expect(context.session).toBeDefined();
|
||||
testFn();
|
||||
return json({});
|
||||
});
|
||||
|
||||
const response = await router.handle(
|
||||
new Request('http://test.local/', {
|
||||
headers: {
|
||||
authorization: `Bearer ${session.sessionID}`,
|
||||
},
|
||||
}),
|
||||
context
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(testFn).toHaveBeenCalled();
|
||||
});
|
67
packages/api/src/sessions/middleware.ts
Normal file
67
packages/api/src/sessions/middleware.ts
Normal file
|
@ -0,0 +1,67 @@
|
|||
import { Context, RoleypolyMiddleware } from '@roleypoly/api/src/utils/context';
|
||||
import { unauthorized } from '@roleypoly/api/src/utils/response';
|
||||
import { SessionData } from '@roleypoly/types';
|
||||
|
||||
export const withSession: RoleypolyMiddleware = async (
|
||||
request: Request,
|
||||
context: Context
|
||||
) => {
|
||||
if (context.authMode.type !== 'bearer') {
|
||||
return;
|
||||
}
|
||||
|
||||
const session = await context.config.kv.sessions.get<SessionData>(
|
||||
context.authMode.sessionId
|
||||
);
|
||||
if (!session) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.session = session;
|
||||
};
|
||||
|
||||
export const requireSession: RoleypolyMiddleware = (
|
||||
request: Request,
|
||||
context: Context
|
||||
) => {
|
||||
if (context.authMode.type !== 'bearer' || !context.session) {
|
||||
return unauthorized();
|
||||
}
|
||||
};
|
||||
|
||||
export const withAuthMode: RoleypolyMiddleware = (request: Request, context: Context) => {
|
||||
const auth = extractAuthentication(request);
|
||||
|
||||
if (auth.authType === 'Bearer') {
|
||||
context.authMode = {
|
||||
type: 'bearer',
|
||||
sessionId: auth.token,
|
||||
};
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (auth.authType === 'Bot') {
|
||||
context.authMode = {
|
||||
type: 'bot',
|
||||
identity: auth.token,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
context.authMode = {
|
||||
type: 'anonymous',
|
||||
};
|
||||
};
|
||||
|
||||
export const extractAuthentication = (
|
||||
request: Request
|
||||
): { authType: string; token: string } => {
|
||||
const authHeader = request.headers.get('authorization');
|
||||
if (!authHeader) {
|
||||
return { authType: 'None', token: '' };
|
||||
}
|
||||
|
||||
const [authType, token] = authHeader.split(' ');
|
||||
return { authType, token };
|
||||
};
|
25
packages/api/src/sessions/state.spec.ts
Normal file
25
packages/api/src/sessions/state.spec.ts
Normal file
|
@ -0,0 +1,25 @@
|
|||
import { parseEnvironment } from '../utils/config';
|
||||
import { getBindings } from '../utils/testHelpers';
|
||||
import { getStateSession, setupStateSession } from './state';
|
||||
|
||||
it('creates and fetches a state session', async () => {
|
||||
const config = parseEnvironment(getBindings());
|
||||
|
||||
const stateID = await setupStateSession(config, {
|
||||
test: 'test-data',
|
||||
});
|
||||
|
||||
const stateSession = await getStateSession(config, stateID);
|
||||
|
||||
expect(stateSession).toEqual({
|
||||
test: 'test-data',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns undefined when state is invalid', async () => {
|
||||
const config = parseEnvironment(getBindings());
|
||||
|
||||
const stateSession = await getStateSession(config, 'invalid-state-id');
|
||||
|
||||
expect(stateSession).toBeUndefined();
|
||||
});
|
19
packages/api/src/sessions/state.ts
Normal file
19
packages/api/src/sessions/state.ts
Normal file
|
@ -0,0 +1,19 @@
|
|||
import { Config } from '@roleypoly/api/src/utils/config';
|
||||
import { getID } from '@roleypoly/api/src/utils/id';
|
||||
|
||||
export const setupStateSession = async <T>(config: Config, data: T): Promise<string> => {
|
||||
const stateID = getID();
|
||||
|
||||
await config.kv.sessions.put(`state_${stateID}`, { data }, config.retention.session);
|
||||
|
||||
return stateID;
|
||||
};
|
||||
|
||||
export const getStateSession = async <T>(
|
||||
config: Config,
|
||||
stateID: string
|
||||
): Promise<T | undefined> => {
|
||||
const stateSession = await config.kv.sessions.get<{ data: T }>(`state_${stateID}`);
|
||||
|
||||
return stateSession?.data;
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue