11const path = require ( 'path' ) ;
2+ const fs = require ( 'fs' ) ; // Import the file system module
23const express = require ( 'express' ) ;
34const javascriptStringify = require ( 'javascript-stringify' ) . stringify ;
45const qs = require ( 'qs' ) ;
5- const rateLimit = require ( 'express-rate-limit' ) ;
66const text2png = require ( 'text2png' ) ;
77
88const packageJson = require ( './package.json' ) ;
@@ -184,11 +184,35 @@ app.use(authAndRateLimit);
184184// Serve static files from the 'public' directory (now protected)
185185app . use ( express . static ( path . join ( __dirname , 'public' ) ) ) ;
186186
187- // Route for the interactive QR code page (now protected)
187+ // MODIFIED Route for the interactive QR code page
188188app . get ( '/qr-code-api' , ( req , res ) => {
189- res . sendFile ( path . join ( __dirname , 'public/qr-code-api.html' ) ) ;
189+ const filePath = path . join ( __dirname , 'public/qr-code-api.html' ) ;
190+ fs . readFile ( filePath , 'utf8' , ( err , data ) => {
191+ if ( err ) {
192+ logger . error ( 'Could not read qr-code-api.html' , err ) ;
193+ return res . status ( 500 ) . send ( 'Error loading page.' ) ;
194+ }
195+
196+ // Find the key from the request (header or query). Will be empty for anonymous.
197+ let apiKey = '' ;
198+ const authHeader = req . headers . authorization ;
199+ if ( authHeader && authHeader . startsWith ( 'Bearer ' ) ) {
200+ apiKey = authHeader . substring ( 7 , authHeader . length ) ;
201+ } else if ( req . query . key ) {
202+ apiKey = req . query . key ;
203+ }
204+
205+ // Inject the key (or an empty string) into a placeholder in the HTML
206+ const modifiedHtml = data . replace (
207+ "const apiKey = ''" , // Placeholder in the HTML
208+ `const apiKey = '${ apiKey } '` // Injected key
209+ ) ;
210+
211+ res . send ( modifiedHtml ) ;
212+ } ) ;
190213} ) ;
191214
215+
192216// All API routes are now implicitly protected by the app.use(authAndRateLimit) above
193217app . get ( '/chart' , ( req , res ) => {
194218 if ( req . query . cht ) {
@@ -284,8 +308,6 @@ app.get('/qr', (req, res) => {
284308app . get ( '/gchart' , handleGChart ) ;
285309
286310
287- // --- Unchanged Code from original file continues below ---
288-
289311function utf8ToAscii ( str ) {
290312 const enc = new TextEncoder ( ) ;
291313 const u8s = enc . encode ( str ) ;
@@ -305,7 +327,7 @@ function failPng(res, msg, statusCode = 500) {
305327 'X-quickchart-error' : sanitizeErrorHeader ( msg ) ,
306328 } ) ;
307329 res . end (
308- text2png ( `Chart Error: ${ msg } ` , {
330+ text2png ( `Error: ${ msg } ` , {
309331 padding : 10 ,
310332 backgroundColor : '#fff' ,
311333 } ) ,
0 commit comments