diff --git a/apps/api/package.json b/apps/api/package.json index 50024a1..71fc06d 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -11,16 +11,17 @@ }, "dependencies": { "@hono/node-server": "^1.19.9", - "@hono/zod-openapi": "^0.19.2", + "@hono/zod-openapi": "^1.2.2", "@repo/auth": "workspace:*", "@repo/db": "workspace:*", "@repo/env": "workspace:*", "dotenv": "^17.2.4", + "drizzle-orm": "^0.45.1", "hono": "^4.11.9", "hono-pino": "^0.8.0", "pino": "^9.6.0", "pino-pretty": "^13.0.0", - "zod": "^3.24.2" + "zod": "^4.3.6" }, "devDependencies": { "@repo/typescript-config": "workspace:*", diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 9bd30b2..55f095d 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -4,6 +4,7 @@ import { cors } from "hono/cors" import createApp from "@/lib/helpers/app/create-app" import configureOpenAPI from "@/lib/helpers/openapi/configure-openapi" import index from "@/routes/index.route" +import channelsRouter from "@/routes/v1/channels/index" import waitlistRouter from "@/routes/waitlist/index" const app = createApp() @@ -33,7 +34,7 @@ for (const route of internalRoutes) { } // Versioned public API routes -const v1Routes = [] as const +const v1Routes = [channelsRouter] as const for (const route of v1Routes) { app.route("/v1", route) } diff --git a/apps/api/src/lib/helpers/http/status-codes.ts b/apps/api/src/lib/helpers/http/status-codes.ts index e69de29..158e817 100644 --- a/apps/api/src/lib/helpers/http/status-codes.ts +++ b/apps/api/src/lib/helpers/http/status-codes.ts @@ -0,0 +1,356 @@ +// Generated file. Do not edit +// Codes retrieved on Thu, 03 Oct 2024 12:05:14 GMT from https://raw.githubusercontent.com/prettymuchbryce/http-status-codes/refs/heads/master/codes.json +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3 + * + * The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing. + */ +export const ACCEPTED = 202 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3 + * + * This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. + */ +export const BAD_GATEWAY = 502 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1 + * + * This response means that server could not understand the request due to invalid syntax. + */ +export const BAD_REQUEST = 400 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8 + * + * This response is sent when a request conflicts with the current state of the server. + */ +export const CONFLICT = 409 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1 + * + * This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished. + */ +export const CONTINUE = 100 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2 + * + * The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request. + */ +export const CREATED = 201 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14 + * + * This response code means the expectation indicated by the Expect request header field can't be met by the server. + */ +export const EXPECTATION_FAILED = 417 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5 + * + * The request failed due to failure of a previous request. + */ +export const FAILED_DEPENDENCY = 424 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3 + * + * The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server. + */ +export const FORBIDDEN = 403 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5 + * + * This error response is given when the server is acting as a gateway and cannot get a response in time. + */ +export const GATEWAY_TIMEOUT = 504 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9 + * + * This response would be sent when the requested content has been permenantly deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code. + */ +export const GONE = 410 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6 + * + * The HTTP version used in the request is not supported by the server. + */ +export const HTTP_VERSION_NOT_SUPPORTED = 505 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2 + * + * Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout. + */ +export const IM_A_TEAPOT = 418 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 + * + * The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. This condition is considered to be temporary. If the request which received this status code was the result of a user action, the request MUST NOT be repeated until it is requested by a separate user action. + */ +export const INSUFFICIENT_SPACE_ON_RESOURCE = 419 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 + * + * The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process. + */ +export const INSUFFICIENT_STORAGE = 507 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1 + * + * The server encountered an unexpected condition that prevented it from fulfilling the request. + */ +export const INTERNAL_SERVER_ERROR = 500 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10 + * + * The server rejected the request because the Content-Length header field is not defined and the server requires it. + */ +export const LENGTH_REQUIRED = 411 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4 + * + * The resource that is being accessed is locked. + */ +export const LOCKED = 423 +/** + * @deprecated + * Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt + * + * A deprecated response used by the Spring Framework when a method has failed. + */ +export const METHOD_FAILURE = 420 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5 + * + * The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code. + */ +export const METHOD_NOT_ALLOWED = 405 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2 + * + * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response. + */ +export const MOVED_PERMANENTLY = 301 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3 + * + * This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests. + */ +export const MOVED_TEMPORARILY = 302 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2 + * + * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate. + */ +export const MULTI_STATUS = 207 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1 + * + * The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses. + */ +export const MULTIPLE_CHOICES = 300 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6 + * + * The 511 status code indicates that the client needs to authenticate to gain network access. + */ +export const NETWORK_AUTHENTICATION_REQUIRED = 511 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5 + * + * There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones. + */ +export const NO_CONTENT = 204 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4 + * + * This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response. + */ +export const NON_AUTHORITATIVE_INFORMATION = 203 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6 + * + * This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent. + */ +export const NOT_ACCEPTABLE = 406 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4 + * + * The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web. + */ +export const NOT_FOUND = 404 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 + * + * The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD. + */ +export const NOT_IMPLEMENTED = 501 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1 + * + * This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response. + */ +export const NOT_MODIFIED = 304 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1 + * + * The request has succeeded. The meaning of a success varies depending on the HTTP method: + * GET: The resource has been fetched and is transmitted in the message body. + * HEAD: The entity headers are in the message body. + * POST: The resource describing the result of the action is transmitted in the message body. + * TRACE: The message body contains the request message as received by the server + */ +export const OK = 200 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1 + * + * This response code is used because of range header sent by the client to separate download into multiple streams. + */ +export const PARTIAL_CONTENT = 206 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2 + * + * This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently. + */ +export const PAYMENT_REQUIRED = 402 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3 + * + * This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. + */ +export const PERMANENT_REDIRECT = 308 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2 + * + * The client has indicated preconditions in its headers which the server does not meet. + */ +export const PRECONDITION_FAILED = 412 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3 + * + * The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict. + */ +export const PRECONDITION_REQUIRED = 428 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1 + * + * This code indicates that the server has received and is processing the request, but no response is available yet. + */ +export const PROCESSING = 102 +/** + * Official Documentation @ https://www.rfc-editor.org/rfc/rfc8297#page-3 + * + * This code indicates to the client that the server is likely to send a final response with the header fields included in the informational response. + */ +export const EARLY_HINTS = 103 +/** + * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.15 + * + * The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. + */ +export const UPGRADE_REQUIRED = 426 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2 + * + * This is similar to 401 but authentication is needed to be done by a proxy. + */ +export const PROXY_AUTHENTICATION_REQUIRED = 407 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5 + * + * The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields. + */ +export const REQUEST_HEADER_FIELDS_TOO_LARGE = 431 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7 + * + * This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message. + */ +export const REQUEST_TIMEOUT = 408 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11 + * + * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field. + */ +export const REQUEST_TOO_LONG = 413 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12 + * + * The URI requested by the client is longer than the server is willing to interpret. + */ +export const REQUEST_URI_TOO_LONG = 414 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4 + * + * The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data. + */ +export const REQUESTED_RANGE_NOT_SATISFIABLE = 416 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6 + * + * This response code is sent after accomplishing request to tell user agent reset document view which sent this request. + */ +export const RESET_CONTENT = 205 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4 + * + * Server sent this response to directing client to get requested resource to another URI with an GET request. + */ +export const SEE_OTHER = 303 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4 + * + * The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached. + */ +export const SERVICE_UNAVAILABLE = 503 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2 + * + * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too. + */ +export const SWITCHING_PROTOCOLS = 101 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7 + * + * Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. + */ +export const TEMPORARY_REDIRECT = 307 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4 + * + * The user has sent too many requests in a given amount of time ("rate limiting"). + */ +export const TOO_MANY_REQUESTS = 429 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1 + * + * Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. + */ +export const UNAUTHORIZED = 401 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7725 + * + * The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government. + */ +export const UNAVAILABLE_FOR_LEGAL_REASONS = 451 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3 + * + * The request was well-formed but was unable to be followed due to semantic errors. + */ +export const UNPROCESSABLE_ENTITY = 422 +/** + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13 + * + * The media format of the requested data is not supported by the server, so the server is rejecting the request. + */ +export const UNSUPPORTED_MEDIA_TYPE = 415 +/** + * @deprecated + * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6 + * + * Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy. + */ +export const USE_PROXY = 305 +/** + * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2 + * + * Defined in the specification of HTTP/2 to indicate that a server is not able to produce a response for the combination of scheme and authority that are included in the request URI. + */ +export const MISDIRECTED_REQUEST = 421 diff --git a/apps/api/src/lib/helpers/openapi/json-content.ts b/apps/api/src/lib/helpers/openapi/json-content.ts index 275f75b..00f5678 100644 --- a/apps/api/src/lib/helpers/openapi/json-content.ts +++ b/apps/api/src/lib/helpers/openapi/json-content.ts @@ -1,6 +1,6 @@ -import type { ZodSchema } from "zod" +import type { ZodType } from "zod" -const jsonContent = ({ +const jsonContent = ({ schema, description, }: { diff --git a/apps/api/src/lib/helpers/openapi/schemas.ts b/apps/api/src/lib/helpers/openapi/schemas.ts index c2a0844..4264b65 100644 --- a/apps/api/src/lib/helpers/openapi/schemas.ts +++ b/apps/api/src/lib/helpers/openapi/schemas.ts @@ -1,6 +1,32 @@ import { z } from "@hono/zod-openapi" import jsonContent from "./json-content" +const errorSchema = z.object({ + success: z.literal(false), + message: z.string(), +}) + +export const unauthorizedSchema = jsonContent({ + schema: errorSchema.openapi({ + example: { success: false, message: "Unauthorized" }, + }), + description: "Unauthorized", +}) + +export const forbiddenSchema = jsonContent({ + schema: errorSchema.openapi({ + example: { success: false, message: "Forbidden" }, + }), + description: "Forbidden", +}) + +export const notFoundSchema = jsonContent({ + schema: errorSchema.openapi({ + example: { success: false, message: "Not found" }, + }), + description: "Not found", +}) + export const internalServerErrorSchema = jsonContent({ schema: z .object({ diff --git a/apps/api/src/lib/types/app-types.ts b/apps/api/src/lib/types/app-types.ts index 3f96d86..b9326ef 100644 --- a/apps/api/src/lib/types/app-types.ts +++ b/apps/api/src/lib/types/app-types.ts @@ -1,10 +1,19 @@ import type { OpenAPIHono, RouteConfig, RouteHandler } from "@hono/zod-openapi" +import type { Session } from "@repo/auth" +import type { guild, guildMember } from "@repo/db/schema" import type { Schema } from "hono" import type { PinoLogger } from "hono-pino" +export type Guild = typeof guild.$inferSelect +export type GuildMember = typeof guildMember.$inferSelect + export interface AppBindings { Variables: { logger: PinoLogger + user: Session["user"] + session: Session["session"] + guild: Guild + member: GuildMember } } diff --git a/apps/api/src/middleware/auth.ts b/apps/api/src/middleware/auth.ts new file mode 100644 index 0000000..a6b1302 --- /dev/null +++ b/apps/api/src/middleware/auth.ts @@ -0,0 +1,77 @@ +import { auth } from "@repo/auth" +import { db } from "@repo/db" +import { guild, guildMember } from "@repo/db/schema" +import { and, eq } from "drizzle-orm" +import type { Context, Next } from "hono" +import * as HttpStatusCodes from "@/lib/helpers/http/status-codes" +import type { AppBindings } from "@/lib/types/app-types" + +/** + * Authenticates the request via better-auth session and resolves the + * user's active guild + membership. + * + * Sets in context: + * - user: The authenticated user + * - session: The session object + * - guild: The user's active guild + * - member: The user's membership in the active guild + */ +export const authMiddleware = async (c: Context, next: Next) => { + const session = await auth.api.getSession({ headers: c.req.raw.headers }) + + if (!session) { + return c.json( + { success: false, message: "Unauthorized" }, + HttpStatusCodes.UNAUTHORIZED + ) + } + + const activeGuildId = session.session.activeOrganizationId + + if (!activeGuildId) { + return c.json( + { success: false, message: "No active guild selected" }, + HttpStatusCodes.BAD_REQUEST + ) + } + + const memberRecord = await db + .select() + .from(guildMember) + .where( + and( + eq(guildMember.userId, session.user.id), + eq(guildMember.guildId, activeGuildId) + ) + ) + .limit(1) + .then((rows) => rows[0]) + + if (!memberRecord) { + return c.json( + { success: false, message: "You are not a member of this guild" }, + HttpStatusCodes.FORBIDDEN + ) + } + + const guildRecord = await db + .select() + .from(guild) + .where(eq(guild.id, activeGuildId)) + .limit(1) + .then((rows) => rows[0]) + + if (!guildRecord) { + return c.json( + { success: false, message: "Guild not found" }, + HttpStatusCodes.NOT_FOUND + ) + } + + c.set("user", session.user) + c.set("session", session.session) + c.set("guild", guildRecord) + c.set("member", memberRecord) + + await next() +} diff --git a/apps/api/src/routes/v1/channels/handlers.ts b/apps/api/src/routes/v1/channels/handlers.ts new file mode 100644 index 0000000..a3751aa --- /dev/null +++ b/apps/api/src/routes/v1/channels/handlers.ts @@ -0,0 +1,40 @@ +import { db } from "@repo/db" +import { channel } from "@repo/db/schema" +import { eq } from "drizzle-orm" +import * as HttpStatusCodes from "@/lib/helpers/http/status-codes" +import type { AppRouteHandler } from "@/lib/types/app-types" +import type { CreateChannelRoute, ListChannelsRoute } from "./routes" + +export const listChannels: AppRouteHandler = async (c) => { + const guild = c.var.guild + + const channels = await db + .select() + .from(channel) + .where(eq(channel.guildId, guild.id)) + + return c.json({ success: true, data: channels }, HttpStatusCodes.OK) +} + +export const createChannel: AppRouteHandler = async (c) => { + const guild = c.var.guild + const body = c.req.valid("json") + + const newChannel = await db + .insert(channel) + .values({ + ...body, + guildId: guild.id, + }) + .returning() + .then((rows) => rows[0]) + + if (!newChannel) { + return c.json( + { success: false, message: "Internal server error" }, + HttpStatusCodes.INTERNAL_SERVER_ERROR + ) + } + + return c.json({ success: true, data: newChannel }, HttpStatusCodes.CREATED) +} diff --git a/apps/api/src/routes/v1/channels/index.ts b/apps/api/src/routes/v1/channels/index.ts new file mode 100644 index 0000000..8b53988 --- /dev/null +++ b/apps/api/src/routes/v1/channels/index.ts @@ -0,0 +1,9 @@ +import { createRouter } from "@/lib/helpers/app/create-app" +import * as handlers from "./handlers" +import * as routes from "./routes" + +const channelsRouter = createRouter() + .openapi(routes.listChannels, handlers.listChannels) + .openapi(routes.createChannel, handlers.createChannel) + +export default channelsRouter diff --git a/apps/api/src/routes/v1/channels/routes.ts b/apps/api/src/routes/v1/channels/routes.ts new file mode 100644 index 0000000..dad0bec --- /dev/null +++ b/apps/api/src/routes/v1/channels/routes.ts @@ -0,0 +1,60 @@ +import { createRoute } from "@hono/zod-openapi" +import * as HttpStatusCodes from "@/lib/helpers/http/status-codes" +import jsonContent from "@/lib/helpers/openapi/json-content" +import { + forbiddenSchema, + internalServerErrorSchema, + unauthorizedSchema, +} from "@/lib/helpers/openapi/schemas" +import { authMiddleware } from "@/middleware/auth" +import { + createChannelRequestSchema, + createChannelResponseSchema, + listChannelsResponseSchema, +} from "./schema" + +export const listChannels = createRoute({ + path: "/channels", + method: "get", + summary: "List channels", + description: "Lists all channels in the user's active guild.", + tags: ["Channels"], + middleware: [authMiddleware] as const, + responses: { + [HttpStatusCodes.OK]: jsonContent({ + schema: listChannelsResponseSchema, + description: "List of channels", + }), + [HttpStatusCodes.UNAUTHORIZED]: unauthorizedSchema, + [HttpStatusCodes.FORBIDDEN]: forbiddenSchema, + [HttpStatusCodes.INTERNAL_SERVER_ERROR]: internalServerErrorSchema, + }, +}) + +export const createChannel = createRoute({ + path: "/channels", + method: "post", + summary: "Create a channel", + description: + "Creates a new channel in the user's active guild. Guild ID is derived from the session.", + tags: ["Channels"], + middleware: [authMiddleware] as const, + request: { + body: jsonContent({ + schema: createChannelRequestSchema, + description: "Channel details", + }), + }, + responses: { + [HttpStatusCodes.CREATED]: jsonContent({ + schema: createChannelResponseSchema, + description: "Channel created", + }), + [HttpStatusCodes.UNAUTHORIZED]: unauthorizedSchema, + [HttpStatusCodes.FORBIDDEN]: forbiddenSchema, + [HttpStatusCodes.INTERNAL_SERVER_ERROR]: internalServerErrorSchema, + }, +}) + +export type ListChannelsRoute = typeof listChannels +export type CreateChannelRoute = typeof createChannel diff --git a/apps/api/src/routes/v1/channels/schema.ts b/apps/api/src/routes/v1/channels/schema.ts new file mode 100644 index 0000000..c1def52 --- /dev/null +++ b/apps/api/src/routes/v1/channels/schema.ts @@ -0,0 +1,16 @@ +import { z } from "@hono/zod-openapi" +import { insertChannelSchema, selectChannelSchema } from "@repo/db/schema" + +export const channelResponseSchema = selectChannelSchema + +export const listChannelsResponseSchema = z.object({ + success: z.literal(true), + data: z.array(selectChannelSchema), +}) + +export const createChannelRequestSchema = insertChannelSchema + +export const createChannelResponseSchema = z.object({ + success: z.literal(true), + data: selectChannelSchema, +}) diff --git a/apps/web/src/components/sidebar/channel-list.tsx b/apps/web/src/components/sidebar/channel-list.tsx new file mode 100644 index 0000000..b81fe4c --- /dev/null +++ b/apps/web/src/components/sidebar/channel-list.tsx @@ -0,0 +1,88 @@ +import { cn } from "@repo/ui/lib/utils" +import { Hash, Volume2 } from "lucide-react" +import { UserAvatar } from "../user-avatar" + +// Hardcoded mock data — will be replaced with real data +const channels = [ + { name: "general", active: true, unread: false }, + { name: "introductions", active: false, unread: true }, + { name: "development", active: false, unread: false }, + { name: "design", active: false, unread: false }, + { name: "off-topic", active: false, unread: true }, +] + +const voiceChannels = [ + { name: "Lounge", usersIn: ["Sam Chen", "Jordan Blake"] }, + { name: "Dev Session", usersIn: [] as string[] }, +] + +export function ChannelList() { + return ( + + ) +} diff --git a/apps/web/src/components/sidebar/channel-panel.tsx b/apps/web/src/components/sidebar/channel-panel.tsx new file mode 100644 index 0000000..0facf00 --- /dev/null +++ b/apps/web/src/components/sidebar/channel-panel.tsx @@ -0,0 +1,18 @@ +import { ScrollArea } from "@repo/ui/components/scroll-area" +import { ChannelList } from "./channel-list" +import { GuildHeader } from "./guild-header" +import { SearchBar } from "./search-bar" +import { UserBar } from "./user-bar" + +export function ChannelPanel() { + return ( +
+ + + + + + +
+ ) +} diff --git a/apps/web/src/components/sidebar/guild-bar.tsx b/apps/web/src/components/sidebar/guild-bar.tsx new file mode 100644 index 0000000..1c8253b --- /dev/null +++ b/apps/web/src/components/sidebar/guild-bar.tsx @@ -0,0 +1,72 @@ +import { cn } from "@repo/ui/lib/utils" +import { MessageCircle, Plus } from "lucide-react" + +// Mock data — will be replaced with real data +const guilds = [ + { id: "1", name: "Townhall", active: true }, + { id: "2", name: "Design Team", active: false }, + { id: "3", name: "Open Source", active: false }, +] + +function GuildIcon({ name, active }: { name: string; active: boolean }) { + const initials = name + .split(" ") + .map((w) => w[0]) + .join("") + .slice(0, 2) + + return ( +
+ {/* Left pill indicator */} +
+ +
+ {initials} +
+
+ ) +} + +export function GuildBar() { + return ( +
+ {/* Home / DMs button */} +
+
+
+ +
+
+ + {/* Separator */} +
+ + {/* Guild icons */} + {guilds.map((guild) => ( + + ))} + + {/* Separator */} +
+ + {/* Add guild button */} +
+
+ +
+
+
+ ) +} diff --git a/apps/web/src/components/sidebar/guild-header.tsx b/apps/web/src/components/sidebar/guild-header.tsx new file mode 100644 index 0000000..d1ad74a --- /dev/null +++ b/apps/web/src/components/sidebar/guild-header.tsx @@ -0,0 +1,15 @@ +import { ChevronDown } from "lucide-react" + +export function GuildHeader() { + return ( + + ) +} diff --git a/apps/web/src/components/sidebar/search-bar.tsx b/apps/web/src/components/sidebar/search-bar.tsx new file mode 100644 index 0000000..348286c --- /dev/null +++ b/apps/web/src/components/sidebar/search-bar.tsx @@ -0,0 +1,12 @@ +import { Search } from "lucide-react" + +export function SearchBar() { + return ( +
+
+ + Search +
+
+ ) +} diff --git a/apps/web/src/components/sidebar/sidebar.tsx b/apps/web/src/components/sidebar/sidebar.tsx new file mode 100644 index 0000000..32cc162 --- /dev/null +++ b/apps/web/src/components/sidebar/sidebar.tsx @@ -0,0 +1,11 @@ +import { ChannelPanel } from "./channel-panel" +import { GuildBar } from "./guild-bar" + +export function Sidebar() { + return ( +
+ + +
+ ) +} diff --git a/apps/web/src/components/sidebar/user-bar.tsx b/apps/web/src/components/sidebar/user-bar.tsx new file mode 100644 index 0000000..c9b9c8b --- /dev/null +++ b/apps/web/src/components/sidebar/user-bar.tsx @@ -0,0 +1,35 @@ +import { authClient } from "@repo/auth/client" +import { Settings } from "lucide-react" +import { UserAvatar } from "../user-avatar" + +export function UserBar() { + const { data: session } = authClient.useSession() + + const name = session?.user.name ?? "User" + const username = session?.user.name ?? "user" + + return ( +
+
+
+ +
+
+
+
+ {username} +
+
+ Online +
+
+ +
+
+ ) +} diff --git a/apps/web/src/components/user-avatar.tsx b/apps/web/src/components/user-avatar.tsx new file mode 100644 index 0000000..bd3b8b6 --- /dev/null +++ b/apps/web/src/components/user-avatar.tsx @@ -0,0 +1,37 @@ +import { Avatar, AvatarFallback, AvatarImage } from "@repo/ui/components/avatar" +import { cn } from "@repo/ui/lib/utils" + +export function UserAvatar({ + src, + name, + size = "md", + className, +}: { + src?: string | null + name?: string | null + size?: "sm" | "md" + className?: string +}) { + const initials = name + ?.split(" ") + .map((n) => n[0]) + .join("") + .slice(0, 2) + .toUpperCase() + + return ( + + {src && } + + {initials ?? "?"} + + + ) +} diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 2d0b90d..11a3c95 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -13,9 +13,7 @@ export const Route = createRootRoute({ component: () => ( <> - - - + {/**/} ), }) diff --git a/apps/web/src/routes/_authenticated.tsx b/apps/web/src/routes/_authenticated.tsx index 4d076ba..8672a0f 100644 --- a/apps/web/src/routes/_authenticated.tsx +++ b/apps/web/src/routes/_authenticated.tsx @@ -1,6 +1,7 @@ import { authClient } from "@repo/auth/client" import { createFileRoute, Outlet, useNavigate } from "@tanstack/react-router" import { useEffect } from "react" +import { Sidebar } from "../components/sidebar/sidebar" export const Route = createFileRoute("/_authenticated")({ component: AuthenticatedLayout, @@ -28,5 +29,10 @@ function AuthenticatedLayout() { return null } - return + return ( +
+ + +
+ ) } diff --git a/apps/web/src/routes/_authenticated/index.tsx b/apps/web/src/routes/_authenticated/index.tsx index af70582..53bebbc 100644 --- a/apps/web/src/routes/_authenticated/index.tsx +++ b/apps/web/src/routes/_authenticated/index.tsx @@ -1,5 +1,3 @@ -import { authClient } from "@repo/auth/client" -import { Button } from "@repo/ui/components/button" import { createFileRoute } from "@tanstack/react-router" export const Route = createFileRoute("/_authenticated/")({ @@ -7,19 +5,11 @@ export const Route = createFileRoute("/_authenticated/")({ }) function Home() { - const { data: session } = authClient.useSession() - return ( -
-

Townhall

- {session && ( -

- Welcome, {session.user.name} -

- )} - +
+ + Select a channel to start chatting +
) } diff --git a/packages/db/package.json b/packages/db/package.json index 4d47f5a..ecdeed0 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -17,7 +17,9 @@ "dependencies": { "@repo/env": "workspace:*", "drizzle-orm": "^0.45.1", - "postgres": "^3.4.8" + "drizzle-zod": "^0.8.3", + "postgres": "^3.4.8", + "zod": "^4.3.6" }, "devDependencies": { "@repo/typescript-config": "workspace:*", diff --git a/packages/db/src/schemas/channels.ts b/packages/db/src/schemas/channels.ts index a32ae44..0b899ba 100644 --- a/packages/db/src/schemas/channels.ts +++ b/packages/db/src/schemas/channels.ts @@ -10,6 +10,11 @@ import { uniqueIndex, uuid, } from "drizzle-orm/pg-core" +import { + createInsertSchema, + createSelectSchema, + createUpdateSchema, +} from "drizzle-zod" import { guild } from "./guilds" import { message } from "./messages" import { user } from "./users" @@ -118,3 +123,30 @@ export const channelMemberRelations = relations(channelMember, ({ one }) => ({ references: [user.id], }), })) + +// Zod schemas +export const selectChannelSchema = createSelectSchema(channel) + +export const insertChannelSchema = createInsertSchema(channel, { + name: (s) => s.min(1).max(100), + topic: (s) => s.max(1024).optional(), +}).omit({ + id: true, + createdAt: true, + updatedAt: true, + guildId: true, + ownerId: true, + position: true, + rateLimitPerUser: true, +}) + +export const updateChannelSchema = createUpdateSchema(channel, { + name: (s) => s.min(1).max(100), + topic: (s) => s.max(1024), +}).omit({ + id: true, + createdAt: true, + updatedAt: true, + guildId: true, + ownerId: true, +}) diff --git a/packages/db/src/schemas/guilds.ts b/packages/db/src/schemas/guilds.ts index 8572ac8..3697ee7 100644 --- a/packages/db/src/schemas/guilds.ts +++ b/packages/db/src/schemas/guilds.ts @@ -6,6 +6,11 @@ import { uniqueIndex, uuid, } from "drizzle-orm/pg-core" +import { + createInsertSchema, + createSelectSchema, + createUpdateSchema, +} from "drizzle-zod" import { guildMember } from "./guild-members" import { guildRole } from "./guild-roles" import { invitation } from "./invitations" @@ -36,3 +41,14 @@ export const guildRelations = relations(guild, ({ one, many }) => ({ guildMembers: many(guildMember), invitations: many(invitation), })) + +// Zod schemas +export const selectGuildSchema = createSelectSchema(guild) + +export const insertGuildSchema = createInsertSchema(guild, { + name: (s) => s.min(1).max(100), +}) + +export const updateGuildSchema = createUpdateSchema(guild, { + name: (s) => s.min(1).max(100), +}) diff --git a/packages/db/src/schemas/index.ts b/packages/db/src/schemas/index.ts index eaf99bc..41100bc 100644 --- a/packages/db/src/schemas/index.ts +++ b/packages/db/src/schemas/index.ts @@ -1,8 +1,10 @@ export * from "./accounts" +export * from "./channels" export * from "./guild-members" export * from "./guild-roles" export * from "./guilds" export * from "./invitations" +export * from "./messages" export * from "./sessions" export * from "./two-factors" export * from "./users" diff --git a/packages/ui/src/components/avatar.tsx b/packages/ui/src/components/avatar.tsx new file mode 100644 index 0000000..6ae6604 --- /dev/null +++ b/packages/ui/src/components/avatar.tsx @@ -0,0 +1,108 @@ +"use client" + +import { cn } from "@repo/ui/lib/utils" +import { Avatar as AvatarPrimitive } from "radix-ui" +import type * as React from "react" + +function Avatar({ + className, + size = "default", + ...props +}: React.ComponentProps & { + size?: "default" | "sm" | "lg" +}) { + return ( + + ) +} + +function AvatarImage({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function AvatarFallback({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) { + return ( + svg]:hidden", + "group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2", + "group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2", + className + )} + {...props} + /> + ) +} + +function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function AvatarGroupCount({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3", + className + )} + {...props} + /> + ) +} + +export { + Avatar, + AvatarImage, + AvatarFallback, + AvatarBadge, + AvatarGroup, + AvatarGroupCount, +} diff --git a/packages/ui/src/components/scroll-area.tsx b/packages/ui/src/components/scroll-area.tsx new file mode 100644 index 0000000..15d4039 --- /dev/null +++ b/packages/ui/src/components/scroll-area.tsx @@ -0,0 +1,57 @@ +"use client" + +import { cn } from "@repo/ui/lib/utils" +import { ScrollArea as ScrollAreaPrimitive } from "radix-ui" +import type * as React from "react" + +function ScrollArea({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + {children} + + + + + ) +} + +function ScrollBar({ + className, + orientation = "vertical", + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +export { ScrollArea, ScrollBar } diff --git a/packages/ui/src/components/tooltip.tsx b/packages/ui/src/components/tooltip.tsx new file mode 100644 index 0000000..fc80495 --- /dev/null +++ b/packages/ui/src/components/tooltip.tsx @@ -0,0 +1,56 @@ +"use client" + +import { cn } from "@repo/ui/lib/utils" +import { Tooltip as TooltipPrimitive } from "radix-ui" +import type * as React from "react" + +function TooltipProvider({ + delayDuration = 0, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function Tooltip({ + ...props +}: React.ComponentProps) { + return +} + +function TooltipTrigger({ + ...props +}: React.ComponentProps) { + return +} + +function TooltipContent({ + className, + sideOffset = 0, + children, + ...props +}: React.ComponentProps) { + return ( + + + {children} + + + + ) +} + +export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 062f7e4..7058f67 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -30,8 +30,8 @@ importers: specifier: ^1.19.9 version: 1.19.9(hono@4.11.9) '@hono/zod-openapi': - specifier: ^0.19.2 - version: 0.19.10(hono@4.11.9)(zod@3.25.76) + specifier: ^1.2.2 + version: 1.2.2(hono@4.11.9)(zod@4.3.6) '@repo/auth': specifier: workspace:* version: link:../../packages/auth @@ -44,6 +44,9 @@ importers: dotenv: specifier: ^17.2.4 version: 17.2.4 + drizzle-orm: + specifier: ^0.45.1 + version: 0.45.1(kysely@0.28.11)(postgres@3.4.8) hono: specifier: ^4.11.9 version: 4.11.9 @@ -57,8 +60,8 @@ importers: specifier: ^13.0.0 version: 13.1.3 zod: - specifier: ^3.24.2 - version: 3.25.76 + specifier: ^4.3.6 + version: 4.3.6 devDependencies: '@repo/typescript-config': specifier: workspace:* @@ -268,9 +271,15 @@ importers: drizzle-orm: specifier: ^0.45.1 version: 0.45.1(kysely@0.28.11)(postgres@3.4.8) + drizzle-zod: + specifier: ^0.8.3 + version: 0.8.3(drizzle-orm@0.45.1(kysely@0.28.11)(postgres@3.4.8))(zod@4.3.6) postgres: specifier: ^3.4.8 version: 3.4.8 + zod: + specifier: ^4.3.6 + version: 4.3.6 devDependencies: '@repo/typescript-config': specifier: workspace:* @@ -347,10 +356,10 @@ packages: resolution: {integrity: sha512-9q/yCljni37pkMr4sPrI3G4jqdIk074+iukc5aFJl7kmDCCsiJrbZ6zKxnES1Gwg+i9RcDZwvktl23puGslmvA==} hasBin: true - '@asteasolutions/zod-to-openapi@7.3.4': - resolution: {integrity: sha512-/2rThQ5zPi9OzVwes6U7lK1+Yvug0iXu25olp7S0XsYmOqnyMfxH7gdSQjn/+DSOHRg7wnotwGJSyL+fBKdnEA==} + '@asteasolutions/zod-to-openapi@8.4.1': + resolution: {integrity: sha512-WmJUsFINbnWxGvHSd16aOjgKf+5GsfdxruO2YDLcgplsidakCauik1lhlk83YDH06265Yd1XtUyF24o09uygpw==} peerDependencies: - zod: ^3.20.2 + zod: ^4.0.0 '@babel/code-frame@7.29.0': resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==} @@ -1056,12 +1065,12 @@ packages: peerDependencies: hono: ^4 - '@hono/zod-openapi@0.19.10': - resolution: {integrity: sha512-dpoS6DenvoJyvxtQ7Kd633FRZ/Qf74+4+o9s+zZI8pEqnbjdF/DtxIib08WDpCaWabMEJOL5TXpMgNEZvb7hpA==} + '@hono/zod-openapi@1.2.2': + resolution: {integrity: sha512-va6vsL23wCJ1d0Vd+vGL1XOt+wPwItxirYafuhlW9iC2MstYr2FvsI7mctb45eBTjZfkqB/3LYDJEppPjOEiHw==} engines: {node: '>=16.0.0'} peerDependencies: hono: '>=4.3.6' - zod: '>=3.0.0' + zod: ^4.0.0 '@hono/zod-validator@0.7.6': resolution: {integrity: sha512-Io1B6d011Gj1KknV4rXYz4le5+5EubcWEU/speUjuw9XMMIaP3n78yXLhjd2A3PXaXaUwEAluOiAyLqhBEJgsw==} @@ -2909,6 +2918,12 @@ packages: sqlite3: optional: true + drizzle-zod@0.8.3: + resolution: {integrity: sha512-66yVOuvGhKJnTdiqj1/Xaaz9/qzOdRJADpDa68enqS6g3t0kpNkwNYjUuaeXgZfO/UWuIM9HIhSlJ6C5ZraMww==} + peerDependencies: + drizzle-orm: '>=0.36.0' + zod: ^3.25.0 || ^4.0.0 + dunder-proto@1.0.1: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} @@ -4441,10 +4456,10 @@ snapshots: package-manager-detector: 1.6.0 tinyexec: 1.0.2 - '@asteasolutions/zod-to-openapi@7.3.4(zod@3.25.76)': + '@asteasolutions/zod-to-openapi@8.4.1(zod@4.3.6)': dependencies: openapi3-ts: 4.5.0 - zod: 3.25.76 + zod: 4.3.6 '@babel/code-frame@7.29.0': dependencies: @@ -4974,18 +4989,18 @@ snapshots: dependencies: hono: 4.11.9 - '@hono/zod-openapi@0.19.10(hono@4.11.9)(zod@3.25.76)': + '@hono/zod-openapi@1.2.2(hono@4.11.9)(zod@4.3.6)': dependencies: - '@asteasolutions/zod-to-openapi': 7.3.4(zod@3.25.76) - '@hono/zod-validator': 0.7.6(hono@4.11.9)(zod@3.25.76) + '@asteasolutions/zod-to-openapi': 8.4.1(zod@4.3.6) + '@hono/zod-validator': 0.7.6(hono@4.11.9)(zod@4.3.6) hono: 4.11.9 openapi3-ts: 4.5.0 - zod: 3.25.76 + zod: 4.3.6 - '@hono/zod-validator@0.7.6(hono@4.11.9)(zod@3.25.76)': + '@hono/zod-validator@0.7.6(hono@4.11.9)(zod@4.3.6)': dependencies: hono: 4.11.9 - zod: 3.25.76 + zod: 4.3.6 '@hookform/resolvers@5.2.2(react-hook-form@7.71.1(react@19.2.4))': dependencies: @@ -6605,6 +6620,11 @@ snapshots: kysely: 0.28.11 postgres: 3.4.8 + drizzle-zod@0.8.3(drizzle-orm@0.45.1(kysely@0.28.11)(postgres@3.4.8))(zod@4.3.6): + dependencies: + drizzle-orm: 0.45.1(kysely@0.28.11)(postgres@3.4.8) + zod: 4.3.6 + dunder-proto@1.0.1: dependencies: call-bind-apply-helpers: 1.0.2