Skip to content

chore: refactor platform and use path aliases #465

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 21, 2024
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
15 changes: 8 additions & 7 deletions apps/platform/app.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Ctx } from './ctx';
import type { Ctx, TrpcContext } from './ctx';
import { env } from './env';
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
Expand Down Expand Up @@ -42,12 +42,13 @@ app.use(
'/trpc/*',
trpcServer({
router: trpcPlatformRouter,
createContext: (_, c) => ({
db,
account: c.get('account'),
org: null,
event: c
})
createContext: (_, c) =>
({
db,
account: c.get('account'),
org: null,
event: c
}) satisfies TrpcContext
})
);

Expand Down
14 changes: 10 additions & 4 deletions apps/platform/ctx.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import type { HttpBindings } from '@hono/node-server';
import type { DBType } from '@u22n/database';
import type { Context } from 'hono';
import type { DatabaseSession } from 'lucia';

export type Ctx = {
Bindings: HttpBindings;
Variables: {
account: {
id: number;
session: any;
} | null;
account: AccountContext;
};
};

Expand All @@ -29,3 +28,10 @@ export type AccountContext = {
id: number;
session: DatabaseSession;
} | null;

export type TrpcContext = {
db: DBType;
account: AccountContext;
org: OrgContext;
event: Context<Ctx>;
};
3 changes: 1 addition & 2 deletions apps/platform/middlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ export const authMiddleware = createMiddleware<Ctx>(async (c, next) => {
await next();
} else {
c.set('account', {
// @ts-expect-error, not typed properly yet
id: Number(sessionObject.attributes.account.id),
id: sessionObject.attributes.account.id,
session: sessionObject
});
await next();
Expand Down
6 changes: 6 additions & 0 deletions apps/platform/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,14 @@
"scripts": {
"dev": "tsx watch --clear-screen=false app.ts",
"start": "node --import=tsx app.ts",
"build": "echo 'No build step configured'",
"check": "tsc --noEmit"
},
"exports": {
"./trpc": {
"types": "./trpc/index.ts"
}
},
"dependencies": {
"@hono/node-server": "^1.11.1",
"@hono/trpc-server": "^0.3.1",
Expand Down
8 changes: 4 additions & 4 deletions apps/platform/routes/auth.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import { Hono } from 'hono';
import type { Ctx } from '../ctx';
import { lucia } from '../utils/auth';
import type { Ctx } from '~platform/ctx';
import { lucia } from '~platform/utils/auth';
import { setCookie } from 'hono/cookie';

export const authApi = new Hono<Ctx>();

authApi.get('/status', async (c) => {
const account = c.get('account');
if (!account || !account.id) {
if (!account) {
return c.json({ authStatus: 'unauthenticated' });
}
return c.json({ authStatus: 'authenticated' });
});

authApi.post('/logout', async (c) => {
const account = c.get('account');
if (!account || !account.id || !account.session || !account.session.id) {
if (!account) {
return c.json({ ok: true });
}
const sessionId = account.session.id;
Expand Down
6 changes: 3 additions & 3 deletions apps/platform/routes/realtime.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Hono } from 'hono';
import type { Ctx } from '../ctx';
import type { Ctx } from '~platform/ctx';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
import { validateOrgShortCode } from '../utils/orgShortCode';
import { validateOrgShortCode } from '~platform/utils/orgShortCode';
import { db } from '@u22n/database';
import { and, eq } from '@u22n/database/orm';
import { orgMembers } from '@u22n/database/schema';
import { realtime } from '../utils/realtime';
import { realtime } from '~platform/utils/realtime';

export const realtimeApi = new Hono<Ctx>();

Expand Down
15 changes: 10 additions & 5 deletions apps/platform/storage.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { env } from './env';
import { ms } from 'itty-time';
import redisDriver from 'unstorage/drivers/redis';
import { createStorage } from 'unstorage';
import { createStorage, type StorageValue } from 'unstorage';
import type { DatabaseSession } from 'lucia';
import type { OrgContext } from './ctx';

const createCachedStorage = (base: string, ttl: number) =>
createStorage({
const createCachedStorage = <T extends StorageValue = StorageValue>(
base: string,
ttl: number
) =>
createStorage<T>({
driver: redisDriver({
url: env.DB_REDIS_CONNECTION_STRING,
ttl,
Expand All @@ -14,8 +19,8 @@ const createCachedStorage = (base: string, ttl: number) =>

export const storage = {
auth: createCachedStorage('auth', ms('5 minutes')),
orgContext: createCachedStorage('org-context', ms('12 hours')),
session: createCachedStorage(
orgContext: createCachedStorage<OrgContext>('org-context', ms('12 hours')),
session: createCachedStorage<DatabaseSession>(
'sessions',
env.NODE_ENV === 'development' ? ms('12 hours') : ms('30 days')
)
Expand Down
61 changes: 24 additions & 37 deletions apps/platform/trpc/routers/authRouter/passkeyRouter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { z } from 'zod';
import { router, publicRateLimitedProcedure } from '../../trpc';
import { router, publicRateLimitedProcedure } from '~platform/trpc/trpc';
import { eq } from '@u22n/database/orm';
import { accounts } from '@u22n/database/schema';
import { TRPCError } from '@trpc/server';
Expand All @@ -13,13 +13,16 @@ import {
typeIdValidator,
zodSchemas
} from '@u22n/utils';
import { UAParser } from 'ua-parser-js';
import { usePasskeys } from '../../../utils/auth/passkeys';
import { usePasskeysDb } from '../../../utils/auth/passkeyDbAdaptor';
import { lucia } from '../../../utils/auth';
import {
verifyRegistrationResponse,
generateRegistrationOptions,
generateAuthenticationOptions,
verifyAuthenticationResponse
} from '~platform/utils/auth/passkeys';
import { createAuthenticator } from '~platform/utils/auth/passkeyUtils';
import { validateUsername } from './signupRouter';
import { createLuciaSessionCookie } from '../../../utils/session';
import { env } from '../../../env';
import { createLuciaSessionCookie } from '~platform/utils/session';
import { env } from '~platform/env';
import { ms } from 'itty-time';
import { getCookie, setCookie } from 'hono/cookie';

Expand All @@ -42,7 +45,7 @@ export const passkeyRouter = router({
}

const publicId = typeIdGenerator('account');
const passkeyOptions = await usePasskeys.generateRegistrationOptions({
const passkeyOptions = await generateRegistrationOptions({
userDisplayName: username,
username: username,
accountPublicId: publicId
Expand All @@ -63,7 +66,7 @@ export const passkeyRouter = router({
const registrationResponse =
input.registrationResponseRaw as RegistrationResponseJSON;

const passkeyVerification = await usePasskeys.verifyRegistrationResponse({
const passkeyVerification = await verifyRegistrationResponse({
registrationResponse: registrationResponse,
publicId: input.publicId
});
Expand Down Expand Up @@ -104,7 +107,7 @@ export const passkeyRouter = router({
});
}

const insertPasskey = await usePasskeysDb.createAuthenticator(
const insertPasskey = await createAuthenticator(
{
accountId: Number(newAccount.insertId),
credentialID: passkeyVerification.registrationInfo.credentialID,
Expand Down Expand Up @@ -137,12 +140,12 @@ export const passkeyRouter = router({
}
});

const cookie = await createLuciaSessionCookie(ctx.event, {
await createLuciaSessionCookie(ctx.event, {
accountId,
username: input.username,
publicId: input.publicId
});
setCookie(ctx.event, cookie.name, cookie.value, cookie.attributes);

return { success: true };
}),

Expand All @@ -160,7 +163,7 @@ export const passkeyRouter = router({
maxAge: ms('5 minutes'),
domain: env.PRIMARY_DOMAIN
});
const passkeyOptions = await usePasskeys.generateAuthenticationOptions({
const passkeyOptions = await generateAuthenticationOptions({
authChallengeId: authChallengeId
});

Expand All @@ -187,11 +190,10 @@ export const passkeyRouter = router({
});
}

const passkeyVerification =
await usePasskeys.verifyAuthenticationResponse({
authenticationResponse: verificationResponse,
authChallengeId: challengeCookie
});
const passkeyVerification = await verifyAuthenticationResponse({
authenticationResponse: verificationResponse,
authChallengeId: challengeCookie
});

if (
!passkeyVerification.result.verified ||
Expand Down Expand Up @@ -231,26 +233,11 @@ export const passkeyRouter = router({
});
}

const { device, os } = UAParser(event.req.header('User-Agent'));
const userDevice =
device.type === 'mobile' ? device.toString() : device.vendor;

const accountSession = await lucia.createSession(account.id, {
account: {
id: account.id,
username: account.username,
publicId: account.publicId
},
device: userDevice || 'Unknown',
os: os.name || 'Unknown'
await createLuciaSessionCookie(ctx.event, {
accountId: account.id,
username: account.username,
publicId: account.publicId
});
const cookie = lucia.createSessionCookie(accountSession.id);
setCookie(event, cookie.name, cookie.value, cookie.attributes);

await db
.update(accounts)
.set({ lastLoginAt: new Date() })
.where(eq(accounts.id, account.id));

const defaultOrg = account.orgMemberships.sort((a, b) => a.id - b.id)[0]
?.org.shortcode;
Expand Down
39 changes: 10 additions & 29 deletions apps/platform/trpc/routers/authRouter/passwordRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
router,
accountProcedure,
publicRateLimitedProcedure
} from '../../trpc';
} from '~platform/trpc/trpc';
import { eq } from '@u22n/database/orm';
import { accounts } from '@u22n/database/schema';
import {
Expand All @@ -14,14 +14,14 @@ import {
strongPasswordSchema
} from '@u22n/utils';
import { TRPCError } from '@trpc/server';
import { lucia } from '../../../utils/auth';
import { lucia } from '~platform/utils/auth';
import { validateUsername } from './signupRouter';
import { createLuciaSessionCookie } from '../../../utils/session';
import { createLuciaSessionCookie } from '~platform/utils/session';
import { decodeHex } from 'oslo/encoding';
import { TOTPController } from 'oslo/otp';
import { setCookie, getCookie, deleteCookie } from 'hono/cookie';
import { env } from '../../../env';
import { storage } from '../../../storage';
import { env } from '~platform/env';
import { storage } from '~platform/storage';

export const passwordRouter = router({
/**
Expand All @@ -36,7 +36,7 @@ export const passwordRouter = router({
)
.mutation(async ({ ctx, input }) => {
const { username, password } = input;
const { db, event } = ctx;
const { db } = ctx;

const { accountId, publicId } = await db.transaction(async (tx) => {
try {
Expand Down Expand Up @@ -66,18 +66,12 @@ export const passwordRouter = router({
}
});

const cookie = await createLuciaSessionCookie(ctx.event, {
await createLuciaSessionCookie(ctx.event, {
accountId,
username,
publicId
});

setCookie(event, cookie.name, cookie.value, cookie.attributes);
await db
.update(accounts)
.set({ lastLoginAt: new Date() })
.where(eq(accounts.id, accountId));

return { success: true };
}),

Expand Down Expand Up @@ -164,20 +158,14 @@ export const passwordRouter = router({
}
);

const cookie = await createLuciaSessionCookie(event, {
await createLuciaSessionCookie(event, {
accountId,
username,
publicId
});

setCookie(event, cookie.name, cookie.value, cookie.attributes);
deleteCookie(event, 'un-2fa-challenge');

await db
.update(accounts)
.set({ lastLoginAt: new Date() })
.where(eq(accounts.id, accountId));

return { success: true, error: null, recoveryCode };
}),

Expand Down Expand Up @@ -296,17 +284,11 @@ export const passwordRouter = router({
if (validPassword && otpValid) {
const { id: accountId, username, publicId } = userResponse;

const cookie = await createLuciaSessionCookie(event, {
await createLuciaSessionCookie(event, {
accountId,
username,
publicId
});
setCookie(event, cookie.name, cookie.value, cookie.attributes);

await db
.update(accounts)
.set({ lastLoginAt: new Date() })
.where(eq(accounts.id, userResponse.id));

const defaultOrg = userResponse.orgMemberships.sort(
(a, b) => a.id - b.id
Expand Down Expand Up @@ -400,13 +382,12 @@ export const passwordRouter = router({
await lucia.invalidateUserSessions(accountId);
}

const cookie = await createLuciaSessionCookie(event, {
await createLuciaSessionCookie(event, {
accountId,
username: accountData.username,
publicId: accountData.publicId
});

setCookie(event, cookie.name, cookie.value, cookie.attributes);
return { success: true };
})
});
Loading
Loading