Skip to content

Commit a74b173

Browse files
hkaltaiclaude
andcommitted
fix: an already-shared connection is not rewritten without --share, and every result after such a rewrite says who can use it
- the connection's own privacy is read from the connections list; anything but "private" (or none) needs --share before the in-place update - the refusal names update <id> --share or sync <id> --share - a secondary connection promoted to an entry's default needs --share - sync step labels, attach-only sync and failure results report the audience - CLI --share wiring and connect's JSON shared are tested Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 13328df commit a74b173

5 files changed

Lines changed: 171 additions & 27 deletions

File tree

‎packages/opencode/src/altimate/integrations/backend.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ export interface Connection {
3333
created_at?: string | null
3434
updated_at?: string | null
3535
is_owner?: boolean
36+
/** Who besides the owner can use it; anything but "private" (or none) counts as shared. */
37+
privacy?: string
3638
}
3739

3840
/** The login used for backend calls, or null when there is none. */

‎packages/opencode/src/altimate/integrations/core.ts‎

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,8 @@ export interface UpsertResult {
920920
created: boolean
921921
isValid: boolean
922922
message: string | null
923+
/** The updated connection was already shared, so whoever it is shared with gets the new credential. */
924+
shared?: true
923925
/** What happened to the workspace attach; absent when the connection was saved invalid. */
924926
workspace?: { attached: string; workspaceId?: string; kept?: true; shared?: true } | { notLinked: true } | { error: string }
925927
}
@@ -942,14 +944,17 @@ export const rejectionMessage = (res: Pick<UpsertResult, "created">) => (res.cre
942944
* Saves the credential as this tool's own connection: updated in place when it exists (matched on
943945
* integration and name among the caller's own connections), created otherwise.
944946
*/
945-
export async function upsertManaged(cfg: backend.BackendConfig, id: ProviderId, config: Record<string, unknown>, share = false): Promise<UpsertResult> {
947+
export async function upsertManaged(cfg: backend.BackendConfig, id: ProviderId, config: Record<string, unknown>, share = false, retry: "sync" | "update" = "sync"): Promise<UpsertResult> {
946948
const visible = await backend.listVisibleConnections(cfg)
947949
const existing = findManaged(backend.ownConnections(visible), id)
950+
// An update in place hands the new credential to everyone the connection is already shared with, so it needs the same consent as attaching to a shared workspace.
951+
const sharedConnection = existing != null && existing.privacy !== "private"
952+
if (sharedConnection && !share) throw new Error(SHARED_CONNECTION_REFUSAL(id, retry))
948953
const saved = existing
949954
? await backend.updateConnection(cfg, existing.id, { config })
950955
: await backend.createConnection(cfg, { name: managedName(id), integration_id: INTEGRATION_IDS[id], config })
951956
const isValid = saved.is_valid !== false
952-
const result: UpsertResult = { connectionId: saved.id, created: !existing, isValid, message: isValid ? null : rejectionMessage({ created: !existing }) }
957+
const result: UpsertResult = { connectionId: saved.id, created: !existing, isValid, message: isValid ? null : rejectionMessage({ created: !existing }), ...(sharedConnection ? { shared: true as const } : {}) }
953958
if (!isValid) return result
954959
return { ...result, workspace: await attachToBoundWorkspace(cfg, id, saved.id, visible.map((c) => c.id), share) }
955960
}
@@ -1005,6 +1010,15 @@ export function attachToIntegrations(
10051010
})
10061011
}
10071012

1013+
export const SHARED_CONNECTION_REFUSAL = (id: ProviderId, command: "sync" | "update" = "sync") =>
1014+
`the workspace connection is shared with other people, so updating it would let them use the new credential; nothing was changed. Run altimate integrations ${command} ${id} --share to update it`
1015+
1016+
/** Appended to what a sync or connect reports when other people can use the connection. */
1017+
export const SHARED_AUDIENCE = "; its members can use this connection"
1018+
export const SHARED_CONNECTION_AUDIENCE = "; the people it is shared with can use the new credential"
1019+
/** Added to a failure after a shared connection was rewritten, so the text says who already has the new credential. */
1020+
export const SHARED_REWRITE_NOTE = `The shared connection was updated${SHARED_CONNECTION_AUDIENCE}.`
1021+
10081022
export const SHARED_WORKSPACE_REFUSAL = (name: string, id: ProviderId) =>
10091023
`workspace "${name}" is shared, so attaching would let its members use this connection; it stays saved to your account only. Run altimate integrations sync ${id} --share to attach it`
10101024

@@ -1031,8 +1045,11 @@ async function attachToWorkspace(cfg: backend.BackendConfig, id: ProviderId, con
10311045
const next = attachToIntegrations(datamate.integrations, integrationId, connectionId, keys, live)
10321046
// Attaching widens the connection to the workspace's audience, so a workspace that does not say it is private (in this latest read) only gets it
10331047
// when asked. Members can use it only when the entry ends up naming it: a connection already there widens nothing more, and neither does an entry kept on another one.
1048+
const isDefault = (entries: backend.DatamateIntegrationEntry[]) => entries.some((e) => String(e.id) === integrationId && String(e.connection_id ?? "") === conn)
10341049
const shared = datamate.privacy !== "private" && usesThis(next)
1035-
if (shared && !share && !usesThis(datamate.integrations)) throw new Error(SHARED_WORKSPACE_REFUSAL(datamate.name, id))
1050+
// Already there means already exposed, unless this write promotes it from a secondary connection to the entry's default.
1051+
const alreadyThere = usesThis(datamate.integrations) && (isDefault(datamate.integrations) || !isDefault(next))
1052+
if (shared && !share && !alreadyThere) throw new Error(SHARED_WORKSPACE_REFUSAL(datamate.name, id))
10361053
await backend.updateDatamateIntegrations(cfg, datamateId, next)
10371054
const entry = next.find((e) => String(e.id) === integrationId)
10381055
return { kept: entry?.connection_id != null && String(entry.connection_id) !== conn, shared }
@@ -1089,14 +1106,15 @@ async function syncReal(
10891106
steps.push({ label: l, ok: true })
10901107
onStep?.(l, true)
10911108
}
1092-
const reportWorkspace = (w: NonNullable<UpsertResult["workspace"]>): SyncOutcome => {
1093-
if ("error" in w) return { id, result: "failed", reason: ATTACH_FAILED_PREFIX + w.error, steps }
1094-
if ("attached" in w) step(w.kept ? `Kept the workspace's existing connection in ${workspaceLabel(w.attached, w.workspaceId)}` : `Attached to ${workspaceLabel(w.attached, w.workspaceId)}`)
1109+
const reportWorkspace = (w: NonNullable<UpsertResult["workspace"]>, sharedConnection = false): SyncOutcome => {
1110+
// A shared connection that was rewritten stays reported as shared even when the attach after it fails.
1111+
if ("error" in w) return { id, result: "failed", reason: ATTACH_FAILED_PREFIX + w.error, steps, ...(sharedConnection ? { shared: true as const } : {}) }
1112+
if ("attached" in w) step(`${w.kept ? `Kept the workspace's existing connection in ${workspaceLabel(w.attached, w.workspaceId)}` : `Attached to ${workspaceLabel(w.attached, w.workspaceId)}`}${w.shared ? SHARED_AUDIENCE : ""}`)
10951113
else {
10961114
steps.push({ label: NOT_LINKED_LABEL, ok: false })
10971115
onStep?.(NOT_LINKED_LABEL, false)
10981116
}
1099-
return { id, result: "synced", steps, ...("attached" in w && w.shared ? { shared: true as const } : {}) }
1117+
return { id, result: "synced", steps, ...(sharedConnection || ("attached" in w && w.shared) ? { shared: true as const } : {}) }
11001118
}
11011119
if ("reason" in collected) {
11021120
// Nothing local to upload, but a connection already in the workspace may still need attaching to it: the one this machine saved, or one it has no record of.
@@ -1118,7 +1136,7 @@ async function syncReal(
11181136
if (!found) return { id, result: "skipped", reason: known == null ? collected.reason : REMOVED_NOTE, steps: [] }
11191137
if (found.is_valid === false) return { id, result: "skipped", reason: INVALID_IN_WORKSPACE, steps: [] }
11201138
step("Connection already in the workspace")
1121-
return reportWorkspace(await attachToBoundWorkspace(cfg, id, found.id, visible.map((c) => c.id), share))
1139+
return reportWorkspace(await attachToBoundWorkspace(cfg, id, found.id, visible.map((c) => c.id), share), found.privacy !== "private")
11221140
})
11231141
} catch (e) {
11241142
return { id, result: "failed", reason: e instanceof Error ? e.message : String(e), steps }
@@ -1158,9 +1176,9 @@ async function syncReal(
11581176
warning = REMOVE_FAILED_WARNING(e instanceof Error ? e.message : String(e))
11591177
}
11601178
}
1161-
return { id, result: "failed", reason: rejectionMessage(res) + warning, steps }
1179+
return { id, result: "failed", reason: rejectionMessage(res) + warning + (res.shared ? ` ${SHARED_REWRITE_NOTE}` : ""), steps, ...(res.shared ? { shared: true as const } : {}) }
11621180
}
1163-
step(res.created ? "Created connection" : "Updated connection")
1181+
step(res.created ? "Created connection" : `Updated connection${res.shared ? SHARED_CONNECTION_AUDIENCE : ""}`)
11641182
try {
11651183
await updateStore((next) => {
11661184
next.providers[id] = {
@@ -1178,7 +1196,7 @@ async function syncReal(
11781196
}
11791197
})
11801198
} catch (e) {
1181-
return { id, result: "failed", reason: RECORD_WRITE_FAILED(e instanceof Error ? e.message : String(e), "Run sync again"), steps }
1199+
return { id, result: "failed", reason: RECORD_WRITE_FAILED(e instanceof Error ? e.message : String(e), "Run sync again") + (res.shared ? ` ${SHARED_REWRITE_NOTE}` : ""), steps, ...(res.shared ? { shared: true as const } : {}) }
11821200
}
11831201
// The connection is in the workspace and accepted: no secret stays on this machine, the same as when it is connected there directly.
11841202
try {
@@ -1188,7 +1206,7 @@ async function syncReal(
11881206
// The workspace holds the connection and the record says so; only the local cleanup is left to redo, which running sync for this provider does.
11891207
steps.push({ label: `${LOCAL_CLEANUP_FAILED_PREFIX}${e instanceof Error ? e.message : String(e)}. Run altimate integrations sync ${id} to remove it.`, ok: false })
11901208
}
1191-
return reportWorkspace(res.workspace ?? { notLinked: true })
1209+
return reportWorkspace(res.workspace ?? { notLinked: true }, res.shared === true)
11921210
})
11931211
} catch (e) {
11941212
return { id, result: "failed", reason: e instanceof Error ? e.message : String(e), steps }

‎packages/opencode/src/altimate/integrations/credentials.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -747,14 +747,17 @@ export async function connectCredentials(opts: CredentialOptions): Promise<Crede
747747
const config: Record<string, unknown> = {}
748748
for (const f of r.def.fields) if (r.values[f.name]) config[f.name] = r.values[f.name]
749749
if (check.expiresAt) config.expires_at = check.expiresAt
750+
// Set once a shared connection was rewritten, so a later failure still says who already has the new credential.
751+
let sharedRewrite = false
750752
try {
751753
// The blocked check and the upload share one lock with Keep local, so a move to this machine cannot interleave with an upload.
752754
return await core.withLock(async (): Promise<CredentialResult> => {
753755
if (!core.sameRecord(core.loadStore().providers[id], rec)) return local({ status: "failed", sync: syncState(), message: CHANGED_WHILE_CONNECTING })
754756
if (core.isBlocked(id)) return local({ status: "failed", sync: syncState(), message: "Sync is blocked for this provider, kept local." })
755-
const res = await core.upsertManaged(cfg, id, core.withVariant(id, r.variant, config), opts.share === true)
757+
const res = await core.upsertManaged(cfg, id, core.withVariant(id, r.variant, config), opts.share === true, "update")
758+
sharedRewrite = res.shared === true
756759
if (!res.isValid) {
757-
const rejected = (sync: "synced" | "local"): CredentialResult => ({ ...base, provider: id, status: "rejected", sync, account: check.account, expiresAt: common.expiresAt ?? null, message: core.rejectionMessage(res) })
760+
const rejected = (sync: "synced" | "local"): CredentialResult => ({ ...base, provider: id, status: "rejected", sync, account: check.account, expiresAt: common.expiresAt ?? null, message: core.rejectionMessage(res) + (res.shared ? ` ${core.SHARED_REWRITE_NOTE}` : ""), ...(res.shared ? { shared: true as const } : {}) })
758761
// An existing connection was updated in place and cannot be reverted, so it stays marked rejected for update to fix; the local copy of a local credential is untouched.
759762
if (!res.created && !(rec?.registered && !rec.synced)) {
760763
await record(true, { connectionId: res.connectionId, rejected: true })
@@ -780,7 +783,7 @@ export async function connectCredentials(opts: CredentialOptions): Promise<Crede
780783
try {
781784
await record(true, { connectionId: res.connectionId })
782785
} catch (e) {
783-
return { ...base, provider: id, status: "failed", sync: "synced", account: check.account, expiresAt: common.expiresAt ?? null, message: core.RECORD_WRITE_FAILED(e instanceof Error ? e.message : String(e), "Connect again") }
786+
return { ...base, provider: id, status: "failed", sync: "synced", account: check.account, expiresAt: common.expiresAt ?? null, message: [core.RECORD_WRITE_FAILED(e instanceof Error ? e.message : String(e), "Connect again"), res.shared ? core.SHARED_REWRITE_NOTE : null].filter(Boolean).join(" "), ...(res.shared ? { shared: true as const } : {}) }
784787
}
785788
let leftover: string | null = null
786789
try {
@@ -790,12 +793,15 @@ export async function connectCredentials(opts: CredentialOptions): Promise<Crede
790793
} catch (e) {
791794
leftover = `Saved to the workspace, but the local copy of the credential could not be removed: ${e instanceof Error ? e.message : String(e)}`
792795
}
793-
const message = [workspaceNote(res.workspace), leftover].filter(Boolean).join(" ") || null
794-
const shared = res.workspace && "attached" in res.workspace && res.workspace.shared ? { shared: true as const } : {}
796+
const sharedNote = res.shared ? `Updated the shared connection${core.SHARED_CONNECTION_AUDIENCE}.` : null
797+
const message = [sharedNote, workspaceNote(res.workspace), leftover].filter(Boolean).join(" ") || null
798+
const shared = res.shared || (res.workspace && "attached" in res.workspace && res.workspace.shared) ? { shared: true as const } : {}
795799
return { ...base, provider: id, status: "connected", sync: "synced", account: check.account, expiresAt: common.expiresAt ?? null, message, ...shared }
796800
})
797801
} catch (e) {
798-
return local({ status: "failed", sync: syncState(), message: e instanceof Error ? e.message : String(e) })
802+
const message = e instanceof Error ? e.message : String(e)
803+
if (sharedRewrite) return { ...local({ status: "failed", sync: syncState(), message: `${message} ${core.SHARED_REWRITE_NOTE}` }), shared: true }
804+
return local({ status: "failed", sync: syncState(), message })
799805
}
800806
}
801807

@@ -804,7 +810,7 @@ function workspaceNote(w: core.UpsertResult["workspace"]): string | null {
804810
if ("error" in w) return core.ATTACH_FAILED_PREFIX + w.error
805811
if ("notLinked" in w) return core.NOT_LINKED_LABEL
806812
const where = workspaceLabel(w.attached, w.workspaceId)
807-
const audience = w.shared ? `; its members can use this connection` : ""
813+
const audience = w.shared ? core.SHARED_AUDIENCE : ""
808814
return `${w.kept ? `Kept the workspace's existing connection in ${where}` : `Attached to ${where}`}${audience}`
809815
}
810816

‎packages/opencode/src/cli/cmd/integrations.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ const DetectCommand = cmd({
9999
})
100100

101101
/** Who can use a synced connection: only the user, unless it was attached to a workspace that is not private. */
102-
export const syncedTo = (o: Pick<core.SyncOutcome, "shared">) => `synced to workspace${o.shared ? ", shared with its members" : " (private)"}`
102+
export const syncedTo = (o: Pick<core.SyncOutcome, "shared">) => `synced to workspace${o.shared ? ", shared with other people" : " (private)"}`
103103

104104
function renderSync(o: core.SyncOutcome) {
105105
const name = core.PROVIDER_NAMES[o.id]
@@ -132,7 +132,7 @@ async function runSync(ids: ProviderId[], asJson: boolean, skipSynced = false, s
132132
/** A run over every provider, or one provider asked to keep a saved connection, never overwrites a connection already synced to the workspace. */
133133
export const skipsSynced = (args: { provider?: string; all?: boolean; keepSynced?: boolean }) => !args.provider || Boolean(args.keepSynced)
134134

135-
const SyncCommand = cmd({
135+
export const SyncCommand = cmd({
136136
command: "sync [provider]",
137137
describe: "push detected and connected credentials to the workspace",
138138
builder: (yargs: Argv) =>
@@ -234,7 +234,7 @@ const credentialOptions = (yargs: Argv) =>
234234
.option("json", jsonOption)
235235
.option("variant", variantOption)
236236

237-
const ConnectCommand = cmd({
237+
export const ConnectCommand = cmd({
238238
command: "connect <provider>",
239239
describe: "connect a provider with its own credentials",
240240
builder: (yargs: Argv) =>

0 commit comments

Comments
 (0)