Demo
Type Cmd+K or Ctrl+K on any page to open a demo terminal with preloaded lambda functions.
If you cannot find those keys on your keyboard you can click this button:
Preloaded functions
See below for some lambda functions that was pre-loaded for you.
hello
const { 0: name = 'human' } = ctx.args.all();
console.log(`Hello, ${name}!`);
For details on args see ctx args section.
vi-nav
Run vi-nav on. Use h/l for previous/next badge and j/k to scroll down/up. Run vi-nav off to stop.
// Click outside the terminal to use h/j/k/l.
const { 0: mode } = ctx.args.all();
window.viNav?.abort();
if (mode === 'off') {
console.log('vi-nav off');
return;
}
window.viNav = new AbortController();
document.addEventListener('keydown', (event) => {
if (event.ctrlKey || event.metaKey || event.target.closest('input, textarea')) return;
if (!['h', 'j', 'k', 'l'].includes(event.key)) return;
event.preventDefault();
if (event.key === 'h' || event.key === 'l') {
const badges = [...document.querySelectorAll('.docs-categories a')];
const current = badges.findIndex(badge => badge.hasAttribute('aria-current'));
const next = current + (event.key === 'h' ? -1 : 1);
badges[next]?.click();
} else {
window.scrollBy({ top: event.key === 'j' ? 120 : -120, behavior: 'instant' });
}
}, { signal: window.viNav.signal });
console.log('vi-nav on (psst.. go out of terminal)');
Hack your browsing
With Browser Lambdas, your browsing experience is hackable in the best way possible: write lambda functions and execute them on the web to give yourself new tools, capabilities, and shortcuts.
It started as just functions but now also includes a mod’able shell, persistant key-value storage, secrets and URL based trigger automations.
Use it to work faster, reduce mental load, avoid clicks or just have fun. Track your stuff in git and sync with the extension via the CLI tool baah.
How It Works
The intended flow is simple:
- Write a lambda function on your machine and track it with git.
- Sync it to the extension via
baah push. - Go to a page.
- Execute the function.
The extension keeps a copy of your function and injects it together with a small runtime
into a JavaScript context associated with the target page. The runtime exposes APIs for
key-value storage, secrets, and more through the async ctx object. These APIs
establish secure channels between the extension background worker and the runtime.
Your function runs instantly and disappears when it’s done. It can manipulate the page DOM, open tabs, act on inputs, and more. Basically you are Neo now.
Hello world
Quickstart introduction guide to the baah cli tool and running your first lambda function.
- Install the Browser Lambdas extension from the Chrome Web Store.
- Install
baahwith:npm install -g baah - Open the extension workspace in your browser and create a connection token at Settings→Connection token→Create new.
- Run
baah set chromeand provide the token. - Scaffold the hello-world example with:
baah init hello-world - Sync it with the extension:
baah push chrome - Open the workspace and approve the push.
- Go to a page.
- Open the shell with
Cmd+K(orCtrl+K) and runhello-world.
$ baah set chrome
Token (hidden):
✔ Added connection 'chrome'.
✔ Created baah.toml
✔ Created functions/hello-world.js
✔ Project initialized at hello-world
Next:
cd 'hello-world'
baah push chrome
▶ Loading functions...
✔ Function loading complete
▶ Connecting to client...
✔ Client authenticated on ws://127.0.0.1:4455
✔ Push complete
Whats next?
Looks like you are ready to roam on your own.
Browser Lambdas is a powerful tool and it ships with some awesome capabilities not covered in this tutorial. It’s recommended to keep exploring on your own:
- baah CLI tool
- the
ctxAPI (KV storage, secrets, tabs and more)
(or just throw the llms.txt at an agent and ask for shit):
llms.txt
Loading llms.txt…
Overview
The functions you write are just plain JavaScript functions. To spice things up you can use the ctx API to:
- Use key-value storage (KV) to read/write persisted values between function calls
- Read-only access secrets at runtime to make API requests
- Parse rich arguments to your functions (positional, flags etc)
- Run other lambda functions
- Manipulate tabs
- Interact with page-defined JavaScript from user world
The surface of the ctx object looks like this:
| Feature | API Examples | Purpose |
|---|---|---|
| Arguments | ctx.args.all() | Read command‑line flags passed to a lambda |
| Storage | ctx.kv.get(), ctx.kv.set() | Persist values between lambdas |
| Secrets | ctx.secrets.get() | Access configured secrets |
| Main | ctx.main.get(), ctx.main.call(), ctx.main.run() | Read page globals and run page operations |
| Run | ctx.run("foo bar"), ctx.tabs.this().run() | Execute another lambda on the current page |
| Chain | ctx.run() | Pass return values between lambdas |
| Tabs | ctx.tabs.new(), ctx.tabs.all(), ctx.tabs.new().run(), tab.focus(), tab.close() | Open, list and control browser tabs |
| Network | tab.network.add(), tab.network.list(), tab.network.clear(), rule.remove() | Redirect, block and change headers |
Args
ctx.args.all()
Returns an object with all command‑line arguments.
Positional arguments
my-lambda cats dogs
const { 0: first, 1: second } = ctx.args.all();
console.log(first, second);
Long flags
my-lambda --title "Hello" --count=5 --dry-run
const { title, count, dryRun } = ctx.args.all();
console.log(title, count, dryRun);
Short flags and aliases
my-lambda -u alice -p hunter2
const { username, password } = ctx.args.all({ u: 'username', p: 'password' });
console.log(username); // "alice"
console.log(password); // "hunter2"
kv
Key-value map stored persistently in browser extension storage. Values are stored as JSON, so you can save plain strings or complex objects without stringifying.
ctx.kv.get(key)
Fetches a value when the item allows the current page and execution world.
const value = await ctx.kv.get("my-key");
console.log(value);
Missing or denied keys return null with a shell warning. A stored null also returns null, without a warning.
ctx.kv.set(key, value)
Stores a JSON-compatible value and returns true when allowed, or false with a warning when blocked.
await ctx.kv.set("my-key", "hello");
You can store objects too:
const snippet = { url: location.href, text: window.getSelection().toString() };
await ctx.kv.set("last-snippet", snippet);
// later on another page
const saved = await ctx.kv.get("last-snippet");
console.log(saved.text);
Secrets
ctx.secrets.get(key)
Read-only access to a secret added via the extension workspace.
const token = await ctx.secrets.get("API_KEY");
const res = await fetch("https://api.example.com", {
headers: { Authorization: `Bearer ${token}` }
});
console.log(await res.json());
Main
Interact with page-defined JavaScript while keeping your lambda in user world.
MAIN access is blocked by default. Enable it on the extension page; global, project and function permissions must allow it for every calling function.
ctx.main.get(path)
Reads a window-relative dot path and returns its value.
const theme = await ctx.main.get("app.theme");
console.log(theme);
ctx.main.call(path, ...args)
Calls a page function with the supplied arguments and returns its result. Methods keep their normal this value.
await ctx.main.call("app.router.navigate", "/inbox");
ctx.main.run(callback, arg?)
Runs a callback in MAIN with one optional plain-data argument. The callback has no ctx or captured variables; pass values through arg.
const limit = 5;
const ids = await ctx.main.run(
({ limit }) => window.app.items.slice(0, limit).map(item => item.id),
{ limit }
);
console.log(ids);
Arguments and results cross as plain data. DOM nodes, functions and cyclic objects are rejected.
Run
ctx.run(cmd)
Runs another lambda on the current page. Provide the full command exactly as you would type it in the shell.
await ctx.run("other-lambda arg1 arg2");
Chain
Return a value from one lambda and pass it to the next through command arguments.
$ tree functions
functions
├── count-links.js
├── show-count.js
└── chain.js
$ cat functions/count-links.js
return document.querySelectorAll('a').length;
$ cat functions/show-count.js
const { count } = ctx.args.all();
console.log(count);
$ cat functions/chain.js
const count = await ctx.run("count-links");
if (count !== undefined) {
await ctx.run(`show-count --count ${count}`);
}
This also works with the tab .run() command.
Return JSON-compatible values. Anything else yields undefined.
Tabs
ctx.tabs.new(url?)
Opens a new tab with the specified URL.
await ctx.tabs.new("https://example.com");
ctx.tabs.new().run(lambda, args?)
Opens a new tab and runs a lambda inside it.
await ctx.tabs.new("https://example.com").run("scrapetool --include-metatags");
ctx.tabs.new().focus()
Brings a newly opened tab into focus.
const tab = await ctx.tabs.new("https://example.com");
await tab.focus();
ctx.tabs.new().close()
Closes a newly opened tab after you're done with it.
const tab = await ctx.tabs.new();
await tab.close();
ctx.tabs.this().run(cmd)
Runs a lambda on the current tab. This is synonymous with ctx.run().
await ctx.tabs.this().run("other-lambda arg1");
ctx.tabs.all()
Returns wrappers for all open tabs.
const tabs = await ctx.tabs.all();
for (const tab of tabs) {
console.log(tab.title);
}
Network
Redirect, block or change headers in a tab. Also available on tabs from ctx.tabs.new() and ctx.tabs.all().
Enable Allow network rules in Settings, then Network rules in the project’s Functions settings. Both default to off.
Rules survive function completion and reloads; changing origin, closing the tab or restarting the browser clears them. Origin cleanup is asynchronous.
tab.network.add(rule)
Adds a rule and returns a handle.
const network = ctx.tabs.this().network;
const rule = await network.add({
match: { url: "https://example.com/api/*" },
redirect: "http://localhost:3000/api/*"
});
// /api/users?page=2 → http://localhost:3000/api/users?page=2
Use absolute HTTP(S) URLs with one optional path/query *. A destination * inserts the captured suffix, including its query; omit it for an exact destination.
Block
await network.add({
match: {
url: "https://example.com/ads/*",
methods: ["GET"],
resourceTypes: ["image"]
},
block: true
});
Headers
await network.add({
match: { url: "https://api.example.com/*" },
request: {
headers: {
set: { "X-Debug": "true" },
remove: ["X-Legacy"]
}
},
response: {
headers: {
set: { "Access-Control-Allow-Origin": "https://example.com" }
}
}
});
tab.network.list()
Lists all Browser Lambdas rules for the tab, across functions.
console.log(await network.list());
rule.remove()
Removes the returned rule. Removed or replaced handles do nothing.
await rule.remove();
tab.network.clear()
Clears all Browser Lambdas rules in the tab.
await network.clear();
Security
Browser Lambdas was built on a standpoint that security had to be prioritised in all parts of the extension. The core principle being that any user should be able to use the extensions and assume no risks up to the point that they themselves turn off the safeguards provided. The motto being "Safe by default - loosy goosy if you so choosy".
Threat Model
Some things we can protect against and others we cannot, this section draws that line. The primary threats are:
- Compromised or malicious pages
- Compromised machine
- Compromised extension
Each posing risks of
- Data breach of extension storage (secrets or data stored in kv)
- The extension being DoS'ed
And even more seriously an 'advanced' scenario being that a compromised page could lead to a compromised page or extension and vice versa. Scary stuff.
The first thing to make clear is that pre-existing vulnerabilities in your browser that malicious pages can exploit are basically game over and not a risk mitigated by the extension. The browser and its own security barriers are assumed to be intact, working and trusted.
Based on this assumption the overall security principles can be summarised as:
- Maximally isolate things with trusted browser APIs
- Encrypt data passing through trust barriers
- Require authentication to upload data from a machine into the extension
- Default to human reviews of any creation of or changes to executable lambdas or triggers
- Explicit safeguards managed by global, project or item level settings
- Turn off 'risky' features by default
- Use as few dependencies for extension code as possible
The following sections details the above in relation to the extension and the baah CLI tool.
UI Elements
The extension is a system composed of several UI surfaces that each gives users a place to provide inputs and see outputs. These are:
- The extension page
- in-page and fallback popup menus
- the terminal UI
It's not hard to why we only want the user to be able to control these and as such they must be isolated as much as possible. The extension page and popup menus are both isolated by the browser’s extension-origin boundary and same-origin policy and thus pose little risk.
Extension origin elements are unreachable by any page
The terminal UI and in-page menu should by-design somehow live on the page of which they are invoked and thus must be isolated from that page’s JavaScript context so it cannot read their element or interact with them. This is solved by embedding both in an extension controlled iframe. Here the browser provides the security guarantee that they cannot be tampered with by the page they work on.
iframes are unreachable to page JavaScript
Function injection
Browser Lambdas are all about executing functions on pages and it's important users can do so safely. Users write functions and when they are invoked either in the terminal or by a trigger they are injected into a JavaScript context together with a runtime where they are executed.
User world
The user can target a specific JavaScript context and this user choice has great implication for the level of risk. The default behavior is to inject into an isolated extension context called "user world". This isolation barrier provides good security because the page’s JS and the lambda function run in two different context. The only thing shared is the target page DOM. This mean the user can trust that their lambda functions and ctx calls are not tampered with and safe.
Native runtime connection
Main world
The user can also choose to inject their functions into the page’s own JavaScript context. This poses a much greater risk as malicious pages easily can manipulate the entire JS context around the lambda functions and runtime and as such gain full control of requests to ctx and thereby data stored in via ctx.kv and ctx.secrets or for that matter inspect or alter the lambda’s network requests and send sensitive data to an attacker-controlled server. The only meaningful protection that can be provided is on well-behaving pages where we can use IIFE isolation and encrypted channels to provide some level of isolation and privacy.
Global safeguards block main-world execution by default. The user must explicitly enable it, and project settings and function permissions may restrict it further. Separate safeguards block access to secrets and kv-storage from the main world until explicitly enabled. Triggers follow the invoked function’s execution-world permissions. These controls are available on the extension page.
Encrypted MAIN bridge
Main helper
The only benefit running functions in the main world is access to the page JavaScript context. To provide a safer alternative it's recommended that users use the ctx.main API executed in the user world. This provides methods to safely interact with page JavaScript using an injected helper runtime that does not itself expose the ctx API.
Page operation through the worker
Trigger automations
Trigger automations run functions automatically on pages matching configured URL patterns. This opens up for a few risks:
- a trigger could run on an unintended page
- a trigger could run an unintended function or arguments
- a trigger could be executed in an unintended execution world
- Some combination of all of the above
The trigger definitions are stored in extension storage and are as such isolated and out of reach from malicious pages. The engine matching page URLs with each trigger pattern also runs in isolation. This leaves two vulnerable pathways left: simple human mistake or worse a compromised machine updating the triggers via baah CLI tool. To understand the safeguard put in place around the baah CLI tools please read next section.
Baah
The baah CLI tool lets users keep their lambda functions, triggers and terminal styles in git and sync them with the extension running in their browser(s). This bridge creates an additional surface for attacks where a compromised machine or extension could try to make moves across it. Further since lambda functions, triggers or styles can be shared with third parties via git this bridge also exposes the extension to a supply-chain attack risk.
There are 3 strategies for dealing with these issues:
- Pushing data to the extension requires pre-authentication with an extension generated token. This prevents pushing data to an extension instance that is not configured by the user.
- Data is encrypted in transit and is protected against MITM attacks
- Final human review and approval of changed functions, triggers or styles before they can be “unlocked” to prevent injecting malicious functions or triggers without the user knowing.
The required review of updates can be turned off globally or on a project-level setting, but is not recommended.
Local synchronization and review
baah
Functions, triggers and styles should all be tracked in git on your machine. To sync them and run with the extension you need to use the CLI tool baah.
In short it:
- A
baah.tomlfile is used to decide what files get synced. baah pushstarts a server waiting for connected browsers.- When the extension workspace is open it polls the changes.
- You approve the diff.
- Ready to go.
Connections
The baah CLI tool revolves around two resources: connections, which are individual authenticated connections to browsers on your machine, and baah.toml files with instructions for syncing a project through those established connections.
npm install -g baah
Commands
$ baah --help
Usage:
baah init [path] Set up a project and browser connection
[--template minimal|starter] [--skills|--no-skills] [--skip-connection]
baah set <name> [--token TOKEN] [--port PORT]
Save a named connection to your browser extension
baah ls List saved connections
baah info <name> Show saved connection details
baah rm <name> Remove a saved connection
baah push <name> Push using a saved connection
baah init .
Use baah init to scaffold a project. If zero connections are found it will ask to create one (optional).
$ baah init my-lambdas
Choose a template:
1. Minimal — baah.toml only
2. Starter — baah.toml, functions/hello-world.js
Template [1]: 1
Include agent skills in .agents/skills/? [y/N]: n
No browser connections yet
Set up a new browser connection?
- yes
- no
Choose [Y/n]: y
Name new connection (e.g. chrome, work): chrome
Open extension → Settings → Connection token → create a new token or reuse the existing one. Click to copy the token and paste it below (input is hidden).
token:
Use default port for updates (4455)?
- yes (recommended)
- no
Choose [Y/n]: y
✔ Added connection 'chrome'.
✔ Created baah.toml
✔ Project initialized at /path/to/my-lambdas
Next:
cd '/path/to/my-lambdas'
Add your lambdas under functions/.
baah push chrome
baah set
Single command to create or update connections. If you change the default port remember to also change it in the connected browser.
$ baah set chrome
Token (hidden): <entered token is hidden>
✔ Added connection 'chrome'.
$ baah set chrome --token TOKEN --port 4455
✔ Updated connection 'chrome'.
$ baah set chrome --port 3333
✔ Updated connection 'chrome'.
baah push
Starts a server that waits for the workspace to connect. Then it syncs your project with the extension’s storage according to your baah.toml file.
$ baah push chrome
▶ Loading functions...
✔ Function loading complete
▶ Connecting to client...
✔ Client authenticated on ws://127.0.0.1:4455
✔ Push complete
baah ls
List all connections.
$ baah ls
• chrome
• safari
baah info
Show info on each connection.
$ baah info chrome
Push listener: ws://127.0.0.1:4455
baah rm
Remove a single connection.
$ baah rm chrome
Removed connection 'chrome'.
baah.toml
Use the include and exclude globs to select what files are pushed and synced with your browser.
[project]
name = "my-project"
[functions]
include = ["functions/**/*.js"]
exclude = ["functions/**/*.test.js", "functions/**/__*__/*"]
[styles]
include = ["styles/**/*.css"]
[triggers]
include = ["triggers/**/*.yaml"]