Skip to content

fix(cli): refuse to send a saved token to a different server origin - #2452

Merged
yuezengwu merged 10 commits into
first-tree-ai:mainfrom
Walternater:fix/credential-origin-binding
Nov 19, 2026
Merged

yuezengwu merged 10 commits into
first-tree-ai:mainfrom
Walternater:fix/credential-origin-binding

Conversation

@Walternater

Copy link
Copy Markdown
Contributor

Summary

  • The CLI refuses to send the token saved for one server to a different origin, and says how to switch servers deliberately.
  • credentials.json records the server a token was minted for, but every command resolved its target independently (--server, FIRST_TREE_SERVER_URL, client.yaml). Nothing compared the two, so an override shipped a production token to whatever URL it named.

Closes #1629 (SEC-023).

Reproduction

Local HTTP server as the "attacker origin", credentials.json bound to https://prod.example, only FIRST_TREE_SERVER_URL pointed at the local server, real command:

$ FIRST_TREE_SERVER_URL=http://127.0.0.1:53922 first-tree agent list --remote
host: 127.0.0.1:53922
authorization: Bearer eyJhbGciOiJub25lIiwi…prod-signature

The production access token reached the local server.

Already correct before this PR, for the record: /auth/refresh uses credentials.serverUrl, so a stale token is not refreshed against the override. The exposed half is "send the token you already hold".

Fix

Bind every transport that carries the stored token, not just the ones a reviewer happens to find:

  • cliFetch compares the canonical origins (scheme/host/port via URL, so https://PROD.example and https://prod.example:443 compare equal) and fails closed with both origins named.
  • commands that build their own SDK now take the token through accessTokenForOrigin(serverUrl): _shared/member.ts, _shared/local-agent.ts, agent/prune.ts, context/activate.ts, _shared/doctor-checks.ts, runtime-provider-reconcile.ts.
  • the seven direct fetch sites in tree init and org bind-tree go through cliFetch, and an origin refusal is re-thrown instead of being swallowed by their "degrade to a network error" catch.

Only a token that matches the credential store is checked, so the login exchange, admin tokens and one-shot tokens are untouched. The refusal message names the real remedy:

Refusing to send saved credentials to http://127.0.0.1:53922: they were issued for https://prod.example.
  If http://127.0.0.1:53922 is the server you meant to use, sign in to it (this replaces the saved credential):
    first-tree logout && first-tree login <code from http://127.0.0.1:53922>
  Otherwise drop the override (--server / FIRST_TREE_SERVER_URL) so this command uses https://prod.example.

Validation

  • npx vitest run apps/cli/src/__tests__/credential-origin.test.ts → 6 passed. Against the previous code the same two behavioural cases fail as fetch failed and "the command returned normally".
  • Command-level case: agent list --remote under the attack above is refused in-process and the local server receives zero requests (asserted on the recorded requests, not on the error text alone).
  • Guarded surfaces: canonical-origin normalisation, stored token to a foreign origin, equivalent spelling to its own origin (request is actually attempted), unrecognised token not intercepted, accessTokenForOrigin positive and negative.
  • Affected command suites (tree init, org bind-tree, doctor, agent prune, context activate, agent config, cli-fetch): 91 passed, 1 failure that also fails on unmodified main locally (tree-init-command-extra, macOS /var ↔ /private/var symlink aliasing, reported as [Bug] macOS: any workspace under an aliased path (/tmp, /var, ~/symlinked-dir) refuses to bootstrap #2449).
  • Full apps/cli/src/__tests__ (1822 tests): 20 failures on this branch vs 18 on unmodified main; the two extra client-switch-transaction-extra cases pass 22/22 when that file runs alone (load-dependent flake, not reproducible).
  • npx tsc --noEmit in apps/cli clean; npx biome check clean.

Change Surface

  • apps/cli public CLI or help output
  • docs or contributor-facing repository metadata

Notes

  • docs/onboarding-guide.md documents the binding next to FIRST_TREE_SERVER_URL.
  • Not covered, deliberately: the daemon's own connection (core/client-runtime.ts, WebSocket + SDK) speaks to the server recorded in client.yaml, so a hand-edited client.yaml can still point it at another origin. Closing that needs the same check on the connection layer; happy to add it here if you prefer one PR.
  • Anyone whose client.yaml and credentials.json had already drifted will now get a clear error instead of a silent send; login rewrites both, and logout clears them.

The target URL (`--server`, `FIRST_TREE_SERVER_URL`, config) and the persisted
credential are resolved independently and were never compared, so pointing the
CLI at another origin sent the token minted for production to it (SEC-023).

Reproduced end to end: with `credentials.json` bound to `https://prod.example`
and only `FIRST_TREE_SERVER_URL` pointed at a local server, `agent list --remote`
delivered `Authorization: Bearer <prod token>` to that server.

Bind every transport that carries the stored token:

- `cliFetch` guards its own requests (all direct `fetch` sites now go through
  it, including `tree init` and `org bind-tree`), and
- the SDK instances a command builds use `accessTokenForOrigin(serverUrl)`
  instead of `ensureFreshAccessToken()`.

Only a token that matches the credential store is checked, so login codes,
admin tokens and one-shot exchange tokens are unaffected. Origins compare by
scheme/host/port via `URL`, so equivalent spellings are not rejected, and the
refusal message names the real remedy (`logout` + `login <code>`) rather than a
flag that does not exist.

Not covered here: the daemon's own connection (`core/client-runtime.ts`,
WebSocket + SDK), which speaks to the server recorded at login. A hand-edited
`client.yaml` can still point it elsewhere.

@yuezengwu yuezengwu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The CLI can load a saved token and later pass that captured value to transport. The new origin check rereads the credentials file and returns early on a token mismatch. If credentials change between those steps, the captured credential is no longer checked against its issuing origin. Please carry origin together with the token returned by the load or refresh step and check that pair at the transport boundary. A mocked rotation between resolution and transport can cover the case.

… file

The origin check re-read `credentials.json` at transport time and returned early
when the token was no longer in the store. A refresh, or a re-login in another
terminal, rewrites that file, so a token captured before the rewrite was no
longer checked at all and the transport sent it to a foreign origin (SEC-023).

Carry the pair instead: `loadCredentials`/`saveCredentials` record
token → origin, and the transport check consults that memory first, falling back
to the file only for a token this process has not seen. The memory is bounded to
the most recent pairs, and a file-derived match is remembered too so a later
rotation cannot disarm it either.

Cases: load the production token, rewrite the store for staging, send the
captured token → still refused; send the rotated token to staging → allowed.
The first fails against the previous implementation (the request goes out).
@Walternater

Copy link
Copy Markdown
Contributor Author

Fixed — d76e6501.

The check now carries the origin with the token instead of re-deriving it from the file:

  • loadCredentials() and saveCredentials() record token → origin for both the access and refresh token (bounded to the 16 most recent pairs);
  • assertCredentialOriginForToken consults that record first and only falls back to reading credentials.json for a token this process has never seen. A file-derived match is recorded too, so a later rotation cannot disarm a token already in hand.

That closes the window you described: the captured token is compared against the origin that issued it, whatever the file says by the time it reaches the transport.

Cases:

  1. load the production credential → rewrite credentials.json for https://staging.example with a rotated token → send the captured production token to staging → refused. Against the previous implementation the request goes out (TypeError: fetch failed, i.e. it was attempted against staging).
  2. rewrite to staging, load, send the rotated token to staging → allowed and the request is actually made (stubbed fetch, asserted on the call), so the fix does not simply reject everything after a rotation.

forgetRememberedCredentialOrigins() is exported for tests and used in beforeEach so cases do not share state. credential-origin (8), cli-fetch, agent-config-cli and doctor suites: 20 passed. tsc --noEmit and biome check clean.

@yuezengwu yuezengwu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The single-rotation case now passes, but the process-wide cache can evict an origin while a caller still holds the resolved credential. An evicted credential that is also absent from the current file then takes the unknown-token pass-through. Please attach the issuing origin to the credential returned by load or refresh and retain that pair through the request. Keep the intentional foreign-token path explicit and separate from file-derived credentials. A mock can verify that a held credential retains its origin independently of later load activity.

…oken table

Review follow-up on SEC-023. The in-process token→origin map could evict an
origin while a caller still held the resolved credential; if that credential had
also left the store (a refresh or a re-login rewrote it), the check fell through
to the unknown-token path and the request went out.

Attach the origin where the token is obtained and carry the pair:

- `ensureFreshBoundAccessToken()` returns `{ token, origin }`, built from the same
  credential snapshot the refresh talks to, so the pair describes whoever minted
  the token no matter what the file says later;
- `assertBoundCredentialOrigin(serverUrl, credential)` is a pure function of the
  pair — no file read, no process-wide memory, nothing to evict;
- `accessTokenForOrigin`, the daemon's connection auth, the runtime-repair fetch
  and the capability/skill uploads all take or resolve the pair;
- `cliFetch` keeps a check, now named and documented as file-derived: it can
  only classify a token the store still contains, and a token it does not know is
  the explicit login-code / one-shot-exchange path.

The eviction scenario becomes a test: hold a production credential, load 32 more
from other origins, rewrite the store, and the held pair still refuses the foreign
origin. `accessTokenForOrigin` is asserted to keep refusing after the store is
rewritten mid-request.
@Walternater

Copy link
Copy Markdown
Contributor Author

Pushed 59d029b1.

You are right, and the root cause was the shape of the previous fix: a token → origin table is a memory of a fact, and memory can be dropped. The origin now travels with the value, so there is nothing to evict.

What changed

export type BoundCredential = { readonly token: string; readonly origin: string | null };
  • ensureFreshBoundAccessToken() returns the pair, built from the same snapshot the refresh talks to — so it describes whoever minted the token even if a re-login rewrites the file a moment later.
  • assertBoundCredentialOrigin(serverUrl, credential) is a pure function of the pair. No file read, no process-wide state, no fallback branch. CredentialOriginMismatchError is unchanged.
  • The pair is retained through the request at every site that knows its server: accessTokenForOrigin, the daemon's connection getAccessToken, the runtime-repair GET /agents/:id, uploadClientCapabilities, uploadAgentSkills.
  • The table and its rememberCredentialOrigin / forgetRememberedCredentialOrigins API are deleted.

The two paths are now explicit and separate, as you asked

path who what it can prove
pair (assertBoundCredentialOrigin) anything that obtained the credential the origin that issued this object, for as long as it is held
file-derived (assertStoredCredentialOriginForToken) header inspection in cliFetch the origin of a token the store currently contains

The second is named for what it is. A token the store does not contain is the login-code / one-shot exchange path, and that pass-through is stated in the doc comment rather than being an incidental fallback.

Verification

case result
hold a production credential, rewrite the store for staging assertBoundCredentialOrigin("https://staging.example", held) throws
same, after 32 further loads from other origins (any table would have dropped it) still throws
rotated credential sends to its own origin allowed
accessTokenForOrigin("https://prod.example") resolved, store rewritten mid-request still resolves to the production token
accessTokenForOrigin("http://127.0.0.1:9") throws CredentialOriginMismatchError
agent list --remote with an override still refuses and sends nothing
cliFetch with a stored token for a foreign origin still refuses
cliFetch with an unknown token passes — the explicit foreign-token path

I want to be explicit about the one behaviour this trades away: the round-1 case "a token captured from the store, then the store rewritten, then sent through cliFetch" is no longer caught by cliFetch itself, because a header-only transport cannot know that token's origin and guessing from the file is exactly the failure mode you identified. That guarantee now lives at the pair, i.e. where the token is actually obtained — and the daemon and SDK paths all go through it.

Suites: apps/cli targeted set (credential-origin, daemon start/probe, runtime-provider reconcile, ensure-fresh-access-token, client-runtime wiring, prompt, onboard, local-agent token requests, org-bind-tree, login) 210/210; full apps/cli suite running; tsc --noEmit and biome ci . --diagnostic-level=error clean.

…strap mock

SEC-023 resolves credentials through `ensureFreshBoundAccessToken`, which the
`tree init` suite's narrow `core/bootstrap.js` mock did not provide: the SDK
token provider threw, the seed preflight classified the throw, and ten cases
reported the mock error instead of their own behaviour.

The mock now derives the pair from the string accessor it already stubs, with a
null origin so the origin assertion abstains — these cases do not test origins.
@Walternater

Copy link
Copy Markdown
Contributor Author

Full-suite numbers, plus one test-mock fix I had to make on top of 59d029b1.

apps/cli full suite (2000 tests): 1981 passed, 18 failed, 1 skipped. All 18 are pre-existing on this machine and identical before the change:

file failed same at d76e6501
context-byo-repository 4 4
context-project-resolver 8 8
context-skill-loader 1 1
migrate-agent-dirs 4 4
tree-init-command-extra 1 1

I verified this by running the same eight files at d76e6501 (the commit before this round) and at this branch: 18 failed / 145 passed in both. The one remaining tree-init failure is creates and binds a nested Self-Managed GitLab repository with only local glab/git credentials — no glab on this machine.

The fix I had to add (d08ee800)

The first full run showed 30 failures, 10 of them new: tree init --bind --team exits 1 without doing anything. Cause is not product code — the suite's core/bootstrap.js mock lists exports by hand and did not include the new bound accessor:

mock  →  accessTokenForOrigin  →  ensureFreshBoundAccessToken  (missing)
      →  SDK token provider throws
      →  seed preflight classifies the throw
      →  exitCode = 1

So ten cases were reporting the mock gap rather than their own behaviour. The mock now derives the pair from the string accessor it already stubs:

ensureFreshBoundAccessToken: async (...args: unknown[]) => ({
  token: await bootstrapMocks.ensureFreshAccessToken(...args),
  origin: null, // these cases never check an origin, so the assertion abstains
}),

Worth naming as a trade-off rather than hiding it: any path that starts resolving through a new export will break hand-written bootstrap mocks the same way. If you would rather have these suites spread importOriginal so a new export cannot silently become a mock hole, that is a mechanical follow-up I can do in a separate PR — I kept it out of this one because it touches ~20 files.

tsc --noEmit and biome ci . --diagnostic-level=error clean.

@yuezengwu yuezengwu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The credential pair fixes the eviction problem for the migrated callers. The remote agent-list and organization-binding commands still use the token-only accessor and pass the resulting string to cliFetch, which only recognizes tokens present in the current file. Please migrate the direct CLI request paths that already know their destination to accessTokenForOrigin or pass the bound credential to transport. Verify at a real command entry point with mocked credential rotation and a mocked transport. Keep one-shot credentials distinct from the persisted-token path.

…stination

Review follow-up. The pair removed the eviction problem where it was applied,
but the direct command paths still resolved a bare token with
`ensureFreshAccessToken()` and handed the string to `cliFetch`, whose check can
only classify a token the current file still contains.

Every request path that knows its destination now resolves the pair:

- commands: `agent list/status/create/reset/bind`, `agent session list/control`,
  `chat open`, `org bind-tree`, `logout`'s client retire, and both `tree init`
  server phases;
- SDK token resolvers: `login` and `daemon start` name-migration resolvers;
- daemon helpers: `listPinnedAgents`, `reconcileLocalRuntimeProviders`,
  `uploadClientCapabilities`, `uploadAgentSkills` take the `BoundCredential` (the
  first two previously took a string).

`cliFetch` keeps its file-derived check, which is now the only place a token is
classified from the store: one-shot credentials (login code, freshly exchanged
token) still pass through, and that is stated where it happens.

Tests: two real command entry points (`agent list --remote` and
`org bind-tree`) assert that nothing is sent to an override origin, that the
bound accessor is the one used, and that a rotation of the store to the
destination's origin then allows the request.
Five suites replace `core/bootstrap.js` (and, in one case, the `core/index.js`
barrel) with an explicit export list. Any request path that starts resolving
through the bound accessor then hits a mock hole instead of its own behaviour:
26 cases reported `No "ensureFreshBoundAccessToken" export` and 4 reported the
same for `accessTokenForOrigin`.

Each mock now derives the bound form from the string accessor it already drives,
so a stub, a one-shot rejection or a reset applies to both without mirroring.
`tsc`, `biome ci`, and the full `apps/cli` suite are clean: 18 failures, all of
them the pre-existing macOS/environment set (context-byo-repository,
context-project-resolver, context-skill-loader, migrate-agent-dirs,
tree-init-command-extra).
@Walternater

Copy link
Copy Markdown
Contributor Author

Pushed 258efbcd + 1ea8cbac.

Every request path that knows its destination now takes the pair, not a bare token:

layer migrated
commands agent list / status / create / reset / bind, agent session list / control, chat open, org bind-tree, logout's client retire, both tree init server phases
SDK resolvers login and daemon start name-migration resolvers
daemon helpers listPinnedAgents, reconcileLocalRuntimeProviders, uploadClientCapabilities, uploadAgentSkills — the first two previously took accessToken: string

cliFetch keeps the file-derived check and is now the only place a token is classified from the store, so the one-shot path (login code, freshly exchanged token) stays explicit and separate.

Entry-point verification, as asked — two real commands, real credentials.json, mocked transport only:

case result
agent list --remote with the stored production credential and a foreign override exit 1, zero requests, no error body sent
the same command resolves through ensureFreshBoundAccessToken bound ≥ 1, string === 0
rotate the store to the destination's origin, rerun request goes out; string still 0
org bind-tree <url> with a foreign override exit 1, zero requests, nothing written

The accessor counters are produced by a vi.mock that delegates to the real implementation, so they assert routing rather than a stub's behaviour.

Full apps/cli suite: 1983 passed, 18 failed, 1 skipped (2002) — the same 18 pre-existing macOS/environment failures as before this round (context-byo-repository 4, context-project-resolver 8, context-skill-loader 1, migrate-agent-dirs 4, tree-init-command-extra 1). The intermediate run showed 43; the 25 extra were mock holes, fixed in 1ea8cbac: five suites replace core/bootstrap.js with an explicit export list, and each now derives the bound accessor from the string accessor it already drives, so a stub or a one-shot rejection applies to both without mirroring.

If you would rather have those suites spread importOriginal so a new export can never become a mock hole again, that is a mechanical follow-up I can open separately — I kept it out of this PR because it touches ~20 files.

The block-form factories introduced indentation the formatter rejects, and
`biome check .` (what CI runs) reports those as errors while `biome ci` did not —
so the previous push passed locally and failed on the lint job. Also drops the
`ensureFreshAccessToken` import the daemon no longer uses.
@Walternater

Copy link
Copy Markdown
Contributor Author

CI follow-up in c965d85e: the block-form mock factories left indentation the formatter rejects (biome check . errors on that while biome ci did not, so it slipped past my local check). Formatter applied to the four files, plus the now-unused ensureFreshAccessToken import dropped from daemon/start.ts. pnpm check and tsc --noEmit clean; the 8 affected suites are 148/148.

@yuezengwu yuezengwu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The command migrations cover the agent-list and organization-binding paths from the prior review. The agent config commands still resolve their destination and then obtain a bare token through ensureFreshAdminToken. Their shared fetchers use the file-derived check, so a credential held across the commands' requests has no durable issuing origin. Please use the bound accessor for these commands too, and cover the shared fetch path with a mocked credential update. Preserve the separate behavior for one-shot credentials.

The config commands resolved their destination, then took a bare token from
`ensureFreshAdminToken()` and passed the string through the shared fetchers.
Those fetchers rely on `cliFetch`'s file-derived check, which has to answer
"which origin issued this token?" by consulting the credential file at request
time — and deliberately lets through tokens the file does not contain. A
credential held across a command's several requests therefore had no durable
issuing origin: a re-login in another terminal mid-command re-pointed the
answer, and a token that had been rotated away became unclassifiable.

`credentialForOrigin` returns the pair (token + issuer) for a known
destination; the commands now bind once and the shared fetchers take the pair,
asserting it against the URL they are about to call. The guarantee no longer
depends on the file's contents at request time. One-shot credentials (login
code exchange) are untouched and still use their own path.

Tests: the fetch helper refuses a credential bound to another origin without
sending anything, and keeps using the pair it was handed after the store
rotates. Both fail if the boundary assertion is removed.
@Walternater

Copy link
Copy Markdown
Contributor Author

Fixed in e1b1ad90. You were right that the agent-config family was still on the bare-token path: every one of those commands resolved its destination with resolveServerUrl and then called ensureFreshAdminToken(), and the shared fetchers passed the resulting string to cliFetch — so the only thing tying the token to that server was the file's contents at request time.

What changed

  • The eight agent config commands (show, set-model, set-env, set-reasoning-effort, set-service-tier, add-repo, dry-run, prompt) bind once per command with credentialForOrigin(serverUrl) and carry the pair.
  • _shared/fetchers.ts now takes BoundCredential instead of a string: adminFetch asserts the pair against the URL it is about to call, and resolveAgentRecord asserts it against the destination before resolving. The guarantee is a property of the pair, not of a later file read.
  • One-shot credentials are untouched: the login-code exchange and ensureFreshAccessToken's other callers keep their own path, and accessTokenForOrigin remains a thin wrapper for call sites that only need the header value.

Coverage you asked for (agent-config-fetchers.test.ts):

case assertion
keeps spending the bound credential after the store rotates the store is swapped mid-test; the second request still carries the original pair's token
refuses a bound credential on another origin before sending anything a pair bound to https://hub.example calling another host rejects and fetch is never called

Both fail if assertBoundCredentialOrigin is removed. The command-level suite (agent-config-commands-extra.test.ts) now mocks credentialForOrigin rather than the token accessor, so a command that regresses to a bare token fails there too — the mock would not return a credential.

apps/cli: tsc --noEmit clean, pnpm check clean, the three affected suites 39/39. CI is running on e1b1ad90.

@yuezengwu yuezengwu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The config commands now carry the bound credential as requested. The interactive agent add flow (core/prompt.ts) and the multi-request onboardCreate flow (core/onboard.ts) still pass bare saved tokens to cliFetch. Those calls fall back to the mutable credentials-file check rather than carrying the issuing origin, so the binding still depends on which credentials are on disk at send time. Please use the same destination-bound accessor in both paths and update their existing mocked tests.

`promptAddAgent` and `onboardCreate` resolved their destination and then took a
bare token from `ensureFreshAccessToken()`, handing the string to `cliFetch` —
whose guard answers "which origin issued this?" by reading the credentials file
at request time, and deliberately lets through tokens the file no longer holds.
`onboardCreate` makes several requests with that one string, so a re-login in
another terminal mid-flow could retarget what the guard believes.

Both now bind once through `credentialForOrigin(serverUrl)`, the same accessor
the agent-config commands use. Their existing mocked tests mock that accessor
instead of the token function, so a regression to the bare token leaves the
credential undefined and the flow fails rather than silently passing.
@Walternater

Copy link
Copy Markdown
Contributor Author

Both remaining paths migrated in d1e6df47.

  • core/prompt.ts (agent add): resolves the destination, then binds once with credentialForOrigin(serverUrl) before the agent lookup.
  • core/onboard.ts (onboardCreate): binds once at the top; the org lookup and every createAgentViaAdmin call in the flow spend that one pair, so a re-login in another terminal mid-flow can no longer retarget what the guard believes.

ensureFreshAccessToken no longer appears in either file; the mocked suites now mock ../core/access-token.js (credentialForOrigin) instead of the token accessor, so a regression to a bare token hands the flow undefined and fails instead of passing quietly.

apps/cli: onboard-core + prompt-core 14/14, tsc --noEmit clean, pnpm check clean. CI is running on d1e6df47.

The mock swap alone does not fail a regression: the bootstrap mock still answers
`ensureFreshAccessToken` with a string, and neither suite asserts the
Authorization header, so a command that went back to the bare accessor would
pass with `Bearer undefined`. Both flows now assert the bound accessor was
called with the resolved server and that the token accessor was not called.
@Walternater

Copy link
Copy Markdown
Contributor Author

Correction to my previous comment: the mock swap alone would not have caught a regression — the bootstrap mock still answers ensureFreshAccessToken with a string and neither suite asserts the Authorization header, so a command that went back to the bare accessor would have passed with Bearer undefined.

7959d4a3 makes the guarantee explicit in both suites:

expect(credentialForOriginMock).toHaveBeenCalledWith("http://first-tree.test");
expect(ensureFreshAccessTokenMock).not.toHaveBeenCalled();

onboard-core + prompt-core 14/14, tsc and pnpm check clean. CI is running on 7959d4a3.

@yuezengwu yuezengwu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The agent-add and onboarding flows now obtain credentials bound to the destination they use, and the tests verify they no longer call the bare accessor. The fixed onboarding destination is reused across its requests. CI and CLA passed on this head, and 64 focused tests passed on the combined tree against current main.

@yuezengwu
yuezengwu merged commit c181643 into first-tree-ai:main Nov 19, 2026
15 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 19, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[SEC-023][High] Persisted credentials are not bound to the configured server origin

2 participants