diff --git a/packages/cli/src/commands/handlers/auth/import.ts b/packages/cli/src/commands/handlers/auth/import.ts index e1434a24bb0..4a88ba02ad4 100644 --- a/packages/cli/src/commands/handlers/auth/import.ts +++ b/packages/cli/src/commands/handlers/auth/import.ts @@ -1,6 +1,6 @@ import { EOL } from "node:os" import { isConflictError, type CredentialCreateInput } from "@opencode/client" -import { Credential } from "@opencode/schema/credential" +import { CredentialLegacy } from "@opencode/schema/credential-legacy" import { Effect, Option, Schema } from "effect" import { Commands } from "../../commands" import { Runtime } from "../../../framework/runtime" @@ -16,7 +16,9 @@ export default Runtime.handler( if (!file && process.stdin.isTTY) return yield* Effect.fail(new Error("Pipe auth export output into stdin or pass a file to import")) const text = yield* request(() => (file ? Bun.file(file).text() : readStdin())) - const credentials = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Credential.Entry)))(text) + const credentials = yield* Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Array(CredentialLegacy.Entry)), + )(text) const client = yield* createClient({ server: Option.getOrUndefined(input.server), standalone: input.standalone }) const existing = yield* request((signal) => client.credential.list({ signal })) const ids = new Set(existing.map((credential) => credential.id)) diff --git a/packages/cli/test/auth.test.ts b/packages/cli/test/auth.test.ts index a0858247111..5e82a2fc639 100644 --- a/packages/cli/test/auth.test.ts +++ b/packages/cli/test/auth.test.ts @@ -261,6 +261,42 @@ describe("auth command", () => { expect(result.stdout).not.toContain("\n at ") }) + test("imports credentials exported before v2.1 with their form answers as metadata", async () => { + const created: unknown[] = [] + using server = authServer(async (request, url) => { + if (url.pathname === "/api/credential" && request.method === "GET") return Response.json({ data: [] }) + if (url.pathname === "/api/credential" && request.method === "POST") { + const body = await request.json() + created.push(body) + return Response.json({ data: { ...body, active: true } }) + } + return new Response("Not found", { status: 404 }) + }) + const value = { type: "key", key: "secret", configuration: { resourceName: "answered" } } + const exported = [{ id: "cred_legacy", integrationID: "azure", label: "Work", active: true, value }] + const child = Bun.spawn( + [process.execPath, "run", "src/index.ts", "auth", "import", "--server", server.url.toString()], + { + cwd: path.join(import.meta.dir, ".."), + stdin: new Blob([JSON.stringify(exported)]), + stdout: "pipe", + stderr: "pipe", + }, + ) + const [stderr, exitCode] = await Promise.all([new Response(child.stderr).text(), child.exited]) + + expect({ exitCode, stderr: stderr.trim() }).toEqual({ exitCode: 0, stderr: "Imported 1 credential" }) + expect(created).toEqual([ + { + id: "cred_legacy", + integrationID: "azure", + label: "Work", + value: { type: "key", key: "secret", metadata: { resourceName: "answered" } }, + activate: true, + }, + ]) + }) + test("removes a selected stored credential", async () => { const removed: string[] = [] using server = authServer((request, url) => { diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 01a2dfa6187..3cb024326b4 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -236,6 +236,8 @@ export type McpResourceTemplate = { mimeType?: string } +export type CredentialKey = { type: "key"; key: string; metadata?: { [x: string]: JsonValue } } + export type ProjectVcs = string export type ProjectIcon = { url?: string; override?: string; color?: string } @@ -848,7 +850,7 @@ export type FormMultiselectField1 = { default?: Array } -export type FormAnswer2 = { [x: string]: FormValue1 } +export type FormAnswer1 = { [x: string]: FormValue1 } export type VcsInfo = { provider?: string; branch: VcsBranch } @@ -1922,13 +1924,6 @@ export type FormState = | { status: "answered"; answer: FormAnswer } | { status: "cancelled"; message?: string } -export type CredentialKey = { - type: "key" - key: string - metadata?: { [x: string]: JsonValue } - configuration?: FormAnswer -} - export type ProviderInfo = { id: ProviderID canonical?: ProviderID @@ -1944,6 +1939,8 @@ export type ProviderInfo = { export type VoiceSessionResponse = { data: { transport: VoiceTransport } } +export type CredentialValue = CredentialOAuth | CredentialKey | CredentialExternal + export type ConnectionInfo = ConnectionCredentialInfo | ConnectionEnvInfo export type PtyCreated = { @@ -1994,7 +1991,7 @@ export type FormReplied = { metadata?: { [x: string]: any } type: "form.replied" location?: LocationRef - data: { id: FormID; sessionID: string; answer: FormAnswer2 } + data: { id: FormID; sessionID: string; answer: FormAnswer1 } } export type SessionInboxMove = { @@ -2379,7 +2376,13 @@ export type SessionMessageAssistantTool1 = { export type FormFields = [FormField, ...Array] -export type CredentialValue = CredentialOAuth | CredentialKey | CredentialExternal +export type CredentialEntry = { + id: CredentialID + integrationID: IntegrationID + label: string + active: boolean + value: CredentialValue +} export type FormFields2 = [FormField1, ...Array] @@ -2445,14 +2448,6 @@ export type IntegrationKeyMethod = { type: "key"; label?: string; form?: FormFie export type IntegrationExternalMethod = { id: IntegrationMethodID; type: "external"; label: string; form?: FormFields } -export type CredentialEntry = { - id: CredentialID - integrationID: IntegrationID - label: string - active: boolean - value: CredentialValue -} - export type FormInfo1 = { id: FormID; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields2 } export type SessionMessageInfo = @@ -5180,14 +5175,7 @@ export type CredentialCreateInput = { readonly expires: number readonly metadata?: { readonly [x: string]: JsonValue } } - | { - readonly type: "key" - readonly key: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly configuration?: { - readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray - } - } + | { readonly type: "key"; readonly key: string; readonly metadata?: { readonly [x: string]: JsonValue } } | { readonly type: "external" readonly methodID: string @@ -5208,14 +5196,7 @@ export type CredentialCreateInput = { readonly expires: number readonly metadata?: { readonly [x: string]: JsonValue } } - | { - readonly type: "key" - readonly key: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly configuration?: { - readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray - } - } + | { readonly type: "key"; readonly key: string; readonly metadata?: { readonly [x: string]: JsonValue } } | { readonly type: "external" readonly methodID: string @@ -5236,14 +5217,7 @@ export type CredentialCreateInput = { readonly expires: number readonly metadata?: { readonly [x: string]: JsonValue } } - | { - readonly type: "key" - readonly key: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly configuration?: { - readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray - } - } + | { readonly type: "key"; readonly key: string; readonly metadata?: { readonly [x: string]: JsonValue } } | { readonly type: "external" readonly methodID: string @@ -5264,14 +5238,7 @@ export type CredentialCreateInput = { readonly expires: number readonly metadata?: { readonly [x: string]: JsonValue } } - | { - readonly type: "key" - readonly key: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly configuration?: { - readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray - } - } + | { readonly type: "key"; readonly key: string; readonly metadata?: { readonly [x: string]: JsonValue } } | { readonly type: "external" readonly methodID: string @@ -5292,14 +5259,7 @@ export type CredentialCreateInput = { readonly expires: number readonly metadata?: { readonly [x: string]: JsonValue } } - | { - readonly type: "key" - readonly key: string - readonly metadata?: { readonly [x: string]: JsonValue } - readonly configuration?: { - readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray - } - } + | { readonly type: "key"; readonly key: string; readonly metadata?: { readonly [x: string]: JsonValue } } | { readonly type: "external" readonly methodID: string diff --git a/packages/core/src/credential.ts b/packages/core/src/credential.ts index f39940931af..d764fd955e2 100644 --- a/packages/core/src/credential.ts +++ b/packages/core/src/credential.ts @@ -3,6 +3,7 @@ export * as Credential from "./credential.js" import { asc, desc, eq } from "drizzle-orm" import { Cause, Context, Effect, Layer, Schema } from "effect" import { Credential } from "@opencode/schema/credential" +import { CredentialLegacy } from "@opencode/schema/credential-legacy" import { Integration } from "@opencode/schema/integration" import { Database } from "./database/database.js" import { Bus } from "./bus.js" @@ -67,7 +68,8 @@ const layer = Layer.effect( Effect.gen(function* () { const db = (yield* Database.Service).db const bus = yield* Bus.Service - const decode = Schema.decodeUnknownSync(Value) + // Rows written before v2.1 may carry the old key credential shape. + const decode = Schema.decodeUnknownSync(CredentialLegacy.Value) const stored = (row: typeof CredentialTable.$inferSelect) => { if (!row.integration_id) return return new Info({ diff --git a/packages/core/src/integration.ts b/packages/core/src/integration.ts index 8480e463245..8e75588ce64 100644 --- a/packages/core/src/integration.ts +++ b/packages/core/src/integration.ts @@ -759,7 +759,7 @@ const layer = Layer.effect( value: Credential.Key.make({ type: "key", key: input.key, - ...(Object.keys(answer).length > 0 ? { configuration: answer } : {}), + ...(Object.keys(answer).length > 0 ? { metadata: answer } : {}), }), }) }), diff --git a/packages/core/src/model-resolver.ts b/packages/core/src/model-resolver.ts index e3938a7f2fb..1e13ea150ca 100644 --- a/packages/core/src/model-resolver.ts +++ b/packages/core/src/model-resolver.ts @@ -199,8 +199,7 @@ const resolveCatalogModel = Effect.fn("ModelResolver.resolveCatalogModel")(funct dependencies?: Dependencies, ) { const resolved = prepareRuntimeModel(model) - const configuration = credential?.type === "key" ? credential.configuration : undefined - const configured = { ...resolved.settings, ...credential?.metadata, ...configuration } + const configured = { ...resolved.settings, ...credential?.metadata } if (Provider.isAISDK(resolved.package)) { const loadAISDK = dependencies?.loadAISDK if (!loadAISDK) return yield* unsupported(resolved) @@ -209,7 +208,6 @@ const resolveCatalogModel = Effect.fn("ModelResolver.resolveCatalogModel")(funct Provider.mergeOverlay(resolved.settings, { ...nativeCredentialSettings(resolved, resolved.package ?? "", credential), ...credential?.metadata, - ...configuration, }) ?? {}, ) return yield* loadAISDK({ ...resolved, settings }).pipe( diff --git a/packages/core/src/plugin/provider/azure.ts b/packages/core/src/plugin/provider/azure.ts index 0b754ba66d5..76549ff71d3 100644 --- a/packages/core/src/plugin/provider/azure.ts +++ b/packages/core/src/plugin/provider/azure.ts @@ -479,15 +479,12 @@ function expandResourceName(baseURL: string, resourceName: string) { .replaceAll("${AZURE_COGNITIVE_SERVICES_RESOURCE_NAME}", resourceName) } -// The Azure CLI method stores the resource as credential metadata, the API key method as its form answer. API keys -// imported from V1 keep their connect-form answer as metadata. +// Both the API key and Azure CLI methods store their resource form answer as credential metadata. function credentialResource(credential: Credential.Value | undefined) { const resource = - credential?.type === "key" - ? (credential.configuration?.resourceName ?? credential.metadata?.resourceName) - : credential?.type === "external" && credential.methodID === methodID - ? credential.metadata?.resourceName - : undefined + credential?.type === "key" || (credential?.type === "external" && credential.methodID === methodID) + ? credential.metadata?.resourceName + : undefined return typeof resource === "string" && resource.trim() !== "" ? resource : undefined } diff --git a/packages/core/src/plugin/provider/snowflake-cortex.ts b/packages/core/src/plugin/provider/snowflake-cortex.ts index 9f41a03cd6e..0249123e018 100644 --- a/packages/core/src/plugin/provider/snowflake-cortex.ts +++ b/packages/core/src/plugin/provider/snowflake-cortex.ts @@ -172,13 +172,7 @@ export const SnowflakeCortexPlugin = define({ const load = Effect.gen(function* () { const value = (yield* saved)?.value - account.value = normalizeAccount( - process.env.SNOWFLAKE_ACCOUNT ?? - (value?.type === "key" - ? (value.configuration?.account ?? value.metadata?.account) - : value?.metadata?.account) ?? - configured?.account, - ) + account.value = normalizeAccount(process.env.SNOWFLAKE_ACCOUNT ?? value?.metadata?.account ?? configured?.account) }) yield* load yield* ctx.provider.transform((providers) => { diff --git a/packages/core/test/credential.test.ts b/packages/core/test/credential.test.ts index ed970d0fc84..fde1330aa73 100644 --- a/packages/core/test/credential.test.ts +++ b/packages/core/test/credential.test.ts @@ -1,5 +1,5 @@ import { describe, expect } from "bun:test" -import { eq } from "drizzle-orm" +import { eq, sql } from "drizzle-orm" import { Effect } from "effect" import { Bus } from "@opencode/core/bus" import { Credential } from "@opencode/core/credential" @@ -48,6 +48,30 @@ describe("Credential", () => { }), ) + it.effect("reads key form answers stored in configuration before v2.1 as metadata", () => + Effect.gen(function* () { + const credentials = yield* Credential.Service + const db = (yield* Database.Service).db + const integrationID = Integration.ID.make("azure") + // A row from an earlier release, which the current schema would otherwise strip. + const legacy = { + type: "key", + key: "secret", + metadata: { imported: true, resourceName: "older" }, + configuration: { resourceName: "answered" }, + } + yield* db.run( + sql`INSERT INTO credential (id, integration_id, label, value, active, time_created, time_updated) VALUES ('cred_legacy', ${integrationID}, 'Legacy', ${JSON.stringify(legacy)}, 1, 0, 0)`, + ) + + expect((yield* credentials.get(Credential.ID.make("cred_legacy")))?.value).toEqual({ + type: "key", + key: "secret", + metadata: { imported: true, resourceName: "answered" }, + }) + }), + ) + it.effect("publishes global events only for observable credential mutations", () => Effect.gen(function* () { const credentials = yield* Credential.Service diff --git a/packages/core/test/integration.test.ts b/packages/core/test/integration.test.ts index 5d352c76679..95ac02c2320 100644 --- a/packages/core/test/integration.test.ts +++ b/packages/core/test/integration.test.ts @@ -187,7 +187,7 @@ describe("Integration", () => { expect.objectContaining({ integrationID, label: "Work", - value: Credential.Key.make({ type: "key", key: "secret", configuration: { accountId: "account" } }), + value: Credential.Key.make({ type: "key", key: "secret", metadata: { accountId: "account" } }), }), ]) expect((yield* Fiber.join(created)).map((event) => ({ type: event.type, data: event.data }))).toEqual([ diff --git a/packages/core/test/model-resolver.test.ts b/packages/core/test/model-resolver.test.ts index 1dfdee22381..5ea1062524b 100644 --- a/packages/core/test/model-resolver.test.ts +++ b/packages/core/test/model-resolver.test.ts @@ -1336,7 +1336,7 @@ describe("ModelResolver", () => { Credential.Key.make({ type: "key", key: "workers-secret", - configuration: { accountId: "account" }, + metadata: { accountId: "account" }, }), ) @@ -1397,7 +1397,7 @@ describe("ModelResolver", () => { Credential.Key.make({ type: "key", key: "fallback-secret", - configuration: { accountId: "account" }, + metadata: { accountId: "account" }, }), { loadAISDK: (runtime) => diff --git a/packages/core/test/plugin/provider-azure.test.ts b/packages/core/test/plugin/provider-azure.test.ts index f2db66158d0..963e84775a9 100644 --- a/packages/core/test/plugin/provider-azure.test.ts +++ b/packages/core/test/plugin/provider-azure.test.ts @@ -162,7 +162,7 @@ const cliCredential = () => }) const keyCredential = (key = "secret", resourceName = "test-resource") => - Credential.Key.make({ type: "key", key, configuration: { resourceName } }) + Credential.Key.make({ type: "key", key, metadata: { resourceName } }) const connect = Effect.fn(function* (value: Credential.Value) { const credentials = yield* Credential.Service diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 08275acbac3..7ef3b429b6c 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -14869,9 +14869,6 @@ }, "metadata": { "type": "object" - }, - "configuration": { - "$ref": "#/components/schemas/Form.Answer_1" } }, "required": ["type", "key"], @@ -15006,12 +15003,6 @@ "$ref": "#/components/schemas/Form.Value" } }, - "Form.Answer_1": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/Form.Value" - } - }, "Form.BooleanField": { "type": "object", "properties": { diff --git a/packages/schema/src/credential-legacy.ts b/packages/schema/src/credential-legacy.ts new file mode 100644 index 00000000000..e09ce0c8c44 --- /dev/null +++ b/packages/schema/src/credential-legacy.ts @@ -0,0 +1,29 @@ +export * as CredentialLegacy from "./credential-legacy.js" + +import { Schema, SchemaTransformation } from "effect" +import { Credential } from "./credential.js" +import { Form } from "./form.js" +import { optional } from "./schema.js" + +/** + * Storage and import compatibility for credentials written before v2.1 (not V1 contracts). Key credentials then kept + * their setup-form answers in `configuration`; they now live in `metadata`. Only decoders for stored rows and + * `auth export` files use these schemas, so the public credential contract never sees the old field. + */ +const Key = Schema.Struct({ ...Credential.Key.fields, configuration: optional(Form.Answer) }).pipe( + Schema.decodeTo( + Credential.Key, + SchemaTransformation.transform({ + // Form answers overrode metadata when both reached provider settings, so they keep precedence. + decode: ({ configuration, ...key }) => + configuration === undefined ? key : { ...key, metadata: { ...key.metadata, ...configuration } }, + encode: (key) => key, + }), + ), +) + +/** Decodes a stored or exported credential value of either shape into the current `Credential.Value`. */ +export const Value = Schema.Union([Credential.OAuth, Key, Credential.External]) + +/** Decodes an `auth export` entry of either shape into the current `Credential.Entry`. */ +export const Entry = Schema.Struct({ ...Credential.Entry.fields, value: Value }) diff --git a/packages/schema/src/credential.ts b/packages/schema/src/credential.ts index c7a0e1dbb85..279a129fe45 100644 --- a/packages/schema/src/credential.ts +++ b/packages/schema/src/credential.ts @@ -6,7 +6,6 @@ import { ephemeral, inventory } from "./event.js" import { IntegrationID, IntegrationMethodID } from "./integration-id.js" import { ascending } from "./identifier.js" import { NonNegativeInt, statics } from "./schema.js" -import { Form } from "./form.js" export const ID = Schema.String.pipe( Schema.brand("Credential.ID"), @@ -44,7 +43,6 @@ export const Key = Schema.Struct({ type: Schema.Literal("key"), key: Schema.String, metadata: optional(Schema.Record(Schema.String, Schema.Unknown)), - configuration: optional(Form.Answer), }).annotate({ identifier: "Credential.Key" }) /** References a credential source whose secrets and renewal are managed outside the credential store. */ diff --git a/packages/schema/test/credential-legacy.test.ts b/packages/schema/test/credential-legacy.test.ts new file mode 100644 index 00000000000..c4b7e9c6669 --- /dev/null +++ b/packages/schema/test/credential-legacy.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, test } from "bun:test" +import { Schema } from "effect" +import { Credential } from "../src/credential.js" +import { CredentialLegacy } from "../src/credential-legacy.js" + +const decode = Schema.decodeUnknownSync(CredentialLegacy.Value) +const legacy = { + type: "key", + key: "secret", + metadata: { imported: true, resourceName: "older" }, + configuration: { resourceName: "answered", accountId: "account" }, +} + +describe("CredentialLegacy", () => { + test("decodes key form answers written to configuration before v2.1 into metadata, keeping answers first", () => { + expect(decode(legacy)).toEqual({ + type: "key", + key: "secret", + metadata: { imported: true, resourceName: "answered", accountId: "account" }, + }) + expect(decode({ type: "key", key: "secret", configuration: { resourceName: "answered" } })).toEqual({ + type: "key", + key: "secret", + metadata: { resourceName: "answered" }, + }) + }) + + test("decodes current values and exported entries unchanged", () => { + const current = { type: "key", key: "secret", metadata: { resourceName: "answered" } } as const + expect(decode(current)).toEqual(current) + const external = { type: "external", methodID: "azure-cli", metadata: { resourceName: "answered" } } as const + expect(Schema.encodeSync(Credential.Value)(decode(external))).toEqual(external) + expect( + Schema.decodeUnknownSync(CredentialLegacy.Entry)({ + id: "cred_legacy", + integrationID: "azure", + label: "Work", + active: true, + value: legacy, + }).value, + ).toEqual(decode(legacy)) + }) + + test("rejects invalid legacy configuration", () => { + expect(() => decode({ type: "key", key: "secret", configuration: "answered" })).toThrow() + }) + + test("the public credential schema does not know configuration", () => { + expect(Schema.decodeUnknownSync(Credential.Value)(legacy)).toEqual({ + type: "key", + key: "secret", + metadata: { imported: true, resourceName: "older" }, + }) + }) +}) diff --git a/services/www/openapi.json b/services/www/openapi.json index 08275acbac3..7ef3b429b6c 100644 --- a/services/www/openapi.json +++ b/services/www/openapi.json @@ -14869,9 +14869,6 @@ }, "metadata": { "type": "object" - }, - "configuration": { - "$ref": "#/components/schemas/Form.Answer_1" } }, "required": ["type", "key"], @@ -15006,12 +15003,6 @@ "$ref": "#/components/schemas/Form.Value" } }, - "Form.Answer_1": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/Form.Value" - } - }, "Form.BooleanField": { "type": "object", "properties": { diff --git a/services/www/public/openapi.json b/services/www/public/openapi.json index 08275acbac3..7ef3b429b6c 100644 --- a/services/www/public/openapi.json +++ b/services/www/public/openapi.json @@ -14869,9 +14869,6 @@ }, "metadata": { "type": "object" - }, - "configuration": { - "$ref": "#/components/schemas/Form.Answer_1" } }, "required": ["type", "key"], @@ -15006,12 +15003,6 @@ "$ref": "#/components/schemas/Form.Value" } }, - "Form.Answer_1": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/Form.Value" - } - }, "Form.BooleanField": { "type": "object", "properties": {