Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions docs/compose/spec/auth-metadata-tolerant.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
feature: auth-metadata-tolerant
status: delivered
updated: 2026-11-18
source: https://github.com/XiaomiMiMo/MiMo-Code/pull/2830
---

# Tolerant auth.json metadata

## Report
**What was built** — `Auth.all()` now tolerates non-string `metadata` fields on disk `api` entries (they are omitted from the decoded view instead of dropping the credential), and `Auth.set` / `Auth.remove` rewrite the raw JSON so entries and fields the CLI does not understand survive. Desktop one-click-linked `xiaomi` / `xiaomi-token-plan-*` credentials are usable from the CLI and are no longer erased when the CLI re-links another provider.

**Verification**
- `bun test test/auth test/provider/provider-auth-write.test.ts test/provider/xiaomi-family.test.ts test/plugin/mimo.test.ts` — 45 pass / 0 fail (both new tests failed on base for the intended reason)
- `bun test test/provider test/cli` — 1048 pass / 0 fail
- `bun run typecheck` (packages/cli) — pass
- Manual: Desktop-shaped auth.json under a temp `XDG_DATA_HOME`, `providers list` — base: 0 credentials; branch: 2 credentials
- Independent review — approved, no critical findings; test cleanup nit addressed

## [S1] Problem

MiMo Desktop's one-click platform link writes `auth.json` entries shaped
`{ type: "api", key, metadata: { uid, base_url, platform_linked: true } }` for `xiaomi` and
`xiaomi-token-plan-*`. The CLI's `Auth.Api` schema declares `metadata` as
`Record<string, string>`, so the boolean `platform_linked` fails decoding and `Auth.all()` silently
drops the whole entry. Two user-visible effects:

1. The CLI sees no credential for the linked providers; requests go out without a valid key
(`401 Invalid API Key`).
2. `Auth.set` / `Auth.remove` rewrite the file from the decoded view, so re-linking one provider in
the CLI (e.g. Token Plan) erases every other undecodable entry from disk — the Desktop-linked
`xiaomi` disappears, leaving only `xiaomi-token-plan-cn`.

## [S2] Design

### S2.1 Lenient read

When reading `auth.json` from disk, an `api` entry's `metadata` keeps only its string-valued fields
before decoding; non-string fields (such as `platform_linked: true`) are omitted from the decoded
`Auth.Info`. The entry itself stays valid. The public `Auth.Info` type is unchanged
(`metadata?: Record<string, string>`), so the SDK and plugin contracts do not move.

### S2.2 Lossless write

`Auth.set` and `Auth.remove` mutate the raw JSON object of the same source `all()` reads, touching
only the target key (plus its trailing-slash twin). Entries the CLI does not understand, and unknown
metadata fields on other entries, are written back byte-for-byte equivalent JSON values.

### S2.3 Unchanged paths

The in-process `inject` / `MIMOCODE_AUTH_CONTENT` channel keeps returning the parsed JSON as before.

## [S3] Out of Scope

- Whether a CLI re-link should preserve Desktop's `platform_linked` marker on the entry it
overwrites (the overwritten entry is replaced by the CLI's own login result, as today).
- Changes in MiMo Desktop.

## Tasks
- [x] T1: Lenient decode of api metadata — acceptance: an `auth.json` entry with `metadata.platform_linked: true` is returned by `Auth.all()` with its key and string metadata (covers: S2.1)
- [x] T2: Raw-preserving set/remove — acceptance: `Auth.set` on one provider keeps a sibling entry carrying `platform_linked: true` on disk unchanged (covers: S2.2)

## Journey log
None
36 changes: 30 additions & 6 deletions packages/cli/src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,22 @@ export class AuthError extends Schema.TaggedErrorClass<AuthError>()("AuthError",
cause: Schema.optional(Schema.Defect),
}) {}

/**
* `metadata` is typed as string → string, but hosts sharing auth.json may add
* non-string fields (MiMo Desktop's `platform_linked: true`). Drop those from the
* decoded view instead of rejecting the whole credential.
*/
function stringMetadata(value: unknown): unknown {
if (!value || typeof value !== "object" || Array.isArray(value)) return value
const entry = value as { type?: unknown; metadata?: unknown }
const metadata = entry.metadata
if (entry.type !== "api" || !metadata || typeof metadata !== "object" || Array.isArray(metadata)) return value
return {
...entry,
metadata: Object.fromEntries(Object.entries(metadata).filter(([, field]) => typeof field === "string")),
}
}

export interface Interface {
readonly get: (providerID: string) => Effect.Effect<Info | undefined, AuthError>
readonly all: () => Effect.Effect<Record<string, Info>, AuthError>
Expand All @@ -72,25 +88,33 @@ export const layer = Layer.effect(
const fsys = yield* AppFileSystem.Service
const decode = Schema.decodeUnknownOption(Info)

const all = Effect.fn("Auth.all")(function* () {
// Host-supplied JSON is trusted as-is; the file is decoded per entry.
const source = Effect.fn("Auth.source")(function* () {
const raw = injected ?? process.env.MIMOCODE_AUTH_CONTENT
if (raw) {
try {
return JSON.parse(raw)
return { data: JSON.parse(raw) as Record<string, unknown>, trusted: true }
} catch (err) {}
}

const data = (yield* fsys.readJson(file).pipe(Effect.orElseSucceed(() => ({})))) as Record<string, unknown>
return Record.filterMap(data, (value) => Result.fromOption(decode(value), () => undefined))
return { data, trusted: false }
})

const all = Effect.fn("Auth.all")(function* () {
const { data, trusted } = yield* source()
if (trusted) return data as Record<string, Info>
return Record.filterMap(data, (value) => Result.fromOption(decode(stringMetadata(value)), () => undefined))
})

const get = Effect.fn("Auth.get")(function* (providerID: string) {
return (yield* all())[providerID]
})

// Writes mutate the raw JSON so entries (or metadata fields) this build does not
// understand — e.g. a host's `platform_linked: true` — survive the rewrite.
const set = Effect.fn("Auth.set")(function* (key: string, info: Info) {
const norm = key.replace(/\/+$/, "")
const data = yield* all()
const { data } = yield* source()
if (norm !== key) delete data[key]
delete data[norm + "/"]
yield* fsys
Expand All @@ -100,7 +124,7 @@ export const layer = Layer.effect(

const remove = Effect.fn("Auth.remove")(function* (key: string) {
const norm = key.replace(/\/+$/, "")
const data = yield* all()
const { data } = yield* source()
delete data[key]
delete data[norm]
yield* fsys.writeJson(file, data, 0o600).pipe(Effect.mapError(fail("Failed to write auth data")))
Expand Down
42 changes: 42 additions & 0 deletions packages/cli/test/auth/auth.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { describe, expect } from "bun:test"
import fs from "fs/promises"
import path from "path"
import { Effect, Layer } from "effect"
import { Auth } from "../../src/auth"
import { Global } from "../../src/global"
import * as CrossSpawnSpawner from "../../src/effect/cross-spawn-spawner"
import { provideTmpdirInstance } from "../fixture/fixture"
import { testEffect } from "../lib/effect"

const node = CrossSpawnSpawner.defaultLayer

const it = testEffect(Layer.mergeAll(Auth.defaultLayer, node))
const file = path.join(Global.Path.data, "auth.json")

describe("Auth", () => {
it.live("set normalizes trailing slashes in keys", () =>
Expand Down Expand Up @@ -84,6 +88,44 @@ describe("Auth", () => {
),
)

// A host (MiMo Desktop's platform link) may store non-string metadata such as
// `platform_linked: true`. The CLI must still read the credential and must never
// drop such entries when it rewrites the file.
const linked = {
type: "api",
key: "sk-linked",
metadata: { uid: "42", base_url: "https://api.example.com/v1", platform_linked: true },
}

it.live("all keeps api entries whose metadata carries non-string values", () =>
provideTmpdirInstance(() =>
Effect.gen(function* () {
yield* Effect.promise(() => fs.writeFile(file, JSON.stringify({ xiaomi: linked })))
const data = yield* (yield* Auth.Service).all()
expect(data["xiaomi"]).toEqual(
new Auth.Api({ type: "api", key: "sk-linked", metadata: { uid: "42", base_url: "https://api.example.com/v1" } }),
)
yield* Effect.promise(() => fs.rm(file, { force: true }))
}),
),
)

it.live("set and remove preserve sibling entries verbatim", () =>
provideTmpdirInstance(() =>
Effect.gen(function* () {
const unknown = { type: "future", value: 1 }
yield* Effect.promise(() => fs.writeFile(file, JSON.stringify({ xiaomi: linked, other: unknown })))
const auth = yield* Auth.Service
yield* auth.set("xiaomi-token-plan-cn", { type: "api", key: "tp-new" })
const written = JSON.parse(yield* Effect.promise(() => fs.readFile(file, "utf8")))
expect(written).toEqual({ xiaomi: linked, other: unknown, "xiaomi-token-plan-cn": { type: "api", key: "tp-new" } })
yield* auth.remove("xiaomi-token-plan-cn")
expect(JSON.parse(yield* Effect.promise(() => fs.readFile(file, "utf8")))).toEqual({ xiaomi: linked, other: unknown })
yield* Effect.promise(() => fs.rm(file, { force: true }))
}),
),
)

// Auth.inject is the in-process channel for an embedding host (the desktop runs the engine
// in-process). It exists so credentials never have to sit in MIMOCODE_AUTH_CONTENT, which every
// child the engine spawns would inherit.
Expand Down
Loading