From 5e52e096a287b3d431e6198757a3b5647eafb48d Mon Sep 17 00:00:00 2001 From: Carter Date: Wed, 22 Apr 2026 14:27:58 -0600 Subject: [PATCH 01/14] build for local server and deployment script --- deploy.sh | 11 +++++++++++ docker-compose.local.yml | 18 ++++++++++++++++++ package.json | 1 + 3 files changed, 30 insertions(+) create mode 100644 deploy.sh create mode 100644 docker-compose.local.yml diff --git a/deploy.sh b/deploy.sh new file mode 100644 index 0000000..cdcd400 --- /dev/null +++ b/deploy.sh @@ -0,0 +1,11 @@ +# 1. Build +docker build -t webui:local -f pond/Dockerfile . + +# 2. Transfer image +docker save webui:local | ssh -i ~/.ssh/id_ed25519 carter@172.16.1.20 docker load + +# 3. SCP compose file +scp -i ~/.ssh/id_ed25519 docker-compose.local.yml carter@172.16.1.20:~/ + +# 4. Deploy +ssh -i ~/.ssh/id_ed25519 carter@172.16.1.20 "docker stack deploy -c docker-compose.local.yml webui" \ No newline at end of file diff --git a/docker-compose.local.yml b/docker-compose.local.yml new file mode 100644 index 0000000..b8722cb --- /dev/null +++ b/docker-compose.local.yml @@ -0,0 +1,18 @@ +version: "3.6" + +services: + webui: + image: webui:local + ports: + - "8080:80" + stop_signal: SIGQUIT + deploy: + replicas: 1 + update_config: + order: start-first + healthcheck: + test: ["CMD", "curl", "-f", "localhost:80/health"] + interval: 1m + timeout: 10s + retries: 3 + start_period: 30s \ No newline at end of file diff --git a/package.json b/package.json index 90ac71b..31aea89 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "build:development": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_APP_API_URL=https://bxt-dev.api.adaptiveagriculture.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_DEVELOPMENT} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build", "build:production": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=5pUCkl2SfogkWmM244UDcLEUOp8EFdHd VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=api.brandxtech.ca VITE_APP_API_URL=https://api.brandxtech.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_PRODUCTION} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build", "build:streamline": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=HwUV0hHNdVvU96zuMBTAU8i7nFdwwgIX VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=streamline.api.adaptiveagriculture.ca VITE_APP_API_URL=https://streamline.api.adaptiveagriculture.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_PRODUCTION} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build", + "build:local": "VITE_AUTH0_CLIENT_ID=local VITE_AUTH0_AUDIENCE=local VITE_AUTH0_CLIENT_DOMAIN=local VITE_APP_API_URL=http://172.16.1.20:50052/v1 VITE_APP_WS_URL=ws://172.16.1.20:50052/v1/live NODE_OPTIONS=--max_old_space_size=4096 vite build", "build:offline": "npx env-cmd offline,whitelabel npm run build", "test": "vitest" }, From 23de0a3bca4e7e88411bdea303b6a1a52e88df49 Mon Sep 17 00:00:00 2001 From: Carter Date: Mon, 27 Apr 2026 14:09:50 -0600 Subject: [PATCH 02/14] created local deployment method that excludes crisp --- deploy.sh | 70 ++++++++++++++++++++++++++++++++++++----- indexLocal.html | 15 +++++++++ package.json | 4 +-- src/app/UserWrapper.tsx | 24 ++++++-------- src/chat/ChatDrawer.tsx | 20 ++++++------ src/chat/CrispChat.ts | 8 +++++ vite.config.ts | 57 ++++++++++++++++++++++++++++++--- 7 files changed, 160 insertions(+), 38 deletions(-) mode change 100644 => 100755 deploy.sh create mode 100644 indexLocal.html diff --git a/deploy.sh b/deploy.sh old mode 100644 new mode 100755 index cdcd400..1be7fa9 --- a/deploy.sh +++ b/deploy.sh @@ -1,11 +1,65 @@ -# 1. Build -docker build -t webui:local -f pond/Dockerfile . +#!/usr/bin/env bash +set -euo pipefail -# 2. Transfer image -docker save webui:local | ssh -i ~/.ssh/id_ed25519 carter@172.16.1.20 docker load +# Load .env.local if it exists +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ENV_FILE="$SCRIPT_DIR/.env.local" -# 3. SCP compose file -scp -i ~/.ssh/id_ed25519 docker-compose.local.yml carter@172.16.1.20:~/ +if [[ -f "$ENV_FILE" ]]; then + # Export only the vars we care about, ignoring comments and blank lines + set -o allexport + # shellcheck source=/dev/null + source <(grep -E '^(DEPLOY_USER|DEPLOY_HOST|DEPLOY_SSH_KEY)=' "$ENV_FILE") + set +o allexport +fi -# 4. Deploy -ssh -i ~/.ssh/id_ed25519 carter@172.16.1.20 "docker stack deploy -c docker-compose.local.yml webui" \ No newline at end of file +# Prompt for any missing values +if [[ -z "${DEPLOY_USER:-}" ]]; then + read -rp "SSH username: " DEPLOY_USER +fi + +if [[ -z "${DEPLOY_HOST:-}" ]]; then + read -rp "Server IP/hostname: " DEPLOY_HOST +fi + +if [[ -z "${DEPLOY_SSH_KEY:-}" ]]; then + read -rp "SSH key path [~/.ssh/id_ed25519]: " DEPLOY_SSH_KEY + DEPLOY_SSH_KEY="${DEPLOY_SSH_KEY:-~/.ssh/id_ed25519}" +fi + +SSH_OPTS="-i $DEPLOY_SSH_KEY" + +echo "→ Deploying to $DEPLOY_USER@$DEPLOY_HOST using key $DEPLOY_SSH_KEY" + +# 1. Build frontend (uses indexLocal.html — no Crisp; see vite --mode nocrisp) +( + cd "$SCRIPT_DIR" + npm run build:local +) + +# Fail if the bundle still embeds Crisp (wrong vite mode or stale build/) +INDEX_HTML="$SCRIPT_DIR/build/index.html" +if [[ ! -f "$INDEX_HTML" ]]; then + echo "error: missing $INDEX_HTML after build:local" >&2 + exit 1 +fi +if grep -qiE 'crisp\.chat|\$crisp|CRISP_WEBSITE_ID|CRISP_RUNTIME_CONFIG' "$INDEX_HTML"; then + echo "error: build/index.html still references Crisp; expected nocrisp build (indexLocal.html)" >&2 + exit 1 +fi + +# 2. Build container image +docker build -t webui:local -f Dockerfile . + +# 3. Transfer image +docker save webui:local | ssh $SSH_OPTS "$DEPLOY_USER@$DEPLOY_HOST" docker load + +# 4. SCP compose file +scp $SSH_OPTS docker-compose.local.yml "$DEPLOY_USER@$DEPLOY_HOST:~/" + +# 5. Deploy — then force service recreate. Swarm often keeps the old task when the tag stays +# webui:local after docker load, so without --force you still see the previous HTML/JS. +STACK_NAME="${LOCAL_DOCKER_STACK_NAME:-webui}" +SERVICE_NAME="${STACK_NAME}_webui" +ssh $SSH_OPTS "$DEPLOY_USER@$DEPLOY_HOST" \ + "docker stack deploy -c docker-compose.local.yml $STACK_NAME && docker service update --force $SERVICE_NAME" \ No newline at end of file diff --git a/indexLocal.html b/indexLocal.html new file mode 100644 index 0000000..d31ab53 --- /dev/null +++ b/indexLocal.html @@ -0,0 +1,15 @@ + + + + + + + + Adaptive Dashboard + + + +
+ + + diff --git a/package.json b/package.json index 31aea89..6dba33e 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "start": "VITE_AUTH0_CLIENT_ID=5pUCkl2SfogkWmM244UDcLEUOp8EFdHd VITE_AUTH0_AUDIENCE=api.brandxtech.ca VITE_APP_API_URL=https://api.brandxtech.ca/v1 VITE_APP_WS_URL=ws://api.brandxtech.ca/v1/live vite", - "start-local": "VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_APP_API_URL=http://localhost:50052/v1 VITE_APP_WS_URL=ws://localhost:50052/v1/live VITE_APP_BILLING_URL=http://localhost:50053/v1 VITE_APP_RECLUSE_URL=http://localhost:50054/v1 VITE_APP_GITLAB_URL=http://localhost:50055/v1 vite", + "start-local": "VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_APP_API_URL=http://localhost:50052/v1 VITE_APP_WS_URL=ws://localhost:50052/v1/live VITE_APP_BILLING_URL=http://localhost:50053/v1 VITE_APP_RECLUSE_URL=http://localhost:50054/v1 VITE_APP_GITLAB_URL=http://localhost:50055/v1 vite --mode nocrisp", "start-dev": "VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_APP_API_URL=https://bxt-dev.api.adaptiveagriculture.ca/v1 VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_AUTH0_DEV_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 vite", "start-streamline": "VITE_AUTH0_CLIENT_ID=HwUV0hHNdVvU96zuMBTAU8i7nFdwwgIX VITE_APP_API_URL=https://streamline.api.adaptiveagriculture.ca/v1 VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=streamline.api.adaptiveagriculture.ca vite", "start-staging": "VITE_LOCAL_STAGING=true VITE_AUTH0_CLIENT_ID=3ib460VvLwdeyse5iUSQfxkVdQaUmphP VITE_AUTH0_AUDIENCE=stagingapi.brandxtech.ca VITE_AUTH0_CLIENT_DOMAIN=adaptivestaging.us.auth0.com VITE_APP_API_URL=https://stagingapi.brandxtech.ca/v1 VITE_APP_WS_URL=ws://stagingapi.brandxtech.ca/v1/live VITE_APP_AUTH0_CLIENT_DOMAIN=adaptivestaging.us.auth0.com VITE_APP_AUTH0_AUDIENCE=stagingapi.brandxtech.ca vite", @@ -16,7 +16,7 @@ "build:development": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_APP_API_URL=https://bxt-dev.api.adaptiveagriculture.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_DEVELOPMENT} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build", "build:production": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=5pUCkl2SfogkWmM244UDcLEUOp8EFdHd VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=api.brandxtech.ca VITE_APP_API_URL=https://api.brandxtech.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_PRODUCTION} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build", "build:streamline": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=HwUV0hHNdVvU96zuMBTAU8i7nFdwwgIX VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=streamline.api.adaptiveagriculture.ca VITE_APP_API_URL=https://streamline.api.adaptiveagriculture.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_PRODUCTION} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build", - "build:local": "VITE_AUTH0_CLIENT_ID=local VITE_AUTH0_AUDIENCE=local VITE_AUTH0_CLIENT_DOMAIN=local VITE_APP_API_URL=http://172.16.1.20:50052/v1 VITE_APP_WS_URL=ws://172.16.1.20:50052/v1/live NODE_OPTIONS=--max_old_space_size=4096 vite build", + "build:local": "VITE_AUTH0_CLIENT_ID=local VITE_AUTH0_AUDIENCE=local VITE_AUTH0_CLIENT_DOMAIN=local VITE_APP_API_URL=http://172.16.1.20:50052/v1 VITE_APP_WS_URL=ws://172.16.1.20:50052/v1/live NODE_OPTIONS=--max_old_space_size=4096 vite build --mode nocrisp", "build:offline": "npx env-cmd offline,whitelabel npm run build", "test": "vitest" }, diff --git a/src/app/UserWrapper.tsx b/src/app/UserWrapper.tsx index fac8487..f837b70 100644 --- a/src/app/UserWrapper.tsx +++ b/src/app/UserWrapper.tsx @@ -12,9 +12,8 @@ import { makeStyles } from '@mui/styles' import { CssBaseline, Theme } from '@mui/material' import { AppThemeProvider } from 'theme/AppThemeProvider' import HTTPProvider from 'providers/http' -import { Crisp } from "crisp-sdk-web"; import { useMobile, useSnackbar } from 'hooks' -import { initCrisp } from '../chat/CrispChat' +import { initCrisp, isCrispEnabled } from '../chat/CrispChat' // import FirmwareLoader from './FirmwareLoader' const reducer = (state: GlobalState, action: GlobalStateAction): GlobalState => { @@ -72,9 +71,6 @@ export default function UserWrapper(props: Props) { const user_id = or(useAuth.user?.sub, "") - const crispInitialized = useRef(false); - Crisp.configure(import.meta.env.VITE_CRISP_WEBSITE_ID); - const loadUser = useCallback(() => { if (!userAPI.getUserWithTeam) return; if (hasFetched.current) return; @@ -114,15 +110,14 @@ export default function UserWrapper(props: Props) { }, [setGlobal]) useEffect(() => { - if (global?.user) { - initCrisp({ - websiteId: import.meta.env.VITE_CRISP_WEBSITE_ID, - email: global.user.settings.email, - nickname: global.user.settings.name || global.user.settings.email, - phone: global.user.settings.phoneNumber, - tokenId: global.user.id(), - }); - } + if (!global?.user || !isCrispEnabled()) return; + initCrisp({ + websiteId: import.meta.env.VITE_CRISP_WEBSITE_ID, + email: global.user.settings.email, + nickname: global.user.settings.name || global.user.settings.email, + phone: global.user.settings.phoneNumber, + tokenId: global.user.id(), + }); }, [global]); // useEffect(() => { @@ -150,6 +145,7 @@ export default function UserWrapper(props: Props) { // }, [isMobile]); useEffect(() => { + if (!isCrispEnabled()) return; let style = document.getElementById("crisp-offset-override"); if (!style) { style = document.createElement("style"); diff --git a/src/chat/ChatDrawer.tsx b/src/chat/ChatDrawer.tsx index fa4ae4e..01eebcd 100644 --- a/src/chat/ChatDrawer.tsx +++ b/src/chat/ChatDrawer.tsx @@ -7,7 +7,7 @@ import Chat from "./Chat"; import { pond } from "protobuf-ts/pond"; import { useEffect, useState } from "react"; import { useTeamAPI } from "providers"; -import { closeCrispChat, openCrispChat } from './CrispChat'; +import { closeCrispChat, isCrispEnabled, openCrispChat } from './CrispChat'; import RobotIcon from "products/CommonIcons/robotIcon"; const useStyles = makeStyles((theme: Theme) => ({ @@ -68,7 +68,7 @@ export function ChatDrawer(props: Props) { } useEffect(() => { - if (open) { + if (open && isCrispEnabled()) { closeCrispChat() } }, [open]) @@ -108,13 +108,15 @@ export function ChatDrawer(props: Props) { - - - - - + {isCrispEnabled() && ( + + + + + + )} {teams.map((t, i)=> { if (t.settings?.key === team.key()) return null; diff --git a/src/chat/CrispChat.ts b/src/chat/CrispChat.ts index a0220fb..fe9fc16 100644 --- a/src/chat/CrispChat.ts +++ b/src/chat/CrispChat.ts @@ -5,6 +5,11 @@ const ANIMATION_DURATION_MS = 300; let initialized = false; +export function isCrispEnabled(): boolean { + const id = import.meta.env.VITE_CRISP_WEBSITE_ID; + return typeof id === "string" && id.trim() !== ""; +} + /** * Initialize Crisp and immediately hide the default chat button. * Call this once on app load (e.g., in UserWrapper after user data is ready). @@ -17,6 +22,7 @@ export function initCrisp(opts: { tokenId?: string; }) { if (initialized) return; + if (!opts.websiteId?.trim()) return; Crisp.configure(opts.websiteId); Crisp.session.reset(); @@ -71,6 +77,7 @@ function injectCrispStyles() { * Safe to call from any onClick handler. */ export function openCrispChat() { + if (!initialized) return; const chatbox = document.getElementById("crisp-chatbox"); if (chatbox) { chatbox.classList.add("crisp-visible"); @@ -86,6 +93,7 @@ export function openCrispChat() { * Close the chat window and hide the widget. */ export function closeCrispChat() { + if (!initialized) return; Crisp.chat.close(); hideCrispChatButton(); } diff --git a/vite.config.ts b/vite.config.ts index f48db4a..bc0fc1b 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,12 +1,56 @@ -import { defineConfig } from 'vite' +import { defineConfig, type Plugin, type UserConfig } from 'vite' import react from '@vitejs/plugin-react' import tsconfigPaths from 'vite-tsconfig-paths' import { VitePWA } from 'vite-plugin-pwa'; import * as path from 'path' // ✅ Import path module +import { readFileSync, renameSync, existsSync, unlinkSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +const rootDir = path.dirname(fileURLToPath(import.meta.url)) + +const NO_CRISP_MODE = 'nocrisp' + +function useNoCrispIndexHtml (mode: string, command: string): Plugin { + if (mode !== NO_CRISP_MODE || command !== 'serve') { + return { name: 'use-local-index-html-noop' } + } + return { + name: 'use-local-index-html', + apply: 'serve', + transformIndexHtml: { + order: 'pre', + handler () { + return readFileSync(path.join(rootDir, 'indexLocal.html'), 'utf-8') + }, + }, + } +} + +function emitNoCrispIndexAsIndexHtml (mode: string): Plugin { + if (mode !== NO_CRISP_MODE) { + return { name: 'emit-nocrisp-index-as-index-noop' } + } + return { + name: 'emit-nocrisp-index-as-index-html', + closeBundle () { + const outDir = path.join(rootDir, 'build') + const from = path.join(outDir, 'indexLocal.html') + const to = path.join(outDir, 'index.html') + if (existsSync(from)) { + if (existsSync(to)) unlinkSync(to) + renameSync(from, to) + } + }, + } +} // https://vitejs.dev/config/ -export default defineConfig({ +export default defineConfig(({ command, mode }): UserConfig => { + const useNoCrispIndex = mode === NO_CRISP_MODE + return { plugins: [ + useNoCrispIndexHtml(mode, command), + emitNoCrispIndexAsIndexHtml(mode), react(), tsconfigPaths(), VitePWA({ @@ -53,12 +97,15 @@ export default defineConfig({ target: 'esnext', rollupOptions: { input: { - main: path.resolve(__dirname, 'index.html') - } + main: path.join( + rootDir, + useNoCrispIndex ? 'indexLocal.html' : 'index.html' + ), + }, } }, esbuild: { keepNames: true, // Prevent function name mangling }, - + } }) From 8169e280ec75be87aa8c67b988e1d4128aec1712 Mon Sep 17 00:00:00 2001 From: Carter Date: Mon, 27 Apr 2026 14:42:56 -0600 Subject: [PATCH 03/14] front end flow for bypassing auth0 on local buils --- deploy.sh | 4 ---- src/app/App.tsx | 12 ++++++++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/deploy.sh b/deploy.sh index 1be7fa9..daa6b63 100755 --- a/deploy.sh +++ b/deploy.sh @@ -43,10 +43,6 @@ if [[ ! -f "$INDEX_HTML" ]]; then echo "error: missing $INDEX_HTML after build:local" >&2 exit 1 fi -if grep -qiE 'crisp\.chat|\$crisp|CRISP_WEBSITE_ID|CRISP_RUNTIME_CONFIG' "$INDEX_HTML"; then - echo "error: build/index.html still references Crisp; expected nocrisp build (indexLocal.html)" >&2 - exit 1 -fi # 2. Build container image docker build -t webui:local -f Dockerfile . diff --git a/src/app/App.tsx b/src/app/App.tsx index 2c6b94b..09956c2 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -1,9 +1,11 @@ import { Auth0Provider } from '@auth0/auth0-react' import { or } from '../utils/types' +import { isAuth0Configured, isAuth0SpaOriginAllowed, shouldMountAuth0Provider } from '../utils/auth0Config' import AuthWrapper from '../providers/auth' import HTTPProvider from 'providers/http' import { useState } from 'react' import LoadingScreen from './LoadingScreen' +import LocalAuthPlaceholder from './LocalAuthPlaceholder' import UserWrapper from './UserWrapper' import { getWhitelabel } from 'services/whiteLabel' import { AppThemeProvider } from 'theme/AppThemeProvider' @@ -54,6 +56,16 @@ function App() { "/libracart" ] + if (!shouldMountAuth0Provider()) { + const placeholderReason = + isAuth0Configured() && !isAuth0SpaOriginAllowed() ? 'insecure_origin' : 'unconfigured' + return ( + + + + ) + } + return ( Date: Wed, 29 Apr 2026 10:20:44 -0600 Subject: [PATCH 04/14] local authentication placeholder --- deploy.sh | 2 +- indexLocal.html | 3 +- package.json | 4 +-- src/app/LocalAuthPlaceholder.tsx | 61 ++++++++++++++++++++++++++++++++ src/utils/auth0Config.ts | 24 +++++++++++++ vite.config.ts | 28 ++++++++------- 6 files changed, 105 insertions(+), 17 deletions(-) create mode 100644 src/app/LocalAuthPlaceholder.tsx create mode 100644 src/utils/auth0Config.ts diff --git a/deploy.sh b/deploy.sh index daa6b63..e03b995 100755 --- a/deploy.sh +++ b/deploy.sh @@ -31,7 +31,7 @@ SSH_OPTS="-i $DEPLOY_SSH_KEY" echo "→ Deploying to $DEPLOY_USER@$DEPLOY_HOST using key $DEPLOY_SSH_KEY" -# 1. Build frontend (uses indexLocal.html — no Crisp; see vite --mode nocrisp) +# 1. Build frontend for LAN / self-contained hosts (indexLocal.html via vite --mode localnet) ( cd "$SCRIPT_DIR" npm run build:local diff --git a/indexLocal.html b/indexLocal.html index d31ab53..af3867c 100644 --- a/indexLocal.html +++ b/indexLocal.html @@ -1,4 +1,5 @@ - + diff --git a/package.json b/package.json index 6dba33e..8531516 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "start": "VITE_AUTH0_CLIENT_ID=5pUCkl2SfogkWmM244UDcLEUOp8EFdHd VITE_AUTH0_AUDIENCE=api.brandxtech.ca VITE_APP_API_URL=https://api.brandxtech.ca/v1 VITE_APP_WS_URL=ws://api.brandxtech.ca/v1/live vite", - "start-local": "VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_APP_API_URL=http://localhost:50052/v1 VITE_APP_WS_URL=ws://localhost:50052/v1/live VITE_APP_BILLING_URL=http://localhost:50053/v1 VITE_APP_RECLUSE_URL=http://localhost:50054/v1 VITE_APP_GITLAB_URL=http://localhost:50055/v1 vite --mode nocrisp", + "start-local": "VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_APP_API_URL=http://localhost:50052/v1 VITE_APP_WS_URL=ws://localhost:50052/v1/live VITE_APP_BILLING_URL=http://localhost:50053/v1 VITE_APP_RECLUSE_URL=http://localhost:50054/v1 VITE_APP_GITLAB_URL=http://localhost:50055/v1 vite --mode localnet", "start-dev": "VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_APP_API_URL=https://bxt-dev.api.adaptiveagriculture.ca/v1 VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_AUTH0_DEV_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 vite", "start-streamline": "VITE_AUTH0_CLIENT_ID=HwUV0hHNdVvU96zuMBTAU8i7nFdwwgIX VITE_APP_API_URL=https://streamline.api.adaptiveagriculture.ca/v1 VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=streamline.api.adaptiveagriculture.ca vite", "start-staging": "VITE_LOCAL_STAGING=true VITE_AUTH0_CLIENT_ID=3ib460VvLwdeyse5iUSQfxkVdQaUmphP VITE_AUTH0_AUDIENCE=stagingapi.brandxtech.ca VITE_AUTH0_CLIENT_DOMAIN=adaptivestaging.us.auth0.com VITE_APP_API_URL=https://stagingapi.brandxtech.ca/v1 VITE_APP_WS_URL=ws://stagingapi.brandxtech.ca/v1/live VITE_APP_AUTH0_CLIENT_DOMAIN=adaptivestaging.us.auth0.com VITE_APP_AUTH0_AUDIENCE=stagingapi.brandxtech.ca vite", @@ -16,7 +16,7 @@ "build:development": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=dzJTpqIeMA4Rwk4xujtwPbAO3TY32bM1 VITE_AUTH0_AUDIENCE=bxt-dev.api.adaptiveagriculture.ca VITE_APP_API_URL=https://bxt-dev.api.adaptiveagriculture.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_DEVELOPMENT} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build", "build:production": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=5pUCkl2SfogkWmM244UDcLEUOp8EFdHd VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=api.brandxtech.ca VITE_APP_API_URL=https://api.brandxtech.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_PRODUCTION} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build", "build:streamline": "VITE_CRISP_WEBSITE_ID={CRISP_WEBSITE_ID} VITE_AUTH0_CLIENT_ID=HwUV0hHNdVvU96zuMBTAU8i7nFdwwgIX VITE_AUTH0_CLIENT_DOMAIN=brandxtech.auth0.com VITE_AUTH0_AUDIENCE=streamline.api.adaptiveagriculture.ca VITE_APP_API_URL=https://streamline.api.adaptiveagriculture.ca/v1 NODE_OPTIONS=--max_old_space_size=4096 VITE_APP_GOOGLE_API_KEY=${GOOGLE_API_KEY} VITE_APP_STRIPE_PUBLIC_KEY=${STRIPE_PUBLIC_KEY_PRODUCTION} VITE_MAPBOX_ACCESS_TOKEN=${MAPBOX_ACCESS_TOKEN} VITE_CNHI_CLIENT_ID=${CNHI_CLIENT_ID} VITE_CNHI_AUTHORIZE_URL=${CNHI_AUTHORIZE_URL} VITE_CNHI_REDIRECT_URI=${CNHI_REDIRECT_URI} VITE_CNHI_SCOPES=${CNHI_SCOPES} VITE_CNHI_CONNECTION=${CNHI_CONNECTION} VITE_CNHI_AUDIENCE=${CNHI_AUDIENCE} VITE_APP_IMAGE4IO_USERNAME=${IMAGE4IO_USERNAME} VITE_APP_IMAGE4IO_PASSWORD=${IMAGE4IO_PASSWORD} VITE_JD_CLIENT_ID=${JD_CLIENT_ID} VITE_JD_AUTHORIZE_URL=${JD_AUTHORIZE_URL} VITE_JD_REDIRECT_URI=${JD_REDIRECT_URI} VITE_JD_SCOPES=${JD_SCOPES} VITE_JD_STATE=${JD_STATE} VITE_OPEN_WEATHERMAP=${OPEN_WEATHERMAP} vite build", - "build:local": "VITE_AUTH0_CLIENT_ID=local VITE_AUTH0_AUDIENCE=local VITE_AUTH0_CLIENT_DOMAIN=local VITE_APP_API_URL=http://172.16.1.20:50052/v1 VITE_APP_WS_URL=ws://172.16.1.20:50052/v1/live NODE_OPTIONS=--max_old_space_size=4096 vite build --mode nocrisp", + "build:local": "VITE_AUTH0_CLIENT_ID=local VITE_AUTH0_AUDIENCE=local VITE_AUTH0_CLIENT_DOMAIN=local VITE_APP_API_URL=http://172.16.1.20:50052/v1 VITE_APP_WS_URL=ws://172.16.1.20:50052/v1/live NODE_OPTIONS=--max_old_space_size=4096 vite build --mode localnet", "build:offline": "npx env-cmd offline,whitelabel npm run build", "test": "vitest" }, diff --git a/src/app/LocalAuthPlaceholder.tsx b/src/app/LocalAuthPlaceholder.tsx new file mode 100644 index 0000000..cc05526 --- /dev/null +++ b/src/app/LocalAuthPlaceholder.tsx @@ -0,0 +1,61 @@ +import { Box, Button, CssBaseline, Paper, Stack, Typography } from '@mui/material' +import { getName } from 'services/whiteLabel' + +export type LocalAuthPlaceholderReason = 'unconfigured' | 'insecure_origin' + +interface Props { + /** Why cloud Auth0 was skipped — copy differs when env is set but the page is not a secure context (e.g. http://LAN IP). */ + reason?: LocalAuthPlaceholderReason +} + +/** + * Shown when Auth0 is not used (missing config and/or non–secure context). + * Replace with backend-driven login once local auth is implemented. + */ +export default function LocalAuthPlaceholder(props: Props) { + const { reason = 'unconfigured' } = props + const productName = getName() + + const explanation = + reason === 'insecure_origin' + ? 'This URL is not a secure context for cloud sign-in (Auth0 requires HTTPS, localhost, or 127.0.0.1). Use local account sign-in here instead once it is connected.' + : 'Cloud sign-in (Auth0) is not configured for this deployment. Local account sign-in will be available here.' + + return ( + <> + + + + + + {productName} + + + {explanation} + + + + + + + Buttons are placeholders until the backend login flow is wired up. + + + + + + ) +} diff --git a/src/utils/auth0Config.ts b/src/utils/auth0Config.ts new file mode 100644 index 0000000..1c5e568 --- /dev/null +++ b/src/utils/auth0Config.ts @@ -0,0 +1,24 @@ +import { getWhitelabel } from 'services/whiteLabel' + +/** True when Auth0 env + whitelabel client ID are present; avoids mounting Auth0Provider on offline / local LAN builds. */ +export function isAuth0Configured(): boolean { + const wl = getWhitelabel() + const domain = String(import.meta.env.VITE_AUTH0_CLIENT_DOMAIN ?? '').trim() + const clientRaw = wl.auth0ClientId ?? import.meta.env.VITE_AUTH0_CLIENT_ID + const clientId = String(clientRaw ?? '').trim() + return domain.length > 0 && clientId.length > 0 +} + +/** + * auth0-spa-js only runs in a "secure context" (HTTPS, http://localhost, http://127.0.0.1, etc.). + * Plain http://192.168.x.x fails — same check as `window.isSecureContext`. + */ +export function isAuth0SpaOriginAllowed(): boolean { + if (typeof window === 'undefined') return true + return window.isSecureContext +} + +/** Mount Auth0 only when credentials exist and the browser will let the SDK run. */ +export function shouldMountAuth0Provider(): boolean { + return isAuth0Configured() && isAuth0SpaOriginAllowed() +} diff --git a/vite.config.ts b/vite.config.ts index bc0fc1b..ed1b6f1 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -8,14 +8,15 @@ import { fileURLToPath } from 'node:url' const rootDir = path.dirname(fileURLToPath(import.meta.url)) -const NO_CRISP_MODE = 'nocrisp' +const LOCALNET_MODE = 'localnet' -function useNoCrispIndexHtml (mode: string, command: string): Plugin { - if (mode !== NO_CRISP_MODE || command !== 'serve') { - return { name: 'use-local-index-html-noop' } +/** Dev server: serve the minimal LAN shell (indexLocal.html) instead of the full index with third-party bootstraps. */ +function useLocalnetShellHtml (mode: string, command: string): Plugin { + if (mode !== LOCALNET_MODE || command !== 'serve') { + return { name: 'localnet-shell-html-noop' } } return { - name: 'use-local-index-html', + name: 'localnet-shell-html', apply: 'serve', transformIndexHtml: { order: 'pre', @@ -26,12 +27,13 @@ function useNoCrispIndexHtml (mode: string, command: string): Plugin { } } -function emitNoCrispIndexAsIndexHtml (mode: string): Plugin { - if (mode !== NO_CRISP_MODE) { - return { name: 'emit-nocrisp-index-as-index-noop' } +/** After build, LAN shell is emitted as indexLocal.html; rename to index.html so nginx and PWA still use /. */ +function emitLocalnetShellAsIndexHtml (mode: string): Plugin { + if (mode !== LOCALNET_MODE) { + return { name: 'emit-localnet-shell-as-index-noop' } } return { - name: 'emit-nocrisp-index-as-index-html', + name: 'emit-localnet-shell-as-index-html', closeBundle () { const outDir = path.join(rootDir, 'build') const from = path.join(outDir, 'indexLocal.html') @@ -46,11 +48,11 @@ function emitNoCrispIndexAsIndexHtml (mode: string): Plugin { // https://vitejs.dev/config/ export default defineConfig(({ command, mode }): UserConfig => { - const useNoCrispIndex = mode === NO_CRISP_MODE + const useLocalnetShell = mode === LOCALNET_MODE return { plugins: [ - useNoCrispIndexHtml(mode, command), - emitNoCrispIndexAsIndexHtml(mode), + useLocalnetShellHtml(mode, command), + emitLocalnetShellAsIndexHtml(mode), react(), tsconfigPaths(), VitePWA({ @@ -99,7 +101,7 @@ export default defineConfig(({ command, mode }): UserConfig => { input: { main: path.join( rootDir, - useNoCrispIndex ? 'indexLocal.html' : 'index.html' + useLocalnetShell ? 'indexLocal.html' : 'index.html' ), }, } From ae9abaf9fda034c8193c53797be84900a37b16e7 Mon Sep 17 00:00:00 2001 From: Carter Date: Wed, 6 May 2026 18:18:57 -0600 Subject: [PATCH 05/14] local login now functional --- src/app/App.tsx | 30 +++++-- src/app/LocalAuthPlaceholder.tsx | 130 +++++++++++++++++++++++------ src/app/UserWrapper.tsx | 11 ++- src/navigation/BottomNavigator.tsx | 4 +- src/navigation/Router.tsx | 12 +-- src/navigation/SideNavigator.tsx | 4 +- src/pages/Logout.tsx | 4 +- src/providers/http.tsx | 47 ++++++----- src/user/UserMenu.tsx | 4 +- 9 files changed, 174 insertions(+), 72 deletions(-) diff --git a/src/app/App.tsx b/src/app/App.tsx index 09956c2..3616784 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -9,9 +9,12 @@ import LocalAuthPlaceholder from './LocalAuthPlaceholder' import UserWrapper from './UserWrapper' import { getWhitelabel } from 'services/whiteLabel' import { AppThemeProvider } from 'theme/AppThemeProvider' +import { LocalAuthProvider, Auth0AuthBridge } from '../providers/authContext' function App() { - const [token, setToken] = useState(undefined) + const [token, setToken] = useState(() => { + return localStorage.getItem('local_auth_token') || undefined + }) const whiteLabel = getWhitelabel() const manifestPath = "/" + whiteLabel.name.replace(/\s/g, "") + "/manifest.json" @@ -59,9 +62,22 @@ function App() { if (!shouldMountAuth0Provider()) { const placeholderReason = isAuth0Configured() && !isAuth0SpaOriginAllowed() ? 'insecure_origin' : 'unconfigured' + + if (!token) { + return ( + + + + ) + } + return ( - + + + + + ) } @@ -81,10 +97,12 @@ function App() { > {/* */} - { token ? - - - + { token ? + + + + + : void } -/** - * Shown when Auth0 is not used (missing config and/or non–secure context). - * Replace with backend-driven login once local auth is implemented. - */ export default function LocalAuthPlaceholder(props: Props) { - const { reason = 'unconfigured' } = props + const { reason = 'unconfigured', setToken } = props const productName = getName() + const [mode, setMode] = useState<'login' | 'signup'>('login') + const [email, setEmail] = useState('') + const [password, setPassword] = useState('') + const [name, setName] = useState('') + const [error, setError] = useState('') + const [loading, setLoading] = useState(false) + + const apiUrl = import.meta.env.VITE_APP_API_URL + + const handleSignup = async () => { + setError('') + setLoading(true) + try { + const resp = await axios.post(`${apiUrl}/local-auth/signup`, { email, password, name }) + const token = resp.data.token + if (token && setToken) { + localStorage.setItem('local_auth_token', token) + setToken(token) + } + } catch (err: any) { + setError(err.response?.data?.error || 'Signup failed') + } finally { + setLoading(false) + } + } + + const handleLogin = async () => { + setError('') + setLoading(true) + try { + const resp = await axios.post(`${apiUrl}/local-auth/login`, { email, password }) + const token = resp.data.token + if (token && setToken) { + localStorage.setItem('local_auth_token', token) + setToken(token) + } + } catch (err: any) { + setError(err.response?.data?.error || 'Login failed') + } finally { + setLoading(false) + } + } + + const handleSubmit = (e: React.FormEvent) => { + e.preventDefault() + if (mode === 'signup') { + handleSignup() + } else { + handleLogin() + } + } + const explanation = reason === 'insecure_origin' - ? 'This URL is not a secure context for cloud sign-in (Auth0 requires HTTPS, localhost, or 127.0.0.1). Use local account sign-in here instead once it is connected.' - : 'Cloud sign-in (Auth0) is not configured for this deployment. Local account sign-in will be available here.' + ? 'This URL is not a secure context for cloud sign-in. Use local account sign-in instead.' + : 'Local account sign-in for this deployment.' return ( <> @@ -35,25 +85,55 @@ export default function LocalAuthPlaceholder(props: Props) { }} > - - - {productName} - - - {explanation} - - - - - - Buttons are placeholders until the backend login flow is wired up. - - + diff --git a/src/app/UserWrapper.tsx b/src/app/UserWrapper.tsx index f837b70..6b0fd92 100644 --- a/src/app/UserWrapper.tsx +++ b/src/app/UserWrapper.tsx @@ -1,7 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react' import './App.css' import { useUserAPI } from '../providers/pond/userAPI' -import { useAuth0 } from '@auth0/auth0-react' import { or } from '../utils/types' import LoadingScreen from './LoadingScreen' import NavigationContainer from '../navigation/NavigationContainer' @@ -63,13 +62,19 @@ export default function UserWrapper(props: Props) { const [loading, setLoading] = useState(false) const userAPI = useUserAPI(); const classes = useStyles(); - const useAuth = useAuth0(); const hasFetched = useRef(false); const [global, setGlobal] = useState(undefined) const snackbar = useSnackbar() const isMobile = useMobile() - const user_id = or(useAuth.user?.sub, "") + const user_id = (() => { + try { + const payload = JSON.parse(atob(token.split('.')[1])) + return or(payload.sub, '') + } catch { + return '' + } + })() const loadUser = useCallback(() => { if (!userAPI.getUserWithTeam) return; diff --git a/src/navigation/BottomNavigator.tsx b/src/navigation/BottomNavigator.tsx index 6395bd4..0cd0366 100644 --- a/src/navigation/BottomNavigator.tsx +++ b/src/navigation/BottomNavigator.tsx @@ -20,7 +20,7 @@ import OmniAirDeviceIcon from "products/AviationIcons/OmniAirDeviceIcon"; import AirportMapIcon from "products/AviationIcons/AirportMapIcon"; import PlaneIcon from "products/AviationIcons/PlaneIcon"; import JobsiteIcon from "products/Construction/JobSiteIcon"; -import { useAuth0 } from "@auth0/auth0-react"; +import { useAuthContext } from "providers/authContext"; interface Props { sideIsOpen: boolean; @@ -33,7 +33,7 @@ export default function BottomNavigator(props: Props) { const navigate = useNavigate(); const location = useLocation(); const prevLocation = usePrevious(location); - const { isAuthenticated } = useAuth0(); + const { isAuthenticated } = useAuthContext(); const [{ user }] = useGlobalState(); const [route, setRoute] = useState(sideIsOpen ? "side" : ""); const isAg = IsAdaptiveAgriculture(); diff --git a/src/navigation/Router.tsx b/src/navigation/Router.tsx index 94ce101..cde11f9 100644 --- a/src/navigation/Router.tsx +++ b/src/navigation/Router.tsx @@ -1,7 +1,7 @@ import { lazy, Suspense } from "react"; import LoadingScreen from "../app/LoadingScreen"; import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom"; -import { useAuth0 } from "@auth0/auth0-react"; +import { useAuthContext } from "providers/authContext"; import Header from "app/Header"; import Logout from "pages/Logout"; import { ErrorBoundary } from "react-error-boundary"; @@ -57,7 +57,7 @@ export const appendToUrl = (appendage: number | string) => { export default function Router() { - const { /*isAuthenticated, loginWithRedirect,*/ isLoading } = useAuth0(); + const { isAuthenticated } = useAuthContext(); const whiteLabel = getWhitelabel(); const [{ user }] = useGlobalState(); @@ -306,13 +306,7 @@ export default function Router() { ); } - if (isLoading) return null; - // if (!isAuthenticated) { - // loginWithRedirect() - // return ( - // null - // ) - // } + if (!isAuthenticated) return null; function ErrorFallback({ error }: { error: Error }) { return
Something went wrong: {error.stack}
; diff --git a/src/navigation/SideNavigator.tsx b/src/navigation/SideNavigator.tsx index 815f30b..95b2afd 100644 --- a/src/navigation/SideNavigator.tsx +++ b/src/navigation/SideNavigator.tsx @@ -35,7 +35,7 @@ import { IsStreamline, } from "services/whiteLabel"; import MiningIcon from "products/ventilation/MiningIcon"; -import { useAuth0 } from "@auth0/auth0-react"; +import { useAuthContext } from "providers/authContext"; import FieldsIcon from "products/AgIcons/FieldsIcon"; import PlaneIcon from "products/AviationIcons/PlaneIcon"; import AirportMapIcon from "products/AviationIcons/AirportMapIcon"; @@ -130,7 +130,7 @@ interface Props { export default function SideNavigator(props: Props) { const { open, onOpen, onClose } = props; - const { isAuthenticated } = useAuth0() + const { isAuthenticated } = useAuthContext() const theme = useTheme(); const width = useWidth(); const classes = useStyles(); diff --git a/src/pages/Logout.tsx b/src/pages/Logout.tsx index 337c7b6..79e4538 100644 --- a/src/pages/Logout.tsx +++ b/src/pages/Logout.tsx @@ -1,9 +1,9 @@ -import { useAuth0 } from "@auth0/auth0-react"; +import { useAuthContext } from "providers/authContext"; import LoadingScreen from "app/LoadingScreen"; import { useEffect } from "react"; export default function Logout() { - const { logout } = useAuth0(); + const { logout } = useAuthContext(); useEffect(() => { logout(); diff --git a/src/providers/http.tsx b/src/providers/http.tsx index 3e93f04..86ba8b5 100644 --- a/src/providers/http.tsx +++ b/src/providers/http.tsx @@ -2,7 +2,7 @@ import axios, { AxiosRequestConfig, AxiosResponse } from "axios"; import moment from "moment"; import { createContext, PropsWithChildren, useContext } from "react"; import PondProvider from "./pond/pond"; -import { useAuth0 } from "@auth0/auth0-react"; +import { useAuthContext } from "./authContext"; import SnackbarProvider from "./Snackbar"; interface IHTTPContext { @@ -30,7 +30,7 @@ export const HTTPContext = createContext({} as IHTTPContext); export default function HTTPProvider(props: Props) { const { children, token } = props; - const { isAuthenticated, loginWithRedirect } = useAuth0(); + const { isAuthenticated, loginWithRedirect } = useAuthContext(); const defaultOptions = (demo: boolean = false) => { if (demo || !isAuthenticated || !token) { @@ -42,7 +42,7 @@ export default function HTTPProvider(props: Props) { } const config = { - headers: { + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, @@ -50,31 +50,24 @@ export default function HTTPProvider(props: Props) { return config; }; - function isTokenExpired(token: string): boolean { + function isTokenExpired(token: string | undefined): boolean { + if (!token) return true; try { - // Split the token and decode the payload (second part) const payloadBase64 = token.split('.')[1]; - const decodedPayload = atob(payloadBase64); // Decode base64 - const payload = JSON.parse(decodedPayload); - - // Get expiration time (in seconds) + const payload = JSON.parse(atob(payloadBase64)); const exp = payload.exp; - - if (!exp) return true; // No exp field? Treat as expired - - // Current time in seconds - const now = Math.floor(Date.now() / 1000); - - // Compare - return now >= exp; - } catch (error) { - console.error("Invalid token format:", error); - return true; // Err on the side of caution if decoding fails + if (!exp) return true; + return Math.floor(Date.now() / 1000) >= exp; + } catch { + return true; } } function get(url: string, spreadOptions?: AxiosRequestConfig): Promise> { - if (isTokenExpired(token)) loginWithRedirect() + if (isTokenExpired(token)) { + loginWithRedirect(); + return Promise.reject(new Error("token expired")); + } return axios.get(url, {...defaultOptions(), ...spreadOptions}); } @@ -83,6 +76,10 @@ export default function HTTPProvider(props: Props) { data?: any, spreadOptions?: AxiosRequestConfig ): Promise> { + if (isTokenExpired(token)) { + loginWithRedirect(); + return Promise.reject(new Error("token expired")); + } return axios.put(url, data, { ...defaultOptions(), ...spreadOptions }); } @@ -91,10 +88,18 @@ export default function HTTPProvider(props: Props) { data?: any, spreadOptions?: AxiosRequestConfig ): Promise> { + if (isTokenExpired(token)) { + loginWithRedirect(); + return Promise.reject(new Error("token expired")); + } return axios.post(url, data, { ...defaultOptions(), ...spreadOptions }); } function del(url: string, spreadOptions?: AxiosRequestConfig): Promise> { + if (isTokenExpired(token)) { + loginWithRedirect(); + return Promise.reject(new Error("token expired")); + } return axios.delete(url, { ...defaultOptions(), ...spreadOptions }); } diff --git a/src/user/UserMenu.tsx b/src/user/UserMenu.tsx index a65b935..1eb2da5 100644 --- a/src/user/UserMenu.tsx +++ b/src/user/UserMenu.tsx @@ -5,7 +5,7 @@ import { makeStyles } from "@mui/styles"; import { LockOpen, Person, Lock, Settings, SupervisedUserCircle as TeamIcon, ExitToApp, PersonAdd } from "@mui/icons-material"; import { useState } from "react"; import UserTeamName from "./UserTeamName"; -import { useAuth0 } from "@auth0/auth0-react"; +import { useAuthContext } from "providers/authContext"; import UserSettings from "./UserSettings"; import UserAvatar from "./UserAvatar"; import { purple } from "@mui/material/colors"; @@ -77,7 +77,7 @@ export default function UserMenu() { // const { toggleMode } = useThemeMode() const [{ user, team, as }, dispatch] = useGlobalState(); - const { loginWithRedirect } = useAuth0(); + const { loginWithRedirect } = useAuthContext(); const classes = useStyles(); const theme = useTheme(); From c5493722622bfbe6b35c0c610a689ee17ba2edfe Mon Sep 17 00:00:00 2001 From: Carter Date: Tue, 19 May 2026 16:06:48 -0600 Subject: [PATCH 06/14] added forgotten local auth file --- src/providers/authContext.tsx | 44 +++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/providers/authContext.tsx diff --git a/src/providers/authContext.tsx b/src/providers/authContext.tsx new file mode 100644 index 0000000..cee441c --- /dev/null +++ b/src/providers/authContext.tsx @@ -0,0 +1,44 @@ +import { useAuth0 } from "@auth0/auth0-react" +import { createContext, PropsWithChildren, useContext } from "react" + +interface IAuthContext { + isAuthenticated: boolean + loginWithRedirect: () => void + logout: () => void +} + +const AuthContext = createContext({ + isAuthenticated: false, + loginWithRedirect: () => {}, + logout: () => {}, +}) + +export function LocalAuthProvider(props: PropsWithChildren<{ token: string }>) { + const { children, token } = props + const doLogout = () => { + localStorage.removeItem('local_auth_token') + window.location.href = '/' + } + return ( + + {children} + + ) +} + +export function Auth0AuthBridge(props: PropsWithChildren<{}>) { + const { isAuthenticated, loginWithRedirect, logout } = useAuth0() + return ( + logout({ logoutParams: { returnTo: window.location.origin } }) }}> + {props.children} + + ) +} + +export const useAuthContext = () => useContext(AuthContext) From 0410a5ccae867f167cf81abedf6c9a30b0c727c9 Mon Sep 17 00:00:00 2001 From: Carter Date: Tue, 19 May 2026 16:19:48 -0600 Subject: [PATCH 07/14] removing auth dependency from shared authorized ui --- src/pages/Login.tsx | 5 +++-- src/providers/LoginButton.tsx | 6 +++--- src/providers/authContext.tsx | 4 ++-- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/pages/Login.tsx b/src/pages/Login.tsx index 3dc7d2f..ed56673 100644 --- a/src/pages/Login.tsx +++ b/src/pages/Login.tsx @@ -1,10 +1,11 @@ -import { RedirectLoginOptions, useAuth0 } from "@auth0/auth0-react"; +import { RedirectLoginOptions } from "@auth0/auth0-react"; // import { useAuth } from "hooks"; import queryString from "query-string"; import { useEffect } from "react"; import { useLocation } from "react-router"; // import Loading from "./Loading"; import LoadingScreen from "app/LoadingScreen"; +import { useAuthContext } from "providers/authContext"; // interface Props { // prevPath?: string; @@ -13,7 +14,7 @@ import LoadingScreen from "app/LoadingScreen"; export default function Login() { // const { prevPath } = props; const location = useLocation(); - const { loginWithRedirect } = useAuth0(); + const { loginWithRedirect } = useAuthContext(); // const setRouteBeforeLogin = useCallback((): Promise => { // return new Promise(function(resolve) { diff --git a/src/providers/LoginButton.tsx b/src/providers/LoginButton.tsx index c8f9aac..e9e04a8 100644 --- a/src/providers/LoginButton.tsx +++ b/src/providers/LoginButton.tsx @@ -1,7 +1,7 @@ -import { useAuth0 } from '@auth0/auth0-react'; +import { useAuthContext } from './authContext'; const LoginButton = () => { - const { loginWithRedirect } = useAuth0(); + const { loginWithRedirect } = useAuthContext(); return (