Skip to content

Commit

Permalink
fix: using private env
Browse files Browse the repository at this point in the history
  • Loading branch information
hywax committed Jun 26, 2024
1 parent b4ef452 commit 49ea525
Show file tree
Hide file tree
Showing 11 changed files with 46 additions and 39 deletions.
7 changes: 4 additions & 3 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import jwt from 'jsonwebtoken'
import { sequence } from '@sveltejs/kit/hooks'
import type { Profile } from '$lib/types'
import { type Locale, defaultLocale, supportedLocales } from '$lib/translations'
import { serverConfig } from '$lib/config'
import { env as privateEnv } from '$env/dynamic/private'
import { config } from '$lib/config'

const handleJWT: Handle = ({ event, resolve }) => {
const cookieKey = serverConfig.cookieKey
const jwtSecret = serverConfig.jwtSecretKey
const cookieKey = config.cookieKey
const jwtSecret = privateEnv.PRIVATE_JWT_SECRET_KEY

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

<footer>
<ul>
<li>
<a href={serverConfig.githubRepoUrl} target='_blank'>Код на GitHub</a>
<a href={config.githubRepoUrl} target='_blank'>Код на GitHub</a>
</li>
<li>
<a href={serverConfig.discordServerInviteUrl} target='_blank'>Discord</a>
<a href={config.discordServerInviteUrl} target='_blank'>Discord</a>
</li>
<li>
<a href={serverConfig.twitch.url} target='_blank'>Twitch</a>
<a href={config.twitch.url} target='_blank'>Twitch</a>
</li>
<li>
<a href={serverConfig.donateUrl} 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 twitchIcon from '$lib/assets/website/icons/twitch/112.png'
import { serverConfig } from '$lib/config.js'
import { config } from '$lib/config'
const url = new URL('https://id.twitch.tv/oauth2/authorize')
url.searchParams.set('client_id', serverConfig.twitch.clientId)
url.searchParams.set('redirect_uri', serverConfig.signInRedirectUrl)
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
19 changes: 12 additions & 7 deletions src/lib/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { z } from 'zod'
import { env as publicEnv } from '$env/dynamic/public'
import { env as privateEnv } from '$env/dynamic/private'

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

const allEnv = z.object({
PRIVATE_JWT_SECRET_KEY: z.string().default(''),
Expand All @@ -21,7 +29,7 @@ const allEnv = z.object({
})),
})

const serverConfigSchema = allEnv.transform((value) => {
const ConfigSchema = allEnv.transform((value) => {
return {
jwtSecretKey: value.PRIVATE_JWT_SECRET_KEY,
websiteBearer: value.PRIVATE_WEBSITE_BEARER,
Expand All @@ -42,8 +50,5 @@ const serverConfigSchema = allEnv.transform((value) => {
}
})

export const serverConfig = serverConfigSchema.parse({ ...privateEnv, ...publicEnv })
export const clientConfig = {}

export type ServerConfig = z.infer<typeof serverConfigSchema>
export type ClientConfig = typeof clientConfig
export type Config = z.infer<typeof ConfigSchema>
export const config = ConfigSchema.parse(publicEnv)
14 changes: 7 additions & 7 deletions src/lib/game/services/action/actionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type {
IGameActionResponse,
IGameSceneAction, ItemType,
} from '$lib/game/types'
import { serverConfig } 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 @@ -114,21 +114,21 @@ export class ActionService implements GameActionService {
}
if (action === 'START_CHANGING_SCENE') {
// Admin only
if (player.id !== serverConfig.game.adminPlayerId) {
if (player.id !== config.game.adminPlayerId) {
return ANSWER.ERROR
}
return this.startChangingSceneAction(player, params)
}
if (action === 'START_GROUP_BUILD') {
// Admin only
if (player.id !== serverConfig.game.adminPlayerId) {
if (player.id !== config.game.adminPlayerId) {
return ANSWER.ERROR
}
return this.startGroupBuildAction(player, params)
}
if (action === 'DISBAND_GROUP') {
// Admin only
if (player.id !== serverConfig.game.adminPlayerId) {
if (player.id !== config.game.adminPlayerId) {
return ANSWER.ERROR
}
return this.disbandGroupAction()
Expand Down Expand Up @@ -507,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: ${serverConfig.discordServerInviteUrl}`,
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 @@ -518,7 +518,7 @@ export class ActionService implements GameActionService {

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

Expand All @@ -528,7 +528,7 @@ export class ActionService implements GameActionService {
}
return {
ok: true,
message: `${player.name}, support the game: ${serverConfig.donateUrl}`,
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 { browser } from '$app/environment'
import { serverConfig } from '$lib/config'
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(serverConfig.websocketUrl ?? '', [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 { serverConfig } from '$lib/config'
import { env as privateEnv } from '$env/dynamic/private'

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

export async function load({ cookies }) {
return {
gameProfileJWT: cookies.get(serverConfig.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 { serverConfig } 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={serverConfig.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 { serverConfig } from '$lib/config'
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 = serverConfig.cookieKey
const cookieKey = config.cookieKey
if (!cookieKey) {
error(500, 'Config problem')
}
Expand Down
9 changes: 5 additions & 4 deletions src/routes/auth/sign-in/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import jwt from 'jsonwebtoken'
import type { RequestHandler } from './$types'
import type { Profile } from '$lib/types'
import { api } from '$lib/server/api'
import { serverConfig } from '$lib/config'
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 @@ -26,12 +27,12 @@ async function findOrCreateProfile({ twitchId, userName }: Pick<Profile, 'twitch
}

async function prepareJwtToken(accessToken: string) {
const { clientId } = serverConfig.twitch
const { clientId } = config.twitch
if (!clientId) {
error(500, 'Config problem')
}

const jwtSecret = serverConfig.jwtSecretKey
const jwtSecret = privateEnv.PRIVATE_JWT_SECRET_KEY
if (!jwtSecret) {
error(500, 'Config problem')
}
Expand Down Expand Up @@ -69,7 +70,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
error(400, 'Wrong data')
}

const cookieKey = serverConfig.cookieKey
const cookieKey = config.cookieKey
if (!cookieKey) {
error(500, 'Config problem')
}
Expand Down

0 comments on commit 49ea525

Please sign in to comment.