└── index.js /index.js: -------------------------------------------------------------------------------- 1 | const users = { 2 | "admin": "password", 3 | "user1": "password1", 4 | "user2": "password2", 5 | // Add more users as needed 6 | }; 7 | 8 | const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/; 9 | const USER_PASS_REGEXP = /^([^:]*):(.*)$/; 10 | 11 | const parseAuthHeader = (string) => { 12 | if (typeof string !== 'string') { 13 | return undefined; 14 | } 15 | 16 | const match = CREDENTIALS_REGEXP.exec(string); 17 | if (!match) return undefined; 18 | 19 | const userPass = USER_PASS_REGEXP.exec(atob(match[1])); 20 | if (!userPass) return undefined; 21 | 22 | return { name: userPass[1], pass: userPass[2] }; 23 | }; 24 | 25 | const unauthorizedResponse = (body) => new Response( 26 | body, { 27 | status: 401, 28 | headers: { 29 | "WWW-Authenticate": 'Basic realm="User Visible Realm"' 30 | } 31 | } 32 | ); 33 | 34 | async function handle(request) { 35 | const credentials = parseAuthHeader(request.headers.get("Authorization")); 36 | 37 | if (!credentials || users[credentials.name] !== credentials.pass) { 38 | return unauthorizedResponse("Unauthorized"); 39 | } 40 | 41 | return fetch(request); 42 | } 43 | 44 | addEventListener('fetch', event => { 45 | event.respondWith(handle(event.request)); 46 | }); 47 | --------------------------------------------------------------------------------