Skip to content

Commit

Permalink
feat: config application (#183)
Browse files Browse the repository at this point in the history
* feat: config

* fix: using private env

* chore: use config type

* chore: remove unused env
  • Loading branch information
hywax authored Jun 26, 2024
1 parent b713aaf commit ca3d467
Show file tree
Hide file tree
Showing 13 changed files with 89 additions and 57 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"howler": "^2.2.4",
"jsonwebtoken": "^9.0.2",
"lucide-svelte": "^0.396.0",
"pixi.js": "^8.2.0"
"pixi.js": "^8.2.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@antfu/eslint-config": "^2.21.1",
Expand Down
6 changes: 3 additions & 3 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { type Handle, redirect } from '@sveltejs/kit'
import jwt from 'jsonwebtoken'
import { sequence } from '@sveltejs/kit/hooks'
import { env as privateEnv } from '$env/dynamic/private'
import { env as publicEnv } from '$env/dynamic/public'
import type { Profile } from '$lib/types'
import { type Locale, defaultLocale, supportedLocales } from '$lib/translations'
import { env as privateEnv } from '$env/dynamic/private'
import { config } from '$lib/config'

const handleJWT: Handle = ({ event, resolve }) => {
const cookieKey = publicEnv.PUBLIC_COOKIE_KEY ?? ''
const cookieKey = config.cookieKey
const jwtSecret = privateEnv.PRIVATE_JWT_SECRET_KEY

const token = event.cookies.get(cookieKey)
Expand Down
15 changes: 5 additions & 10 deletions src/lib/components/Footer.svelte
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
<script>
import {
DISCORD_SERVER_INVITE_URL,
DONATE_URL,
GITHUB_REPO_URL,
TWITCH_URL,
} from '$lib/config'
import { config } from '$lib/config'
</script>

<footer>
<ul>
<li>
<a href={GITHUB_REPO_URL} target='_blank'>Код на GitHub</a>
<a href={config.githubRepoUrl} target='_blank'>Код на GitHub</a>
</li>
<li>
<a href={DISCORD_SERVER_INVITE_URL} target='_blank'>Discord</a>
<a href={config.discordServerInviteUrl} target='_blank'>Discord</a>
</li>
<li>
<a href={TWITCH_URL} target='_blank'>Twitch</a>
<a href={config.twitch.url} target='_blank'>Twitch</a>
</li>
<li>
<a href={DONATE_URL} target='_blank'>Донат</a>
<a href={config.donateUrl} target='_blank'>Донат</a>
</li>
</ul>

Expand Down
6 changes: 3 additions & 3 deletions src/lib/components/Profile.svelte
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<script>
import { page } from '$app/stores'
import { env } from '$env/dynamic/public'
import twitchIcon from '$lib/assets/website/icons/twitch/112.png'
import { config } from '$lib/config'
const url = new URL('https://id.twitch.tv/oauth2/authorize')
url.searchParams.set('client_id', env.PUBLIC_TWITCH_CLIENT_ID ?? '')
url.searchParams.set('redirect_uri', env.PUBLIC_SIGNIN_REDIRECT_URL ?? '')
url.searchParams.set('client_id', config.twitch.clientId)
url.searchParams.set('redirect_uri', config.signInRedirectUrl)
url.searchParams.set('response_type', 'token')
url.searchParams.set('scope', 'chat:read channel:read:redemptions')
Expand Down
62 changes: 50 additions & 12 deletions src/lib/config.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,50 @@
export const DONATE_URL = 'https://www.donationalerts.com/r/hmbanan666'
export const DISCORD_SERVER_INVITE_URL = 'https://discord.gg/B6etUajrGZ'
export const TWITCH_URL = 'https://www.twitch.tv/hmbanan666'
export const GITHUB_REPO_URL = 'https://github.com/hmbanan666/chat-game'

export const TWITCH_CHANNEL_REWARDS = {
add150ViewerPointsId: 'd8237822-c943-434f-9d7e-87a9f549f4c4',
villainStealFuelId: 'd5956de4-54ff-49e4-afbe-ee4e62718eee',
addNewIdea: '289457e8-18c2-4b68-8564-fc61dd60b2a2',
}

export const ADMIN_PLAYER_ID = 'svhjz9p5467wne9ybasf1bwy'
import { z } from 'zod'
import { env as publicEnv } from '$env/dynamic/public'

/**
* Здесь объявляется схема конфигурации приложения.
* Содержит только публичные переменные окружения.
*
* Приватные переменные окружения хранятся в '$env/dynamic/private'
* По политике безопасности они не должны быть доступны на клиенте.
* И каждое использование приватной переменной окружения должно в ручном режиме.
*/

const allEnv = z.object({
PUBLIC_COOKIE_KEY: z.string().default(''),
PUBLIC_SIGNIN_REDIRECT_URL: z.string().default(''),
PUBLIC_WEBSOCKET_URL: z.string().default(''),
PUBLIC_DONATE_URL: z.string().default('https://www.donationalerts.com/r/hmbanan666'),
PUBLIC_GITHUB_REPO_URL: z.string().default('https://github.com/hmbanan666/chat-game'),
PUBLIC_DISCORD_SERVER_INVITE_URL: z.string().default('https://discord.gg/B6etUajrGZ'),
PUBLIC_GAME_ADMIN_PLAYER_ID: z.string().default('svhjz9p5467wne9ybasf1bwy'),
PUBLIC_TWITCH_CLIENT_ID: z.string().default(''),
PUBLIC_TWITCH_URL: z.string().default('https://www.twitch.tv/hmbanan666'),
PUBLIC_TWITCH_CHANNEL_REWARDS: z.string().default(JSON.stringify({
add150ViewerPointsId: 'd8237822-c943-434f-9d7e-87a9f549f4c4',
villainStealFuelId: 'd5956de4-54ff-49e4-afbe-ee4e62718eee',
addNewIdea: '289457e8-18c2-4b68-8564-fc61dd60b2a2',
})),
})

const ConfigSchema = allEnv.transform((value) => {
return {
cookieKey: value.PUBLIC_COOKIE_KEY,
signInRedirectUrl: value.PUBLIC_SIGNIN_REDIRECT_URL,
websocketUrl: value.PUBLIC_WEBSOCKET_URL,
donateUrl: value.PUBLIC_DONATE_URL,
githubRepoUrl: value.PUBLIC_GITHUB_REPO_URL,
discordServerInviteUrl: value.PUBLIC_DISCORD_SERVER_INVITE_URL,
game: {
adminPlayerId: value.PUBLIC_GAME_ADMIN_PLAYER_ID,
},
twitch: {
clientId: value.PUBLIC_TWITCH_CLIENT_ID,
url: value.PUBLIC_TWITCH_URL,
rewards: JSON.parse(value.PUBLIC_TWITCH_CHANNEL_REWARDS),
},
}
})

export type Config = z.infer<typeof ConfigSchema>
export const config: Config = ConfigSchema.parse(publicEnv)
19 changes: 7 additions & 12 deletions src/lib/game/services/action/actionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,7 @@ import type {
IGameActionResponse,
IGameSceneAction, ItemType,
} from '$lib/game/types'
import {
ADMIN_PLAYER_ID,
DISCORD_SERVER_INVITE_URL,
DONATE_URL,
GITHUB_REPO_URL,
} from '$lib/config'
import { config } from '$lib/config'
import type { GameAction } from '$lib/game/actions/interface'
import { TreeObject } from '$lib/game/objects/treeObject'
import { Route } from '$lib/game/services/route/route'
Expand Down Expand Up @@ -119,21 +114,21 @@ export class ActionService implements GameActionService {
}
if (action === 'START_CHANGING_SCENE') {
// Admin only
if (player.id !== ADMIN_PLAYER_ID) {
if (player.id !== config.game.adminPlayerId) {
return ANSWER.ERROR
}
return this.startChangingSceneAction(player, params)
}
if (action === 'START_GROUP_BUILD') {
// Admin only
if (player.id !== ADMIN_PLAYER_ID) {
if (player.id !== config.game.adminPlayerId) {
return ANSWER.ERROR
}
return this.startGroupBuildAction(player, params)
}
if (action === 'DISBAND_GROUP') {
// Admin only
if (player.id !== ADMIN_PLAYER_ID) {
if (player.id !== config.game.adminPlayerId) {
return ANSWER.ERROR
}
return this.disbandGroupAction()
Expand Down Expand Up @@ -512,7 +507,7 @@ export class ActionService implements GameActionService {

return {
ok: true,
message: `${player.name}, this is an interactive chat game that any viewer can participate in! Basic commands: !chop, !mine. The remaining commands appear in events (on the right of the screen). Join our community: ${DISCORD_SERVER_INVITE_URL}`,
message: `${player.name}, this is an interactive chat game that any viewer can participate in! Basic commands: !chop, !mine. The remaining commands appear in events (on the right of the screen). Join our community: ${config.discordServerInviteUrl}`,
}
}

Expand All @@ -523,7 +518,7 @@ export class ActionService implements GameActionService {

return {
ok: true,
message: `${player.name}, the game code is in the repository: ${GITHUB_REPO_URL}`,
message: `${player.name}, the game code is in the repository: ${config.githubRepoUrl}`,
}
}

Expand All @@ -533,7 +528,7 @@ export class ActionService implements GameActionService {
}
return {
ok: true,
message: `${player.name}, support the game: ${DONATE_URL}`,
message: `${player.name}, support the game: ${config.donateUrl}`,
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/lib/game/services/socket/webSocketService.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Game, WebSocketMessage } from '$lib/game/types'
import type { GameWebSocketService } from '$lib/game/services/socket/interface'
import { env } from '$env/dynamic/public'
import { browser } from '$app/environment'
import { config } from '$lib/config'

export class WebSocketService implements GameWebSocketService {
socket!: WebSocket
Expand Down Expand Up @@ -49,7 +49,7 @@ export class WebSocketService implements GameWebSocketService {
}

#init() {
this.socket = new WebSocket(env.PUBLIC_WEBSOCKET_URL ?? '', [this.game.id])
this.socket = new WebSocket(config.websocketUrl ?? '', [this.game.id])

this.#setMessagesPerSecondHandler()

Expand Down
4 changes: 2 additions & 2 deletions src/lib/server/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChatGameAPI } from '@hmbanan666/chat-game-api'
import { env } from '$env/dynamic/private'
import { env as privateEnv } from '$env/dynamic/private'

export const api = new ChatGameAPI(env.PRIVATE_WEBSITE_BEARER ?? '')
export const api = new ChatGameAPI(privateEnv.PRIVATE_WEBSITE_BEARER ?? '')
6 changes: 2 additions & 4 deletions src/routes/[lang]/(game)/play/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { env } from '$env/dynamic/public'
import { config } from '$lib/config'

export async function load({ cookies }) {
const cookieKey = env.PUBLIC_COOKIE_KEY ?? ''

return {
gameProfileJWT: cookies.get(cookieKey),
gameProfileJWT: cookies.get(config.cookieKey),
}
}
4 changes: 2 additions & 2 deletions src/routes/[lang]/(website)/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script lang='ts'>
import { onMount } from 'svelte'
import { TWITCH_URL } from '$lib/config'
import { config } from '$lib/config'
import { BaseGame } from '$lib/game/baseGame'
import { pluralizationRu } from '$lib/utils/locale'
Expand Down Expand Up @@ -75,7 +75,7 @@
перерыв, пока зрители развлекаются или...</p>
<p class='mt-2'>За все время
создано {profileCount} {profileDesc}. Присоединяйся <a
href={TWITCH_URL} target='_blank'
href={config.twitch.url} target='_blank'
class='twitch-link'>на активном
стриме</a>!</p>
</section>
Expand Down
4 changes: 2 additions & 2 deletions src/routes/auth/profile/+server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { error, json } from '@sveltejs/kit'
import type { RequestHandler } from './$types'
import { env } from '$env/dynamic/public'
import { config } from '$lib/config'

export const GET: RequestHandler = async ({ locals }) => {
if (!locals.profile) {
Expand All @@ -11,7 +11,7 @@ export const GET: RequestHandler = async ({ locals }) => {
}

export const DELETE: RequestHandler = async ({ cookies }) => {
const cookieKey = env.PUBLIC_COOKIE_KEY
const cookieKey = config.cookieKey
if (!cookieKey) {
error(500, 'Config problem')
}
Expand Down
8 changes: 4 additions & 4 deletions src/routes/auth/sign-in/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { StaticAuthProvider, getTokenInfo } from '@twurple/auth'
import jwt from 'jsonwebtoken'
import type { RequestHandler } from './$types'
import type { Profile } from '$lib/types'
import { env as publicEnv } from '$env/dynamic/public'
import { env as privateEnv } from '$env/dynamic/private'
import { api } from '$lib/server/api'
import { config } from '$lib/config'
import { env as privateEnv } from '$env/dynamic/private'

async function findOrCreateProfile({ twitchId, userName }: Pick<Profile, 'twitchId' | 'userName'>) {
const profile = await api.profile.getByTwitchId(twitchId)
Expand All @@ -27,7 +27,7 @@ async function findOrCreateProfile({ twitchId, userName }: Pick<Profile, 'twitch
}

async function prepareJwtToken(accessToken: string) {
const clientId = publicEnv.PUBLIC_TWITCH_CLIENT_ID
const { clientId } = config.twitch
if (!clientId) {
error(500, 'Config problem')
}
Expand Down Expand Up @@ -70,7 +70,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
error(400, 'Wrong data')
}

const cookieKey = publicEnv.PUBLIC_COOKIE_KEY
const cookieKey = config.cookieKey
if (!cookieKey) {
error(500, 'Config problem')
}
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5729,3 +5729,8 @@ zimmerframe@^1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/zimmerframe/-/zimmerframe-1.1.2.tgz#5b75f1fa83b07ae2a428d51e50f58e2ae6855e5e"
integrity sha512-rAbqEGa8ovJy4pyBxZM70hg4pE6gDgaQ0Sl9M3enG3I0d6H4XSAM3GeNGLKnsBpuijUow064sf7ww1nutC5/3w==

zod@^3.23.8:
version "3.23.8"
resolved "https://registry.yarnpkg.com/zod/-/zod-3.23.8.tgz#e37b957b5d52079769fb8097099b592f0ef4067d"
integrity sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==

0 comments on commit ca3d467

Please sign in to comment.