Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,4 @@ MIGRATION-NOTES.md
# typescript
*.tsbuildinfo
next-env.d.ts
.env.local
20 changes: 17 additions & 3 deletions apps/credit-history/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { NextIntlClientProvider } from 'next-intl';
import { getMessages, getTranslations } from 'next-intl/server';
import { Header } from '@/components/header';
import { Footer } from '@/components/footer';
import { ActaProvider } from '@/providers/acta-provider';
import { SessionProvider } from '@/session/session-provider';
import './globals.css';

const fontDisplay = Space_Grotesk({
Expand Down Expand Up @@ -46,9 +48,21 @@ export default async function RootLayout({
>
<body className="min-h-full flex flex-col">
<NextIntlClientProvider messages={messages}>
<Header />
<main className="flex flex-1 flex-col">{children}</main>
<Footer />
{/*
* ActaProvider: mounts ActaConfig as low as possible — inside
* NextIntlClientProvider but outside the page content, so only
* components that need the ACTA client context are affected.
*
* SessionProvider: wraps the shell so the header's WalletButton
* and any page-level session gating can both access useSession().
*/}
<ActaProvider>
<SessionProvider>
<Header />
<main className="flex flex-1 flex-col">{children}</main>
<Footer />
</SessionProvider>
</ActaProvider>
</NextIntlClientProvider>
</body>
</html>
Expand Down
4 changes: 2 additions & 2 deletions apps/credit-history/src/app/share/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

import * as React from 'react';
import { getMockCreditCredentialSource } from '@acta-products/acta';
import { getCredentialSource } from '@acta-products/acta';
import { CreditCredential, CreditProfileSummary } from '@acta-products/acta/types';
import {
Card,
Expand Down Expand Up @@ -49,7 +49,7 @@ export default function SharePage() {
React.useEffect(() => {
const loadData = async () => {
try {
const source = getMockCreditCredentialSource();
const source = getCredentialSource();
const [creds, prof] = await Promise.all([
source.listCredentials(),
source.getProfileSummary(),
Expand Down
4 changes: 2 additions & 2 deletions apps/credit-history/src/app/verify/[token]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import * as React from 'react';
import { useParams } from 'next/navigation';
import { getMockCreditCredentialSource } from '@acta-products/acta';
import { getCredentialSource } from '@acta-products/acta';
import { CreditCredential, CreditProfileSummary } from '@acta-products/acta/types';
import {
Card,
Expand Down Expand Up @@ -86,7 +86,7 @@ export default function VerifyPage() {
}

// 3. Retrieve credentials from mock source
const source = getMockCreditCredentialSource();
const source = getCredentialSource();
const [allCreds, prof] = await Promise.all([
source.listCredentials(),
source.getProfileSummary(),
Expand Down
7 changes: 6 additions & 1 deletion apps/credit-history/src/components/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Link from 'next/link';
import { getTranslations } from 'next-intl/server';
import { NavLink } from '@acta-products/ui/components/nav-link';
import { MobileMenu } from './mobile-menu';
import { WalletButton } from './wallet-button';

export async function Header() {
const t = await getTranslations('nav');
Expand Down Expand Up @@ -34,7 +35,11 @@ export async function Header() {
))}
</nav>

<MobileMenu links={navLinks} />
{/* WalletButton is a Client Component — safe inside this Server Component */}
<div className="flex items-center gap-2">
<WalletButton />
<MobileMenu links={navLinks} />
</div>
</div>
</header>
);
Expand Down
87 changes: 87 additions & 0 deletions apps/credit-history/src/components/wallet-button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
'use client';

/**
* WalletButton — Client Component rendered inside the Server Component header.
*
* States:
* disconnected → "Connect wallet" button
* connecting → disabled button with loading spinner + i18n label
* connected → truncated G... address + truncated DID + "Disconnect" button
*
* All text via the 'session' i18n namespace. No hardcoded strings.
*/

import { useSession } from '@/session/session-provider';
import { useTranslations } from 'next-intl';
import { Button } from '@acta-products/ui';
import { Wallet, LogOut, Loader2 } from 'lucide-react';

/** GABC...7KQ4 — shows first 4 and last 4 chars */
function truncateAddress(address: string): string {
return `${address.slice(0, 4)}...${address.slice(-4)}`;
}

/** did:pkh:stellar:testnet:GABC...7KQ4 — keeps prefix, truncates address */
function truncateDid(did: string): string {
const parts = did.split(':');
// did:pkh:stellar:{network}:{address}
if (parts.length < 5) return did;
const prefix = parts.slice(0, 4).join(':');
const addr = parts[4];
return `${prefix}:${addr.slice(0, 4)}...${addr.slice(-4)}`;
}

export function WalletButton() {
const { status, address, did, connect, disconnect } = useSession();
const t = useTranslations('session');

if (status === 'disconnected') {
return (
<Button
size="sm"
variant="outline"
onClick={() => connect().catch(console.error)}
className="gap-1.5"
>
<Wallet className="size-3.5" />
{t('connect')}
</Button>
);
}

if (status === 'connecting') {
return (
<Button size="sm" variant="outline" disabled className="gap-1.5">
<Loader2 className="size-3.5 animate-spin" />
{t('connecting')}
</Button>
);
}

// connected
return (
<div className="flex items-center gap-2">
<div className="hidden sm:flex flex-col items-end">
<span className="text-xs font-medium text-foreground font-mono">
{address ? truncateAddress(address) : ''}
</span>
<span
className="text-[10px] text-muted-foreground font-mono truncate max-w-[180px]"
title={did ?? ''}
>
{did ? truncateDid(did) : ''}
</span>
</div>
<Button
size="sm"
variant="ghost"
onClick={() => disconnect().catch(console.error)}
className="gap-1.5 text-muted-foreground hover:text-destructive"
aria-label={t('disconnect')}
>
<LogOut className="size-3.5" />
<span className="hidden sm:inline">{t('disconnect')}</span>
</Button>
</div>
);
}
9 changes: 9 additions & 0 deletions apps/credit-history/src/i18n/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,14 @@
"share": {
"title": "Share",
"description": "Share your credentials with third parties here."
},
"session": {
"connect": "Connect wallet",
"connecting": "Connecting…",
"disconnect": "Disconnect",
"connectedAs": "Connected as",
"notConnected": "No wallet connected",
"connectCta": "Connect your Stellar wallet to access your credentials.",
"connectButton": "Connect wallet"
}
}
35 changes: 22 additions & 13 deletions apps/credit-history/src/i18n/messages/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,39 @@
"description": "Portable credit history for financial inclusion, built on ACTA verifiable credentials."
},
"nav": {
"home": "Home",
"credentials": "My credentials",
"share": "Share",
"openMenu": "Open menu",
"closeMenu": "Close menu"
"home": "Inicio",
"credentials": "Mis credenciales",
"share": "Compartir",
"openMenu": "Abrir menú",
"closeMenu": "Cerrar menú"
},
"footer": {
"tagline": "Portable credit history built on ACTA verifiable credentials.",
"rights": "All rights reserved."
"tagline": "Historial crediticio portable sobre credenciales verificables de ACTA.",
"rights": "Todos los derechos reservados."
},
"common": {
"appName": "Credit History",
"comingSoon": "Coming soon"
"comingSoon": "Próximamente"
},
"home": {
"title": "Credit History",
"description": "Portable credit history built on ACTA verifiable credentials. Product skeleton — nothing implemented yet."
"description": "Historial crediticio portable sobre credenciales verificables de ACTA."
},
"credentials": {
"title": "My Credentials",
"description": "Your verifiable credentials will appear here."
"title": "Mis Credenciales",
"description": "Tus credenciales verificables aparecerán aquí."
},
"share": {
"title": "Share",
"description": "Share your credentials with third parties here."
"title": "Compartir",
"description": "Comparte tus credenciales con terceros aquí."
},
"session": {
"connect": "Conectar billetera",
"connecting": "Conectando…",
"disconnect": "Desconectar",
"connectedAs": "Conectado como",
"notConnected": "Sin billetera conectada",
"connectCta": "Conecta tu billetera Stellar para acceder a tus credenciales.",
"connectButton": "Conectar billetera"
}
}
41 changes: 41 additions & 0 deletions apps/credit-history/src/providers/acta-provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use client';

import { ActaConfig, mainNet, testNet } from '@acta-products/acta';
import type { baseURL } from '@acta-products/acta';
import type { StellarNetwork } from '@acta-products/acta/did';

// Next.js inlines NEXT_PUBLIC_* at build time — declare so TypeScript resolves.
declare const NEXT_PUBLIC_STELLAR_NETWORK: string | undefined;
declare const NEXT_PUBLIC_ACTA_API_KEY: string | undefined;

function resolveBaseURL(network: StellarNetwork): baseURL {
return network === 'mainnet' ? mainNet : testNet;
}

function resolveNetwork(): StellarNetwork {
const raw =
typeof NEXT_PUBLIC_STELLAR_NETWORK !== 'undefined'
? (NEXT_PUBLIC_STELLAR_NETWORK as string)
: 'testnet';
return raw === 'mainnet' ? 'mainnet' : 'testnet';
Comment on lines +7 to +20

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Find NEXT_PUBLIC usage patterns =="
rg -n -C2 'NEXT_PUBLIC_(STELLAR_NETWORK|ACTA_API_KEY)|process\.env\.NEXT_PUBLIC_(STELLAR_NETWORK|ACTA_API_KEY)'

echo
echo "== Check for explicit global injections of bare NEXT_PUBLIC_* =="
rg -n -C2 'globalThis\.NEXT_PUBLIC_|window\.NEXT_PUBLIC_|declare const NEXT_PUBLIC_'

echo
echo "== Inspect Next config for custom env/define wiring =="
fd -i 'next.config.*' -x sh -c 'echo "--- {} ---"; sed -n "1,240p" "{}"'
rg -n -C3 'DefinePlugin|webpack\(|env\s*:' --iglob '*next.config.*'

Repository: ACTA-Team/products-acta

Length of output: 5470


🌐 Web query:

Next.js NEXT_PUBLIC environment variables process.env vs declare const globals

💡 Result:

In Next.js, the NEXT_PUBLIC_ prefix and manual constant declarations (or configuration-based variables) serve different purposes regarding accessibility, security, and the build process. NEXT_PUBLIC_ Environment Variables By prefixing an environment variable with NEXT_PUBLIC_ (e.g., NEXT_PUBLIC_API_URL), you instruct Next.js to inline the value directly into the JavaScript bundle at build time [1][2][3]. This makes the variable accessible to both server-side code and client-side browser code [1][4][5]. Because these values are baked into the static JavaScript files, they are publicly visible to anyone who inspects the browser source code [6][7]. Consequently, you must never store sensitive secrets (such as API private keys or database passwords) using the NEXT_PUBLIC_ prefix [3][6][5]. Furthermore, because they are inlined at build time, any changes to these variables require a full application rebuild; they cannot be updated at runtime without redeploying the app [1][3][6]. Process.env vs. Global Constants Next.js relies on static analysis (via tools like Webpack's DefinePlugin or Turbopack) to perform the replacement of process.env.NEXT_PUBLIC_ variables [8][3][9]. For this to work correctly, you must use the full, explicit syntax: process.env.NEXT_PUBLIC_VAR_NAME [8][3]. Do not attempt to destructure process.env (e.g., const { NEXT_PUBLIC_VAR } = process.env) or use dynamic access (e.g., process.env[key]), as these patterns bypass the build-time replacement mechanism and will return undefined in the browser bundle [3][9]. Similarly, accessing global.process.env instead of process.env is considered dynamic and will also fail to inline correctly [8]. Server-Only Variables Any environment variable defined in your .env files that does not start with NEXT_PUBLIC_ is strictly server-only [1][10][11]. These variables are accessible in Node.js environments—such as API routes, Server Components, and middleware—but are completely stripped from the client-side JavaScript bundle [3][5][12]. This is the secure, default method for handling sensitive credentials [3][11]. Summary of Best Practices 1. Sensitive Secrets: Use standard environment variables (no prefix) and access them only on the server [5][7]. 2. Public Configuration: Use the NEXT_PUBLIC_ prefix only for non-sensitive values like public API base URLs or feature flags [3][7]. 3. Avoid Destructuring: Always reference variables using the full process.env.VARIABLE_NAME syntax [3][9]. 4. Startup Validation: Use a library like Zod to validate your environment variables at application startup, which helps catch missing or misconfigured variables immediately [6][5][12]. 5. No Runtime Updates: Remember that NEXT_PUBLIC_ values are frozen at build time; for runtime-configurable values, you must expose them through an API endpoint or another dynamic delivery mechanism [1][2].

Citations:


🌐 Web query:

Next.js how are NEXT_PUBLIC_ variables exposed to browser client code

💡 Result:

In Next.js, environment variables prefixed with NEXT_PUBLIC_ are exposed to the browser by being statically "inlined" into your JavaScript bundles during the build process [1][2]. When you run the build command (e.g., next build), the Next.js bundler (such as webpack or Turbopack) scans your code for any occurrences of process.env.NEXT_PUBLIC_VARIABLE_NAME and replaces these references with the actual string value defined in your environment at that time [1][3][4]. Key implications of this mechanism include: 1. Build-Time Freezing: Because these variables are hard-coded into your JavaScript bundles at build time, they are "frozen" [1][5]. If you change the value of a NEXT_PUBLIC_ variable in your environment (such as in your.env file or a hosting provider's dashboard) after the build is complete, your application will not reflect that change until you rebuild the project [1][3][5]. 2. Client-Side Exposure: Any variable prefixed with NEXT_PUBLIC_ is intentionally exposed to the browser [1][4]. Consequently, these values are visible to anyone who inspects the client-side JavaScript or the source code of your page [6][5]. You must never use this prefix for sensitive secrets, such as API private keys, database credentials, or internal configuration values [6][3][5]. 3. Default Behavior for Non-Prefixed Variables: Environment variables that do not use the NEXT_PUBLIC_ prefix are kept server-only [1][3]. If you attempt to access a non-prefixed environment variable (like process.env.DATABASE_URL) in client-side code, it will resolve to undefined [7][3][5]. 4. Strict Pattern Matching: The replacement process performs literal text matching [4]. It requires that you use the full expression, such as process.env.NEXT_PUBLIC_VAR, directly in your code [8][4]. Destructuring process.env or using dynamic keys will prevent the bundler from correctly identifying and replacing the variable, likely resulting in undefined at runtime [8][4]. For values that need to be dynamic or secret, the recommended approach is to keep those variables on the server and access them only through server-side code or by creating a dedicated API route that the client can call to fetch necessary configuration at runtime [1][6].

Citations:


Replace bare NEXT_PUBLIC_* declarations with process.env.NEXT_PUBLIC_* to enable proper environment variable inlining.

Next.js uses static analysis to replace process.env.NEXT_PUBLIC_* references at build time. The current approach using declare const bypasses this mechanism entirely, leaving these variables undefined at runtime and forcing fallback to 'testnet' and the placeholder API key. Use the standard Next.js pattern: process.env.NEXT_PUBLIC_STELLAR_NETWORK and process.env.NEXT_PUBLIC_ACTA_API_KEY.

Suggested fix
-'use client';
+'use client';

 import { ActaConfig, mainNet, testNet } from '`@acta-products/acta`';
 import type { baseURL } from '`@acta-products/acta`';
 import type { StellarNetwork } from '`@acta-products/acta/did`';
-
-// Next.js inlines NEXT_PUBLIC_* at build time — declare so TypeScript resolves.
-declare const NEXT_PUBLIC_STELLAR_NETWORK: string | undefined;
-declare const NEXT_PUBLIC_ACTA_API_KEY: string | undefined;
 
 function resolveBaseURL(network: StellarNetwork): baseURL {
   return network === 'mainnet' ? mainNet : testNet;
 }
 
 function resolveNetwork(): StellarNetwork {
-  const raw =
-    typeof NEXT_PUBLIC_STELLAR_NETWORK !== 'undefined'
-      ? (NEXT_PUBLIC_STELLAR_NETWORK as string)
-      : 'testnet';
+  const raw = process.env.NEXT_PUBLIC_STELLAR_NETWORK ?? 'testnet';
   return raw === 'mainnet' ? 'mainnet' : 'testnet';
 }
@@
 export function ActaProvider({ children }: ActaProviderProps) {
   const network = resolveNetwork();
   const baseURL = resolveBaseURL(network);
-  const apiKey =
-    (typeof NEXT_PUBLIC_ACTA_API_KEY !== 'undefined' &&
-    (NEXT_PUBLIC_ACTA_API_KEY as string).length > 0)
-      ? (NEXT_PUBLIC_ACTA_API_KEY as string)
-      : 'placeholder-batch1-no-api-calls';
+  const apiKey =
+    process.env.NEXT_PUBLIC_ACTA_API_KEY?.trim().length
+      ? process.env.NEXT_PUBLIC_ACTA_API_KEY
+      : 'placeholder-batch1-no-api-calls';
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/credit-history/src/providers/acta-provider.tsx` around lines 7 - 20,
Remove the declare const statements for NEXT_PUBLIC_STELLAR_NETWORK and
NEXT_PUBLIC_ACTA_API_KEY at the top of the file. Update the resolveNetwork
function to reference process.env.NEXT_PUBLIC_STELLAR_NETWORK directly instead
of using the declared constant, which will enable Next.js to properly inline
these environment variables at build time through its static analysis instead of
leaving them undefined at runtime.

}

interface ActaProviderProps {
children: React.ReactNode;
}

export function ActaProvider({ children }: ActaProviderProps) {
const network = resolveNetwork();
const baseURL = resolveBaseURL(network);
const apiKey =
(typeof NEXT_PUBLIC_ACTA_API_KEY !== 'undefined' &&
(NEXT_PUBLIC_ACTA_API_KEY as string).length > 0)
? (NEXT_PUBLIC_ACTA_API_KEY as string)
: 'placeholder-batch1-no-api-calls';

return (
<ActaConfig baseURL={baseURL} apiKey={apiKey}>
{children}
</ActaConfig>
);
}
Loading