Skip to content

Add optional BLOCKY_AUTH_HEADER environment variable#272

Open
mlhynfield wants to merge 2 commits intoGabeDuarteM:mainfrom
mlhynfield:auth-header
Open

Add optional BLOCKY_AUTH_HEADER environment variable#272
mlhynfield wants to merge 2 commits intoGabeDuarteM:mainfrom
mlhynfield:auth-header

Conversation

@mlhynfield
Copy link

Before Submitting This PR

Please confirm you have done the following:

If this is a feature or change that was previously closed/rejected:

  • I have explained in the description below why this should be reconsidered

Human Written Description

In cases such as my own where the blocky-ui does not run in the same network space as blocky itself, since the blocky API must be exposed at an endpoint reachable by blocky-ui, I would like to protect it via a reverse-proxy with, for example, basic auth. Currently, blocky-ui does not support custom headers, so if accepted this change will add the option to configure an Authorization header via the BLOCKY_AUTH_HEADER environment variable to authenticate API requests.

Related Issues/Discussions

I couldn't find any related issues, discussions, or PRs.

Testing

Since I currently have blocky exposed on my home network at both an authenticated endpoint and a non-authenticated endpoint, I tested this via the bun dev against both endpoints. With BLOCKY_AUTH_HEADER set to the correct value, I could connect blocky-ui to both endpoints, and with it unset or set to an incorrect value I could connect blocky-ui to the unauthenticated endpoint but not the authenticated endpoint.

Screenshots/Videos (if applicable)

Before:
image

After:
image

AI Assistance

  • AI was used in this PR (please describe below)

If AI was used:

  • Tools used:
    • GitHub Copilot agent (Claude Sonnet 4.5)
  • How extensively:
    • Used to create the entire implementation with strict guidelines
    • Not used for testing and validation, which I did by hand
    • Since this was a relatively small change, I've looked over every line changed several times

@changeset-bot
Copy link

changeset-bot bot commented Mar 12, 2026

🦋 Changeset detected

Latest commit: 1155a66

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
blocky-ui Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link

coderabbitai bot commented Mar 12, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 802215d8-fec8-4b02-a1c0-99328d240c9b

📥 Commits

Reviewing files that changed from the base of the PR and between 1633d06 and 1155a66.

📒 Files selected for processing (1)
  • .env.example
📜 Recent review details
🔇 Additional comments (1)
.env.example (1)

22-27: Well-documented and correctly implemented!

The documentation for BLOCKY_AUTH_HEADER is clear and the examples are accurate:

  • The Bearer token and Basic Auth examples correctly show the full Authorization header value format
  • The "Optional:" label aligns with the schema definition in src/env.js
  • The previous concern about the misleading API Key example has been properly addressed

The placement after INSTANCE_NAME and before database configuration is logical, and the security warning in the file header adequately covers credential handling.


Summary by CodeRabbit

  • New Features

    • Added optional BLOCKY_AUTH_HEADER to enable supplying an Authorization header for Blocky and Prometheus requests.
  • Documentation

    • Updated configuration docs, examples, and environment sample to document BLOCKY_AUTH_HEADER usage (examples for Bearer and Basic auth) and its default/behavior.

Walkthrough

Adds an optional BLOCKY_AUTH_HEADER env var, documents it, wires it into the runtime env schema, and conditionally includes it as an Authorization header in Blocky and Prometheus HTTP requests.

Changes

Cohort / File(s) Summary
Changeset & examples
.changeset/polite-eyes-search.md, .env.example, AGENTS.md, README.md
Add documentation, examples, and deployment snippets describing the new optional BLOCKY_AUTH_HEADER env var.
Environment mapping
src/env.js
Add BLOCKY_AUTH_HEADER to server schema as z.string().optional() and map from process.env.BLOCKY_AUTH_HEADER.
API clients
src/server/api/routers/blocky.ts, src/server/prometheus/client.ts
When present, include Authorization: BLOCKY_AUTH_HEADER in request headers for Blocky and Prometheus calls; otherwise omit the header.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 I found a header, soft and light,
Tucked in envs to guard the night,
Blocky and metrics whisper "OK",
Secrets travel the safer way,
Hops of joy—secure delight! ✨

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add optional BLOCKY_AUTH_HEADER environment variable' directly and clearly describes the main change—introducing a new optional environment variable for authentication headers.
Description check ✅ Passed The PR description includes a clear human-written explanation of the problem (blocky API exposed via reverse proxy needing authentication), the solution (BLOCKY_AUTH_HEADER environment variable), testing performed, and screenshots demonstrating the feature working.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

CodeRabbit can generate a title for your PR based on the changes with custom instructions.

Set the reviews.auto_title_instructions setting to generate a title for your PR based on the changes in the PR with custom instructions.

@vercel
Copy link
Contributor

vercel bot commented Mar 12, 2026

@mlhynfield is attempting to deploy a commit to the Gabriel Duarte's projects Team on Vercel.

A member of the Team first needs to authorize it.

@mlhynfield mlhynfield marked this pull request as ready for review March 12, 2026 18:32
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.env.example:
- Around line 22-28: The BLOCKY_AUTH_HEADER example for an API key is
misleading; update the .env.example so the API key example is either removed or
clearly labeled as setting the Authorization header value directly (i.e., make
it explicit that BLOCKY_AUTH_HEADER sets the Authorization header), and if you
want to show a more common pattern also add a separate example or note
recommending a dedicated header/env var (e.g., BLOCKY_API_KEY_HEADER) for API
keys instead of using Authorization; change the example line containing
BLOCKY_AUTH_HEADER accordingly and update the surrounding comment text to
reflect the chosen approach.

In `@src/server/prometheus/client.ts`:
- Around line 33-38: Extract the duplicated header construction
(env.BLOCKY_AUTH_HEADER ? { Authorization: env.BLOCKY_AUTH_HEADER } : undefined)
into a single helper (e.g., const authHeader or function buildAuthHeader()) and
use it in both places where ky requests are made (the calls using ky.get and
ky.head around getPrometheusUrl()); replace the inline ternary with the helper
to remove duplication and keep behavior identical, referencing
env.BLOCKY_AUTH_HEADER, getPrometheusUrl, and the ky calls.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 10abaef0-2a3e-4db5-9b68-07e9afd68bc9

📥 Commits

Reviewing files that changed from the base of the PR and between 5156fde and 1633d06.

📒 Files selected for processing (7)
  • .changeset/polite-eyes-search.md
  • .env.example
  • AGENTS.md
  • README.md
  • src/env.js
  • src/server/api/routers/blocky.ts
  • src/server/prometheus/client.ts
📜 Review details
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx,js,jsx,css,json}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx,css,json}: Use 2-space indentation throughout the codebase
Use LF (Unix) line endings instead of CRLF

Files:

  • src/env.js
  • src/server/prometheus/client.ts
  • src/server/api/routers/blocky.ts
src/env.js

📄 CodeRabbit inference engine (AGENTS.md)

Environment variables are validated via @t3-oss/env-nextjs in src/env.js

Files:

  • src/env.js
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use strict TypeScript mode with noUncheckedIndexedAccess enabled
Use inline type imports in TypeScript: import { type Foo } from "bar"
Prefix unused parameters with underscore: (_unused) => {}
Never use any; prefer unknown when type is truly unknown
Do not use non-null assertions (!) or type casting to bypass errors
Use the ~/ path alias for all src imports: import { cn } from "~/lib/utils"
Never import directly from clsx; use cn from ~/lib/utils (enforced by ESLint)
Types and interfaces should use PascalCase naming (e.g., LogEntry, FilterValue)
Constants should use UPPER_SNAKE_CASE naming for arrays and enums (e.g., TIME_RANGES)
Use cn() from ~/lib/utils for conditional class merging with Tailwind
Use try/catch for async operations that may fail
Use toast from sonner for user notifications (toast.success(), toast.error())
Always use where clause with Drizzle delete and update operations (enforced by ESLint)
Don't use raw Drizzle queries unless absolutely necessary; prefer using ORM functions
Report unused ESLint disable directives in the codebase

Files:

  • src/server/prometheus/client.ts
  • src/server/api/routers/blocky.ts
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Tailwind CSS classes exclusively (v4, CSS-based config in globals.css)

Files:

  • src/server/prometheus/client.ts
  • src/server/api/routers/blocky.ts
src/server/api/routers/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

src/server/api/routers/**/*.{ts,tsx}: Place routers in src/server/api/routers/ directory
Use publicProcedure for tRPC endpoints
Validate tRPC inputs with Zod schemas

Files:

  • src/server/api/routers/blocky.ts
🧠 Learnings (3)
📚 Learning: 2025-12-31T17:50:59.256Z
Learnt from: GabeDuarteM
Repo: GabeDuarteM/blocky-ui PR: 200
File: .changeset/rich-meteors-divide.md:5-5
Timestamp: 2025-12-31T17:50:59.256Z
Learning: In all changeset files (e.g., .changeset/*.md), do not use H1 or H2 headings for section titles. Use headings at level 4 or lower (#### and below) for section titles, since the generated changelogs assume a ### top-level heading and using H1/H2 can conflict with the structure.

Applied to files:

  • .changeset/polite-eyes-search.md
📚 Learning: 2026-02-15T18:42:23.821Z
Learnt from: CR
Repo: GabeDuarteM/blocky-ui PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-15T18:42:23.821Z
Learning: Applies to src/env.js : Environment variables are validated via `t3-oss/env-nextjs` in `src/env.js`

Applied to files:

  • AGENTS.md
📚 Learning: 2026-02-15T18:42:23.821Z
Learnt from: CR
Repo: GabeDuarteM/blocky-ui PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-15T18:42:23.821Z
Learning: Never commit secrets; use `.env` file for local development environment variables

Applied to files:

  • AGENTS.md
🪛 LanguageTool
README.md

[style] ~115-~115: To form a complete sentence, be sure to include a subject.
Context: ... | Enable query logging. Can be mysql, postgresql, timescale, ...

(MISSING_IT_THERE)

🔇 Additional comments (8)
.changeset/polite-eyes-search.md (1)

1-5: LGTM!

The changeset correctly declares a minor version bump for the new feature and follows the proper format without using problematic heading levels.

AGENTS.md (1)

150-150: LGTM!

Documentation accurately describes the new environment variable and its purpose, consistent with the implementation in src/env.js.

README.md (2)

43-44: LGTM!

The docker-compose example appropriately shows the authentication header as a commented option with a clear placeholder value.


111-119: LGTM!

The configuration table accurately documents the new BLOCKY_AUTH_HEADER variable with helpful examples showing different authentication schemes (Bearer token, Basic auth).

src/env.js (2)

17-17: LGTM!

The schema correctly defines BLOCKY_AUTH_HEADER as an optional string, allowing flexible authentication header formats (Bearer, Basic, API keys, etc.).


44-44: LGTM!

The runtime environment mapping correctly sources the value from process.env.BLOCKY_AUTH_HEADER.

src/server/api/routers/blocky.ts (1)

28-34: LGTM!

The conditional spread pattern for adding the Authorization header is clean and idiomatic. Setting headers at the ky.create() level ensures all API requests consistently include authentication when configured.

src/server/prometheus/client.ts (1)

17-24: LGTM!

The conditional Authorization header is correctly applied to Prometheus metrics fetching. The implementation properly handles the optional auth header.

Comment on lines +33 to +38
await ky.head(getPrometheusUrl(), {
timeout: 5000,
headers: env.BLOCKY_AUTH_HEADER
? { Authorization: env.BLOCKY_AUTH_HEADER }
: undefined,
});
Copy link

@coderabbitai coderabbitai bot Mar 12, 2026

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Consider extracting the header construction to reduce duplication.

The same header construction logic appears twice in this file (lines 20-22 and 35-37). While the current implementation is correct, you could extract this to a helper constant or function for consistency.

♻️ Optional refactor
+function getAuthHeaders(): { Authorization: string } | undefined {
+  return env.BLOCKY_AUTH_HEADER
+    ? { Authorization: env.BLOCKY_AUTH_HEADER }
+    : undefined;
+}
+
 export async function fetchPrometheusMetrics(): Promise<ParsedMetrics | null> {
   try {
     const text = await ky
       .get(getPrometheusUrl(), {
         timeout: 10000,
-        headers: env.BLOCKY_AUTH_HEADER
-          ? { Authorization: env.BLOCKY_AUTH_HEADER }
-          : undefined,
+        headers: getAuthHeaders(),
       })
       .text();
     return parsePrometheusText(text);
   } catch {
     return null;
   }
 }

 export async function checkPrometheusAvailable(): Promise<boolean> {
   try {
     await ky.head(getPrometheusUrl(), {
       timeout: 5000,
-      headers: env.BLOCKY_AUTH_HEADER
-        ? { Authorization: env.BLOCKY_AUTH_HEADER }
-        : undefined,
+      headers: getAuthHeaders(),
     });
     return true;
   } catch {
     return false;
   }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/server/prometheus/client.ts` around lines 33 - 38, Extract the duplicated
header construction (env.BLOCKY_AUTH_HEADER ? { Authorization:
env.BLOCKY_AUTH_HEADER } : undefined) into a single helper (e.g., const
authHeader or function buildAuthHeader()) and use it in both places where ky
requests are made (the calls using ky.get and ky.head around
getPrometheusUrl()); replace the inline ternary with the helper to remove
duplication and keep behavior identical, referencing env.BLOCKY_AUTH_HEADER,
getPrometheusUrl, and the ky calls.

Copy link
Author

Choose a reason for hiding this comment

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

I'll leave this up to the human reviewer; if desired I'd be happy to extract it out.

Copy link

Choose a reason for hiding this comment

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

@mlhynfield Sounds good! The suggestion is purely optional and the current implementation is correct as-is. I'll leave it for the human reviewer to decide. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant