Files
puter/src/backend/core/context.ts
T
Juan Fernando Castro d1d55a6bc3 SDK auth plumbing: cache scope, dedupe keys and the token listener (#4112)
* fix: pin the token sender, scope the grant flag, and stop two stragglers

Five of the SDK auth-plumbing items.

**The global `puter.token` handler pinned origin but not source.** Its three
siblings all pin both, and each says why: the GUI origin is shared by every
frame on that domain, so origin alone identifies a domain, not a sender.
`signIn` pins its popup and binds `msg_id`, the consent dialog pins its popup,
and the reauth wait pins the embedder. This one pinned the embedder only when
`env === 'app'`. Since `authenticateWithPuter` now hands off to `signIn`, which
adopts the token itself, the embedder is the only sender this handler is left
serving, so it pins in every environment.

**`is_grant_user_app_permission` was a request-wide flag held across an await.**
It tells the `app-root-dir` rewriter that a row is being written, and while it
is set that rewriter resolves to a real `fs:` permission instead of
`PERMISSION_FOR_NOTHING_IN_PARTICULAR`. Anything evaluating an `app-root-dir:`
permission beside the grant -- the grant route runs one under `Promise.all`
with fs work -- read the same flag. It now lives in a scope derived for that
call, so what the write needs to say about itself is not also said to its
neighbours. `runInDerivedContext` is new: `runWithContext` starts an empty
store, which would drop the `actor` the rewriter reads.

**`fs.stat` and `fs.readdir` deduped on parameters alone**, so two identities
in one realm could share a result. They now key on origin and token as
`os/user.js` does, which documents the reason.

**`signIn`'s relay poll never stopped.** Closing the popup settles the promise;
the loop kept asking `/login/wait` every second for the life of the page.

**`triggerReauth`'s five-minute timeout was never cleared**, so a successful
reauth left a timer to fire into a settled promise.

The concurrency test parks the rewrite and reads the flag while it is held --
my first attempt read before the flag was even set and passed either way.

* fix: scope the fs cache per identity, and retarget two paths that never ran

The remaining SDK auth-plumbing items.

**`puter._cache` outlived the identity that filled it.** `_clearAuthToken`
dropped the token and the stored session but left the cache and `whoami` as
they were, and its keys were raw paths -- `item:/alice/Documents` and a
`~`-relative key alike, identical whoever asked. A GUI user switch without a
reload could be served the previous user's stat or readdir. Keys now carry the
origin and token they were read as, built in one place so the writers, the
readers, the invalidations and the warm-up probes cannot drift apart, and
signing out drops the cache and `whoami` with the token.

**The driver permission prompt could not fire.** Both paths waited for a 200
carrying `{success:false, error:{code:'permission_denied'}}`. The driver route
answers `success: true` or throws, so a refusal arrives as a 403 -- the shape
the retry now reads. Its two tests synthesised the old envelope, so they passed
against a response the API does not send; they use the real one now, and the
prompt goes from never called to called once.

This is a behaviour change: a driver call refused for permissions will now
prompt, which is what the path was written to do. Happy to delete it instead if
the prompt is not wanted.

The half-written copy of the same idea in `utils.js` is gone -- it prompted for
one hard-coded interface and its retry was a `// todo`.

**The verification-gate single-flight was keyed on nothing**, so a phone-gated
request in flight beside an email-gated one took the email answer, replayed,
failed again and surfaced raw without ever asking. Keyed per gate: same gate
still shares one dialog, a different gate gets its own.

* test: ask the cache the same way the code does

The API suites built `item:<path>` keys by hand, so they stopped finding
anything once the real keys carried the identity they were read as. They go
through `fsCacheKey` now, which is the point: a test that spells the key itself
passes until the moment the spelling changes, and then fails for a reason that
has nothing to do with the behaviour it is guarding.

These run against a live server, so a plain `vitest run` does not reach them --
they were green locally and red in CI.

* fix: the review's findings on this branch

Eight, and three of them were regressions this branch introduced.

**Pinning the token sender to `globalThis.parent` in every environment broke
the case it was meant to protect.** On a top-level page `parent` is the page
itself, and the token arrives from a popup, so the handler stopped accepting
anything. The GUI posts `puter.token` to `window.opener` for the file pickers
too, not only for sign-in, and this handler is their only consumer -- a site
calling `showOpenFilePicker()` would have signed the user in, dropped the token
and run the following read with none. It now pins the embedder when framed and
a window this SDK opened when not; `UI.js` already tracked its picker popups
for the same reason, so that set is shared rather than duplicated.

**The GUI still spelled a cache key by hand.** `updateSubdomainsForItems` built
`item:<path>`, which no longer matches what the SDK writes, so its `get` could
not hit and its `set` wrote an orphan nothing reads and nothing evicts -- a
published website's badge quietly stopped appearing on a cached render. It goes
through `fsCacheKey` now, and that is the last hand-spelled key in the tree.

**Retargeting the driver permission prompt to 403 was wrong and is reverted to
the deletion the ticket asked for.** The route refuses with `forbidden`, not
`permission_denied`, so the retarget still missed it; meanwhile a driver that
raises `permission_denied` for its own reasons would have opened a prompt that
had nothing to do with the refusal. And the prompt asks for
`driver:<iface>:<method>` while the route checks `service:<driver>:ii:<iface>`,
so granting it changes nothing. The path cannot work as written.

The rest were pre-existing or latent:

`cacheWhoami_` wrote its answer without checking the token it was issued under
was still current, so a reauth landing mid-flight could repopulate `whoami`
with the previous identity. `_dropIdentityCaches` also left `whoamiCache_`,
which other call sites await.

`setAuthToken` now drops the identity caches when the token actually changes:
keys carry the token and the store is persisted with no TTL, so a rotation that
did not go through `_clearAuthToken` orphaned a whole key space with nothing to
reclaim it.

The verification-gate entry was registered after the body could already have
deleted it -- a synchronous throw stranded a resolved "not verified" in the map
for the life of the page. It registers first and clears on a microtask.

`signIn`'s poll is bounded as well as settle-checked: on a cross-origin
isolated page opened from a gesture, nothing watches the popup, so closing it
never settled the promise and the loop ran on exactly as before.

`runInDerivedContext` says in its docblock that callee writes do not survive;
only the one flag needs the scope, and a future caller should not expect to
hand a value back through it.

* fix: the review's findings on the SDK auth plumbing

**The relay bound stopped asking without saying so.** The deadline left the
`signIn` promise pending and its listener attached. On an isolated page opened
from a gesture the relay is the only thing that can settle it -- nothing watches
the popup there -- so a user who took longer than the deadline was left with a
promise that never resolved, and `authenticateWithPuter` queues every later
implicit-auth call behind it. It rejects now.

**Pinning the token source left `signIn`'s own popup untracked.** Only the
picker popups registered, so on a top-level page the global handler bailed on a
sign-in it had opened itself: `puter.onAuth` never fired, and
`puterAuthState.authGranted` was never set. `openAuthPopup` is the one place
auth popups are opened, so they register there.

**A closed popup is ours too.** Rejecting one that had already closed loses a
message from a popup that posts and then closes itself, which is why `UI.js`
tolerates the same case. Kept, with the set bounded instead.

**The gate key carried the factors**, so one route naming them and another not
opened two dialogs for the same gate. It keys on the gate, as `ctx.done` does.

**`fsCacheKey` left `~` unresolved**, so a writer and an invalidation spelling
the same place differently missed each other -- the drift the one key builder
was meant to end.

The dead `opts.permission` went with the path that used to read it.

Four workerd-runner failures are left: `ai > chat stream adapter supports
cancellation`, `kv > a GUI boot key written by another client reads fresh` and
two cache-warmer ones. All four fail the same way on `origin/main`, and the node
and browser runners pass.

* chore: one-line the comments added here

* chore: reflow the comments the removed retry cause left ragged
2026-10-08 15:04:49 -04:00

183 lines
6.1 KiB
TypeScript

/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { AsyncLocalStorage } from 'node:async_hooks';
import type { Request } from 'express';
import type { Actor } from './actor';
/**
* Per-request context with both typed well-known fields AND an open-ended
* key-value map for ad-hoc data. Common fields (`actor`, `req`) are typed for
* autocomplete / safety, while the generic `get`/`set` bag lets any code stash
* per-request values without threading them through function arguments.
*
* Backed by Node's `AsyncLocalStorage`, so the context propagates through
* async/await, timers, and microtasks automatically. The middleware
* (`createRequestContextMiddleware`) wraps each incoming request in a fresh
* context after the auth probe has populated `req.actor`.
*
* Usage:
*
* ```ts
* // read typed field
* const actor = Context.get('actor');
*
* // read the express request from anywhere
* const req = Context.get('req');
*
* // stash / read ad-hoc values
* Context.set('myService.txId', txId);
* const txId = Context.get('myService.txId');
* ```
*/
// -- Well-known typed keys -------------------------------------------
export interface KnownContextFields {
/** The authenticated actor, if one was resolved by the auth probe. */
actor: Actor | undefined;
/** The express request object for this request. */
req: Request;
/** A unique id for this request — useful for structured logging / tracing. */
requestId: string;
/**
* The driver name the caller addressed (set by DriverController for
* `/drivers/call` dispatch); drivers read it to pick a provider.
*/
driverName: string;
/**
* Aborts when the client disconnects before the response has finished (set
* by DriverController). Long-running drivers poll it so work nobody will
* receive stops early and is never metered.
*/
abortSignal: AbortSignal;
/**
* When true, `ChatCompletionDriver.complete` treats a request-level
* upstream 4xx as final instead of falling back to another provider — set
* by the Anthropic route, which needs the vendor's own error rather than a
* different provider's translation of it.
*/
strictUpstreamErrors: boolean;
}
// -- Context store ---------------------------------------------------
interface ContextStore {
known: Partial<KnownContextFields>;
extra: Map<string, unknown>;
}
const als = new AsyncLocalStorage<ContextStore>();
// -- Public API ------------------------------------------------------
/**
* Static-style context accessor.
*
* Well-known keys (`actor`, `req`, `requestId`) return typed values. Any other
* string key hits the generic map and returns `unknown`.
*/
export class Context {
/**
* Get a value from the current request context.
*
* Well-known keys return typed values; arbitrary string keys return
* `unknown`. Returns `undefined` when called outside a request scope or
* when the key hasn't been set.
*/
/** Get the entire context store (no-arg form). */
static get(): ContextStore | undefined;
static get<K extends keyof KnownContextFields>(
key: K,
): KnownContextFields[K] | undefined;
static get(key: string): unknown;
static get(key?: string): unknown {
if (key === undefined) return als.getStore();
const store = als.getStore();
if (!store) return undefined;
if (key in store.known) {
return (store.known as Record<string, unknown>)[key];
}
return store.extra.get(key);
}
/**
* Set a value on the current request context.
*
* Well-known keys are type-checked; arbitrary keys accept `unknown`.
*/
static set<K extends keyof KnownContextFields>(
key: K,
value: KnownContextFields[K],
): void;
static set(key: string, value: unknown): void;
static set(key: string, value: unknown): void {
const store = als.getStore();
if (!store) {
throw new Error(
`Context.set('${key}', ...) called outside a request scope`,
);
}
if (key === 'actor' || key === 'req' || key === 'requestId') {
(store.known as Record<string, unknown>)[key] = value;
} else {
store.extra.set(key, value);
}
}
/**
* Returns the full context store, or `undefined` when called outside a
* request scope. Prefer `.get(key)` for individual lookups.
*/
static current(): ContextStore | undefined {
return als.getStore();
}
}
// -- Internal: used by the request-context middleware -----------------
/**
* Run `fn` in a scope that starts as a copy of the current one, so what it
* writes is invisible both to the caller and to anything running beside it.
* Cuts both ways: nothing the callee stores survives the scope.
*/
export const runInDerivedContext = <T>(fn: () => T): T => {
const parent = als.getStore();
const store: ContextStore = {
known: { ...(parent?.known ?? {}) },
extra: new Map(parent?.extra ?? []),
};
return als.run(store, fn);
};
/**
* Run `fn` inside a new context scope. Used by the request-context middleware
* to wrap the remainder of the middleware/handler chain.
*/
export const runWithContext = <T>(
initial: Partial<KnownContextFields>,
fn: () => T,
): T => {
const store: ContextStore = {
known: { ...initial },
extra: new Map(),
};
return als.run(store, fn);
};