Using Codex and Playwright When There Is No API

Everybody likes an API. It is the clean version of an integration: documented endpoints, structured responses, credentials meant for software, and hopefully somebody else’s problem when the implementation changes.

But plenty of useful systems do not have one. Or they have an API that covers part of the product but not the screen a team actually needs. The data is there, behind a normal login, and somebody is opening a browser and copying it into a spreadsheet.

That is a good place for browser automation.

We have been looking at a practical combination of Playwright and Codex for this kind of work. Playwright drives a real Chrome browser. Codex can work with a browser exposed over the Chrome DevTools Protocol (CDP), which makes it useful for exploring an application and helping build the automation. The important piece is that the login stays human: someone who is authorized to use the site signs in and completes MFA themselves. The automated job uses the resulting browser session; it does not try to get around the login.

A concrete example is recording live odds from sportsbooks such as FanDuel or BetMGM. If an organization is allowed to collect and use the data, that is a much better job for a computer than for someone watching pages and updating a sheet all day.

The browser is sometimes the integration

This is not an argument to scrape everything. If there is an official API that does the job, use it. It is almost always less fragile and easier to support.

But sometimes the browser is the only interface available to the user. A person can log in, look at a live market, and see the numbers, but there is no supported endpoint for getting the same information into an internal system. In that situation, the browser can be the boundary between the site and your workflow.

There are obvious limits. The account needs to be authorized, and the intended use needs to comply with the site’s terms, contracts, and applicable law. That matters especially for sportsbooks, where access and permitted use can vary by operator and jurisdiction. This is not a way to bypass MFA, CAPTCHAs, rate limits, or other controls.

Getting a logged-in browser session

Playwright is a browser automation framework. It can launch Chromium or Chrome, navigate pages, click buttons, fill forms, and read what the page renders.

The feature that makes authenticated automation workable is a persistent browser profile. Instead of starting fresh every time, Playwright launches Chrome with the same profile directory. That lets it retain browser state such as cookies and sessions when the site permits it.

The first run is simple: launch a visible browser, log in normally, handle the two-factor prompt, and make sure the page you need is available. After that, the job can reopen that same profile. It can run visibly while somebody is building or debugging it, then run headlessly when it is ready to collect data on a schedule.

import { chromium } from "playwright";

const userDataDir = "/secure/path/to/browser-profile";
const context = await chromium.launchPersistentContext(userDataDir, {
  channel: "chrome",
  headless: false, // first run: let the account owner log in
});

const page = await context.newPage();
await page.goto("https://example.com/login");

// The authorized user completes sign-in and MFA in this browser window.

That profile directory is sensitive. It may contain an active session, so treat it like a credential: keep it in approved storage, restrict who can access it, and do not put it in source control or logs. Also plan for it to expire. The site decides how long a session lasts. If the job finds a login page again, it should stop and let a person reauthenticate.

Asking Codex to do the tedious part

The page is usually the part that makes these projects annoying. Modern web applications load data after the page appears, change the DOM as markets update, and use selectors that are not obvious until you can inspect the live application.

This is where Codex helps. With the authenticated browser connected over CDP, you can ask it to inspect the page, find the market and selection elements, and build the Playwright script around what is actually there. It is much faster than guessing at selectors from a screenshot or trying to reverse engineer an undocumented backend.

A reasonable first prompt is something like:

Set up Playwright with a persistent Chrome profile and launch it visibly so I can log in. Once I have an authenticated session, use that session to inspect the live odds page and build a script that records the event, market, selection, displayed odds, and collection time.

Codex is helping with the implementation; it is not replacing the account holder. Keep that line clear. It should not be asked to find credentials, solve MFA, or work around controls the site has put in place.

A live-odds collector

Say the job is to keep an internal, timestamped record of odds for a set of games and markets.

First decide what an observation is. At a minimum, it will probably include the sportsbook, event, market, selection, displayed odds, the source page, and the time the value was seen. That last field matters: a number collected at 2:00 PM is not the same thing as a number collected five minutes later.

Next, use the visible browser session to get to the right market and let Codex inspect the rendered page. The job needs to know when the market is actually loaded, how a suspended or unavailable price is represented, and which labels or attributes are stable enough to use as selectors. Prefer user-facing labels where possible over a long chain of generated CSS classes that will disappear in the next redesign.

Once that is understood, the collector can launch the same persistent profile in headless mode, visit only the pages it needs, validate what it finds, and write normalized records to a database or queue.

const context = await chromium.launchPersistentContext(userDataDir, {
  channel: "chrome",
  headless: true,
});
const page = await context.newPage();

await page.goto(targetMarketUrl, { waitUntil: "domcontentloaded" });
await page.getByRole("heading", { name: /live odds/i }).waitFor();

const collectedAt = new Date().toISOString();
const observations = await page.locator("[data-market]").evaluateAll((markets) =>
  markets.map((market) => ({
    market: market.getAttribute("data-market"),
    text: market.textContent?.trim(),
    collectedAt,
  }))
);

The code above is deliberately generic. The real selectors should come from the target site and should be tested against its actual states. The useful outcome is not just a script that reads a page once. It is a small internal data source that dashboards, reports, or models can rely on without each one having to understand the sportsbook’s UI.

The unglamorous stuff is what makes it work

A browser job will change when the website changes. That is normal. The difference between a useful integration and a fragile script is how it behaves on a bad day.

Keep the browser profile locked down. Save where each observation came from and when it was collected. Alert when the job suddenly gets no results, sees a login screen, or returns far fewer records than normal. And give somebody a straightforward way to rerun the visible browser and refresh the session.

That is enough to turn a manual task into something dependable without pretending the website is an API.

For companies sitting on useful data behind logins, this is a practical option: a person handles the authorization once, Playwright keeps the browser state, and Codex speeds up the work of turning what is on the screen into structured data.

AI-Powered Chrome Extensions for the Web Apps You Can't Replace

There has been a lot of discussion recently about companies using AI to build internal tools that replace SaaS licenses. That is interesting, but it misses a big category of software: the web apps you cannot replace.

Sometimes the constraint is technical. More often, it is not. An insurance company may require you to use its verification portal. A specialty vendor may only accept orders through a clunky ecommerce site. Or a marketplace may be where all of the demand for your product or service lives.

You can build a better internal tool, but you still have to use those sites.

The browser is the integration point

Chrome extensions have always been a way to change the experience of a site you do not control. An extension can read information from a page, add controls to it, and help guide a user through a workflow.

Historically, that was possible but often not practical. You needed to write and maintain custom code for every awkward workflow, and the payoff had to be large enough to justify it.

The latest AI models change that calculation. It is now much easier to build an extension that augments a legacy site, whether that means changing a workflow, extracting information from a page, or adding LLM capabilities directly where people are already working.

Instead of asking someone to copy information from one system into another, you can put the assistance in the browser tab where the work already happens.

A bike search on Facebook Marketplace

I recently had a good excuse to try this out. I was looking for a bike on Facebook Marketplace with a specific set of requirements. The hard part was not finding listings. It was reviewing the photos for each listing to determine whether a bike was actually a fit.

Doing that manually meant opening and reviewing dozens of listings every day. That is exactly the sort of repetitive visual task that an AI model can help with.

So I built a Chrome extension that uses OpenAI to review listing photos and flag the listings that match what I was looking for. Rather than replacing Facebook Marketplace, the extension improves the part of the Marketplace workflow that was taking the most time.

The result is not a fully autonomous bike buyer. It is a faster way to narrow down a large list of listings so I can spend my time looking at the promising ones.

Where this approach works

The Marketplace example is personal, but the pattern applies to business workflows too. Look for web-based processes where a person repeatedly has to review, classify, summarize, or move information before they can make a decision.

A Chrome extension can be a practical place to add help to:

  • an insurer’s required portal
  • a vendor ordering site
  • a marketplace your team depends on
  • an internal legacy application that is difficult to change

The goal is not necessarily to replace the site. It is to remove the tedious steps around it while keeping people in the workflow they already need to use.

See it in action

Check out the demo below to see the bike finder at work:

Watch the video on YouTube

Interested in building something similar for a workflow your team cannot avoid? Get in touch with Setfive.

web3: Creating a NFT contract

Wow...it's been awhile!

A couple of weeks ago one of our clients approached us about helping them build an NFT (more on that later). In case you're not "extremely online" and don't know what web3 or NFTs are here's a quick primer.

Crypto and NFTs

As crypto currencies go Bitcoin and Ethereum are the "OG" coins. They're related projects but ultimately quite different. Ethereum differentiates itself because it enables the Ethereum Virtual Machine which is a global, distributed computing environment which uses Ethereum as payment for executing computation. Executing pieces of code, known as smart contracts, on the EVM is broadly referred to as "web3". The web3 vision is that it should be possible to transition dozens of financial businesses processes onto the blockchain by using the EVM and smart contracts to encode the rules of the processes. Think stuff like insurance, stock issuance, and even sports books.

Non-fungible tokens (NFTs) are a specific type of smart contract which encode ownership of an asset onto the Ethereum blockchain. What makes NFTs special is that because of the decentralized nature of the blockchain and the EVM its possible to freely trade NFTs and encode rules into their smart contracts. OpenSea is the defacto NFT marketplace where users can trade tokens without the original creators having to create any additional infrastructure. It's like StubHub...but anyone can sell any NFT on it and anyone can access it.

In addition, because the EVM is Turing complete its possible to enable extremely complex behaviors within the contract of an NFT. In theory, a NFT could represent ownership of any items from tickets to an event or digital collectables. But as it turns out, digital collectibles is where most of the action is today. See for example Bored Ape Yacht Club which has seen some tokens trade for upwards of $24m, Set of "Bored Ape" NFTs sells for $24.4 mln in Sotheby's online auction

OK, now that we're all caught up how does one create an NFT? There's more or less 3 steps:

  1. Develop a smart contract in Solidity which implements the EIP-721: Non-Fungible Token Standard
  2. Write some HTML/JS to interact with web3 via MetaMask to call your contract
  3. Publish the contract to the Ethereum blockchain
  4. Mint your tokens via the HTML/JS from step 2

Sounds simple enough, but how do you actually make it happen?

Here's a walk through to launch a NFT in your local test environment.

You can develop the Solidity code in any text editor. But there are some IDE options including an IntelliJ plugin and a larger list here, https://ethereum.org/en/developers/docs/ides/ It's certainly possible to write a EIP721 Solidity contract from scratch but you'll end up writing a lot of boilerplate code which will increase the surface area for bugs. A sensible alternative is to use the OpenZeppelin framework which provides you with a suite of battle tested, open source libraries to bootstrap your smart contract. Additionally, OpenZeppelin has a handful of working tutorials so that you can see a smart contract working end to end. Check out OpenSea Creatures.

After you have your contract the next piece is interacting with the blockchain to publish your contract. There's a few tools here that all interact:

  1. MetaMask - MetaMask is a browser based crypto wallet and web3 provider. It allows you to store Ethereum and interact with contracts on the Ethereum blockchain. You'll use MetaMask to ultimately mint a token.
  2. Ganache - Ganache is a tool which allows you to run an Ethereum blockchain on your local machine
  3. Truffle - Truffle is a suite of tools which makes it easier to interact with the blockchain. You'll use Truffle to publish your contract and invoke methods within your contract.

Once you have all the tooling setup the steps you'll need to take are:

  1. Setup MetaMask and note the mnemonic phrase which your keys were initialized with
  2. Launch ganache with that mnemonic so that your accounts have some Ethereum
  3. Use Truffle to publish your contract to your local ganache blockchain
  4. Use the HTML/JS integration you wrote to invoke MetaMask to call the .mint() function in your contract

Congratulations, you just minted your first NFT in test!

The process for deploying a NFT live is effectively the same except that you'd need to buy some real Ethereum and you'd point Truffle at the live network when you publish your contract.

Hope this was helpful and we'll add more web3 related content as we continue to build solutions on it!

nginx: Using auth_request to secure vhosts

One of our clients recently had a unique use case. They had a Wiki site where they wanted to restrict viewing of posts to only their app’s authorized users. Picture something like a SaaS app where the Wiki site had proprietary content that our client only wanted paying users to access.

The two obvious options to implement this would be:

  • Create a Wiki user for each authorized user - this has the downside that we’d need to maintain two accounts, figure out how to keep users logged into both, and deal with synchronizing account data.
  • Modify the Wiki’s application code to authorize the users in some fashion - this is problematic because it would make upgrading the Wiki software difficult.

Turns out there’s a third option which is much smoother! Nginx has a directive called auth_request which allows nginx to authorize access to a resource based on a 2nd HTTP request.

The way it works is:

  • Your SaaS app is setup at platform.setfive.com where users are authenticated by a Symfony application.
  • You configure your Symfony application to send a cookie back with a wildcard domain of “.setfive.com”
  • Your wiki is running at wiki.setfive.com and configured to authorize requests to platform.setfive.com/is-authenticated
  • Now, when users request wiki.setfive.com their browser will send your Symfony authentication cookie, nginx will make a request to platform.setfive.com/is-authenticated, and if they’re authenticated they’ll be granted access to your wiki.

The nginx config for this is pretty straightforward as well. One thing to note is this module is not standard so on Ubuntu you do need to install the nginx-extras package to enable it.

server {
    server_name wiki.setfive.com;

    listen 443 ssl;
    ssl_certificate /etc/httpd/ssl/setfive-ssl.chained.crt;
    ssl_certificate_key /etc/httpd/ssl/setfive-ssl.key;

    ssl_session_cache shared:le_nginx_SSL:1m;
    ssl_session_timeout 1440m;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS";

    root /var/www/html/wiki;
    index index.php;

    auth_request /is-authenticated;

    location = /is-authenticated {
        internal;
        proxy_pass https://platform.setfive.com/is-authenticated;
        proxy_set_header Content-Length "";
     }

     location / {
        # This is cool because no php is touched for static content.
        # include the "?$args" part so non-default permalinks doesn't break when using query string
        try_files $uri $uri/ /index.php?$args;
     }

    location ~ \.php$ {
      fastcgi_pass   unix:/run/php-fpm/www.sock;
      fastcgi_split_path_info ^(.+\.php)(/.*)$;
      include fastcgi_params;
      fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
      # fastcgi_param  HTTPS              off;
    }

}

Spring Boot: Creating a filter to verify an API key header

Phew! Been awhile but we’re back!

NOTE: There’s a working Spring Boot application demonstrating this at https://github.com/Setfive/spring-demos

For many applications a security and authentication scheme centered around users makes sense since the focus of the application is logged in users taking some sort of action. Imagine a task tracking app, users “create tasks”, “complete tasks”, etc. For these use cases, Spring Boot’s Security system makes it easy to add application security which then provides a “User” model to the rest of the application. This allows your code to do things like “getUser()” in a Controller and have ready access to the currently authenticated user.

But what about applications that don’t have a user based model? Imagine something like an API which provides HTML to PDF conversions. There’s really no concept of “Users” but rather a need to authenticate that requests are coming from authorized partners via something like an API key. So from an application perspective you don’t really want to involve the user management system, there’s no passwords to verify, and obviously the simpler the better.

Turns out its very straightforward to accomplish this with a Spring managed Filter. Full code below:

package com.setfive.demo.apiheaderdemo.filter;
import com.setfive.demo.apiheaderdemo.entity.ApiKey;
import com.setfive.demo.apiheaderdemo.repository.ApiKeyRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

@Component
public class ApiKeyRequestFilter extends GenericFilterBean {

    private static final Logger LOG = LoggerFactory.getLogger(ApiKeyRequestFilter.class);

    private ApiKeyRepository apiKeyRepository;

    public ApiKeyRequestFilter(ApiKeyRepository apiKeyRepository){
        this.apiKeyRepository = apiKeyRepository;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String path = req.getRequestURI();

        if(path.startsWith("/api") == false){
            chain.doFilter(request, response);
            return;
        }

        String key = req.getHeader("Key") == null ? "" : req.getHeader("Key");
        LOG.info("Trying key: " + key);

        Optional<ApiKey> apiKeyOptional = this.apiKeyRepository.findOneByKey(key);
        if(apiKeyOptional.isPresent()){
            chain.doFilter(request, response);
        }else{
            HttpServletResponse resp = (HttpServletResponse) response;
            String error = "Invalid API KEY";

            resp.reset();
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentLength(error .length());
            response.getWriter().write(error);
        }

    }

}

The code is pretty straightforward but a couple of highlights are:

  • It’s a Spring Component so that you can inject the repository that you need to check the database to see if the key is valid
  • It’s setup to only activate on URLs which start with “/api” so your other routes wont need to include the Key header
  • If the key is missing or invalid it correctly returns a 401 HTTP response code

That’s about it! As always questions and comments welcome!