diff --git a/rust/contracts/github.md b/rust/contracts/github.md index 10d553b6..cf792216 100644 --- a/rust/contracts/github.md +++ b/rust/contracts/github.md @@ -88,8 +88,21 @@ Supported operations are `deviceCode`, `deviceToken`, `currentUser`, `listBranches`, `compareBranches`, `listPullRequests`, `getPullRequest`, `createPullRequest`, `updatePullRequest`, `listPullRequestFiles`, `listPullRequestComments`, `createPullRequestComment`, `createPullRequestReview`, `mergePullRequest`, -`updatePullRequestMetadata`, `listReviewComments`, `listCheckRuns`, and -`getCombinedStatus`. +`updatePullRequestMetadata`, `listReviewComments`, `listCheckRuns`, +`getCombinedStatus`, `latestCommit`, and `listReleases`. + +`latestCommit` and `listReleases` read public data, so their plans set +`requiresAuthentication: false` and work without a signed-in account. +`latestCommit` (`GET /repos/{owner}/{name}/commits?sha={ref}&per_page=1`) needs +`ref` (`HEAD`, a branch or tag name, or a `refs/...` name; whitespace, `..`, a +leading `-` and the revision operators `~ ^ : ? * [ \` are refused) and returns +`{ sha }`, the ref's newest commit as a full lowercase SHA-1 or SHA-256 name. +Hosts use it to pin a marketplace index to a commit, because raw file URLs of a +branch are cached for minutes (see `plugins.marketplace.resolveSource`). +`listReleases` (`GET /repos/{owner}/{name}/releases`, first page of 20) returns +`[{ tagName, name, body, publishedAt, prerelease, url }]` newest publication +first, ties ordered by tag; drafts are dropped, an empty title is `null` and +missing notes are `""`. `listReviewComments` (`GET /repos/{owner}/{name}/pulls/{number}/comments`, first page of 100) needs `pullNumber` and returns a flat array of diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 4a6a2582..fdb83f6d 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5438,8 +5438,11 @@ archives and pass the parsed JSON. `validateIndex` accepts `{ index, sourceKind: "official" | "thirdParty", platform, hostCapabilities? }` and returns `{ status: "ok", index: { plugins, rejected } }` with per-entry `availability`; a listed version is available only when its `pluginAPIVersion` -is one Core supports and every capability it requires is in `hostCapabilities`; `resolveSource` accepts `{ url }` and returns -`{ status: "ok", source: { indexURL, recommendationsURL, repository, displayName } }`; +is one Core supports and every capability it requires is in `hostCapabilities`; `resolveSource` accepts `{ url, commit? }` and returns +`{ status: "ok", source: { indexURL, recommendationsURL, repository, displayName, revision, pinned? } }`, +where `revision` names the GitHub repository and ref a host may look the newest commit of +(`github.latestCommit`) and `pinned` holds the same URLs at the `commit` passed back; +`indexURL` remains the source identity; `installReview` accepts `{ manifest, expectedID?, expectedVersion?, approvedPrograms?, hostCapabilities? }` and returns `{ status: "ok", review: { id, version, permissions, programs, newPrograms } }`; diff --git a/rust/crates/core/src/tests/github.rs b/rust/crates/core/src/tests/github.rs index 10c2a7a6..fcf52561 100644 --- a/rust/crates/core/src/tests/github.rs +++ b/rust/crates/core/src/tests/github.rs @@ -394,3 +394,127 @@ fn request_plan_and_normalize_review_comment_threads() { assert!(response["data"][1]["line"].is_null()); assert_eq!(response["data"][1]["createdAt"], "2026-11-01T00:05:00Z"); } + +#[test] +fn request_plan_reads_the_newest_commit_and_releases_without_credentials() { + let response = execute( + "github.requestPlan", + json!({ + "operation": "latestCommit", + "repository": {"owner": "example", "name": "lithe-plugins"}, + "ref": "refs/heads/release" + }), + ); + assert_eq!(response["ok"], true, "{response:?}"); + assert_eq!(response["data"]["host"], "api"); + assert_eq!(response["data"]["method"], "GET"); + assert_eq!( + response["data"]["path"], + "/repos/example/lithe-plugins/commits" + ); + assert_eq!( + response["data"]["query"], + json!({"per_page": "1", "sha": "refs/heads/release"}) + ); + assert_eq!(response["data"]["requiresAuthentication"], false); + + let response = execute( + "github.requestPlan", + json!({ + "operation": "listReleases", + "repository": {"owner": "example", "name": "lithe-plugin-rust"} + }), + ); + assert_eq!(response["ok"], true, "{response:?}"); + assert_eq!( + response["data"]["path"], + "/repos/example/lithe-plugin-rust/releases" + ); + assert_eq!(response["data"]["query"], json!({"per_page": "20"})); + assert_eq!(response["data"]["requiresAuthentication"], false); + + for git_ref in ["", "main..x", "-x", "main x", "HEAD~1", "a:b"] { + let response = execute( + "github.requestPlan", + json!({ + "operation": "latestCommit", + "repository": {"owner": "example", "name": "lithe-plugins"}, + "ref": git_ref + }), + ); + assert_eq!(response["ok"], false, "{git_ref}: {response:?}"); + assert_eq!(response["error"]["code"], "invalid_request"); + } +} + +#[test] +fn normalizes_the_newest_commit_to_a_full_lowercase_object_name() { + let sha = "0123456789ABCDEF0123456789ABCDEF01234567"; + let response = execute( + "github.normalizeResponse", + json!({ + "operation": "latestCommit", + "status": 200, + "body": json!([{"sha": sha, "commit": {"message": "x"}}]).to_string() + }), + ); + assert_eq!(response["ok"], true, "{response:?}"); + assert_eq!(response["data"], json!({"sha": sha.to_ascii_lowercase()})); + + for body in [json!([]), json!([{"sha": "0123abc"}]), json!({"sha": sha})] { + let response = execute( + "github.normalizeResponse", + json!({"operation": "latestCommit", "status": 200, "body": body.to_string()}), + ); + assert_eq!(response["ok"], false, "{body}: {response:?}"); + assert_eq!(response["error"]["code"], "parse_failed"); + } +} + +#[test] +fn normalizes_releases_newest_first_without_drafts() { + let body = json!([ + { + "tag_name": "v0.1.0", "name": "v0.1.0", "body": "First.", "draft": false, + "prerelease": true, "published_at": "2026-11-21T08:00:00Z", + "html_url": "https://github.com/example/p/releases/tag/v0.1.0" + }, + { + "tag_name": "v0.2.0", "name": null, "body": null, "draft": true, + "prerelease": false, "published_at": null, + "html_url": "https://github.com/example/p/releases/tag/untagged" + }, + { + "tag_name": "v0.1.1", "name": " ", "body": "## Fixes\n- One.", "draft": false, + "prerelease": false, "published_at": "2026-11-22T13:31:49Z", + "html_url": "https://github.com/example/p/releases/tag/v0.1.1" + } + ]); + let response = execute( + "github.normalizeResponse", + json!({"operation": "listReleases", "status": 200, "body": body.to_string()}), + ); + assert_eq!(response["ok"], true, "{response:?}"); + assert_eq!( + response["data"], + json!([ + { + "tagName": "v0.1.1", "name": null, "body": "## Fixes\n- One.", + "publishedAt": "2026-11-22T13:31:49Z", "prerelease": false, + "url": "https://github.com/example/p/releases/tag/v0.1.1" + }, + { + "tagName": "v0.1.0", "name": "v0.1.0", "body": "First.", + "publishedAt": "2026-11-21T08:00:00Z", "prerelease": true, + "url": "https://github.com/example/p/releases/tag/v0.1.0" + } + ]) + ); + + let response = execute( + "github.normalizeResponse", + json!({"operation": "listReleases", "status": 404, "body": "{\"message\":\"Not Found\"}"}), + ); + assert_eq!(response["ok"], false, "{response:?}"); + assert_eq!(response["error"]["code"], "invalid_request"); +} diff --git a/rust/crates/core/src/tests/marketplace_plugins.rs b/rust/crates/core/src/tests/marketplace_plugins.rs index affb21e6..c28a0574 100644 --- a/rust/crates/core/src/tests/marketplace_plugins.rs +++ b/rust/crates/core/src/tests/marketplace_plugins.rs @@ -197,7 +197,11 @@ fn source_url_fixtures_resolve_to_expected_index_urls() { let cases = json_file(SOURCE_URLS); for case in cases["cases"].as_array().unwrap() { let input = case["input"].as_str().unwrap(); - let outcome = resolve_source_command(json!({ "url": input })).unwrap(); + let mut payload = json!({ "url": input }); + if let Some(commit) = case.get("commit") { + payload["commit"] = commit.clone(); + } + let outcome = resolve_source_command(payload).unwrap(); if let Some(code) = case.get("expectedCode") { assert_eq!(outcome["status"], "rejected", "{input}: {outcome}"); assert_eq!(&outcome["error"]["code"], code, "{input}: {outcome}"); diff --git a/rust/crates/github/src/lib.rs b/rust/crates/github/src/lib.rs index 5b1311e2..b1f8c77e 100644 --- a/rust/crates/github/src/lib.rs +++ b/rust/crates/github/src/lib.rs @@ -15,6 +15,11 @@ const DEVICE_EXPIRATION_MAX_SECONDS: u64 = 86_400; // Once an interval reaches the maximum lifetime, no further poll can occur. const DEVICE_INTERVAL_MAX_SECONDS: u64 = DEVICE_EXPIRATION_MAX_SECONDS; const DEVICE_SLOW_DOWN_SECONDS: u64 = 5; +// The changelog shows the newest releases; one bounded page keeps the +// anonymous request small. +const RELEASE_PAGE_SIZE: u64 = 20; +// A Git ref name is bounded like a file name; GitHub refuses longer ones. +const GIT_REF_MAX_BYTES: usize = 255; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] @@ -200,6 +205,9 @@ pub struct RequestPlanRequest { /// Full commit SHA required by commit-status operations. #[serde(default)] pub commit: Option, + /// Branch, tag or `HEAD` whose newest commit `latestCommit` looks up. + #[serde(default, rename = "ref")] + pub git_ref: Option, /// OAuth application's public client identifier. #[serde(default)] pub client_id: Option, @@ -452,6 +460,24 @@ pub struct GitHubComparison { pub files: Vec, } +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +/// Normalized published release of a repository, as a changelog lists it. +pub struct GitHubRelease { + /// Git tag the release was published from. + pub tag_name: String, + /// Release title; null when the author left it empty. + pub name: Option, + /// Markdown release notes; empty when the author wrote none. + pub body: String, + /// ISO-8601 publication timestamp. + pub published_at: Option, + /// Whether the author marked the release as a pre-release. + pub prerelease: bool, + /// Browser URL of the release page. + pub url: String, +} + /// Parses one supported GitHub remote URL. pub fn parse_remote(request: ParseRemoteRequest) -> Result { let value = request.remote_url.trim().trim_end_matches('/'); @@ -634,6 +660,32 @@ pub fn request_plan(request: RequestPlanRequest) -> Result { + let repository = repository_path(&request)?; + let git_ref = git_ref(&request)?; + query.insert("sha".to_string(), git_ref.to_string()); + query.insert("per_page".to_string(), "1".to_string()); + ( + GitHubHost::Api, + "GET", + format!("/repos/{repository}/commits"), + None, + false, + ) + } + "listReleases" => { + let repository = repository_path(&request)?; + query.insert("per_page".to_string(), RELEASE_PAGE_SIZE.to_string()); + ( + GitHubHost::Api, + "GET", + format!("/repos/{repository}/releases"), + None, + false, + ) + } "listPullRequestComments" => { let repository = repository_path(&request)?; let number = pull_number(&request)?; @@ -744,6 +796,8 @@ pub fn normalize_response(request: NormalizeResponseRequest) -> Result normalize_review_comment_list(value), "listCheckRuns" => normalize_check_run_list(value), "getCombinedStatus" => normalize_combined_status(value), + "latestCommit" => normalize_latest_commit(value), + "listReleases" => normalize_release_list(value), "createPullRequestComment" => { Ok(serde_json::to_value(normalize_comment(&value)?).expect("comment encodes")) } @@ -766,6 +820,24 @@ fn commit_path(request: &RequestPlanRequest) -> Result<(String, String), CoreErr Ok((repository, commit.to_string())) } +/// The ref travels as a query value, so it is only bounded here; GitHub +/// answers an unknown ref with an error. +fn git_ref(request: &RequestPlanRequest) -> Result<&str, CoreError> { + let value = required_text(request.git_ref.as_deref(), "ref")?; + let valid = value.len() <= GIT_REF_MAX_BYTES + && !value.contains("..") + && !value.starts_with('-') + && value.chars().all(|character| { + character.is_ascii_graphic() + && !matches!(character, '~' | '^' | ':' | '?' | '*' | '[' | '\\') + }); + if valid { + Ok(value) + } else { + Err(invalid_field("ref")) + } +} + fn repository_path(request: &RequestPlanRequest) -> Result { request .repository @@ -1097,6 +1169,59 @@ fn normalize_combined_status(value: Value) -> Result { Ok(serde_json::to_value(checks).expect("combined status encodes")) } +/// The commit list is asked for one entry: the ref's newest commit. A full +/// SHA-1 or SHA-256 object name is required, because the caller builds an +/// immutable file URL from it. +fn normalize_latest_commit(value: Value) -> Result { + let first = value + .as_array() + .and_then(|commits| commits.first()) + .ok_or_else(parse_shape_error)?; + let sha = text(object(first)?, "sha")?; + if !matches!(sha.len(), 40 | 64) || !sha.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(parse_shape_error()); + } + Ok(json!({ "sha": sha.to_ascii_lowercase() })) +} + +/// Drafts are dropped (an anonymous reader never sees them). The newest +/// publication comes first; equal timestamps fall back to the tag so the +/// order does not depend on GitHub's. +fn normalize_release_list(value: Value) -> Result { + let mut releases = Vec::new(); + for value in value.as_array().ok_or_else(parse_shape_error)? { + let object = object(value)?; + if object.get("draft").and_then(Value::as_bool) == Some(true) { + continue; + } + let optional = |key: &str| { + object + .get(key) + .and_then(Value::as_str) + .filter(|value| !value.trim().is_empty()) + .map(str::to_string) + }; + releases.push(GitHubRelease { + tag_name: text(object, "tag_name")?.to_string(), + name: optional("name"), + body: optional("body").unwrap_or_default(), + published_at: optional("published_at"), + prerelease: object + .get("prerelease") + .and_then(Value::as_bool) + .unwrap_or(false), + url: text(object, "html_url")?.to_string(), + }); + } + releases.sort_by(|left, right| { + right + .published_at + .cmp(&left.published_at) + .then_with(|| right.tag_name.cmp(&left.tag_name)) + }); + Ok(serde_json::to_value(releases).expect("release list encodes")) +} + fn normalize_file_list(value: Value) -> Result { let array = value.as_array().ok_or_else(parse_shape_error)?; let mut files = array diff --git a/rust/crates/plugin-marketplace/src/lib.rs b/rust/crates/plugin-marketplace/src/lib.rs index 11908277..5a05b8e8 100644 --- a/rust/crates/plugin-marketplace/src/lib.rs +++ b/rust/crates/plugin-marketplace/src/lib.rs @@ -481,7 +481,25 @@ fn availability( // MARK: Source resolution /// Resolves what a user pasted into the index URL Lithe will fetch. -fn resolve_source(input: &str) -> Validation { +/// +/// A GitHub-hosted index also reports `revision`, the repository and the ref +/// its URL follows. raw.githubusercontent.com caches a branch URL for minutes, +/// so a host that looks the ref's newest commit up passes it back as `commit` +/// and fetches `pinned`, the same files at that commit, which no cache serves +/// stale. `indexURL` stays the source's identity either way. +fn resolve_source(input: &str, commit: Option<&str>) -> Validation { + let commit = commit + .map(|commit| { + is_object_name(commit) + .then(|| commit.to_ascii_lowercase()) + .ok_or_else(|| { + PluginRejection::new( + "plugin.source.commitInvalid", + "The commit must be a full hexadecimal object name.", + ) + }) + }) + .transpose()?; let url = parse_https(input.trim()).ok_or_else(|| { PluginRejection::new( "plugin.source.invalid", @@ -494,7 +512,7 @@ fn resolve_source(input: &str) -> Validation { .map(|segments| segments.filter(|segment| !segment.is_empty()).collect()) .unwrap_or_default(); - if host == "github.com" || host == "www.github.com" { + let (mut source, file) = if host == "github.com" || host == "www.github.com" { let repository = segments .first() .zip(segments.get(1)) @@ -505,18 +523,24 @@ fn resolve_source(input: &str) -> Validation { "The GitHub URL does not name a repository.", ) })?; - let index_url = match &segments[2..] { - [] => format!( - "https://raw.githubusercontent.com/{}/{}/HEAD/{REPOSITORY_INDEX_FILE_NAME}", - repository.owner, repository.name + let (index_url, file) = match &segments[2..] { + [] => ( + format!( + "https://raw.githubusercontent.com/{}/{}/HEAD/{REPOSITORY_INDEX_FILE_NAME}", + repository.owner, repository.name + ), + github_file(&repository, &["HEAD", REPOSITORY_INDEX_FILE_NAME]), ), // A file page (`/blob//`) maps one-to-one to its raw // URL, whatever slashes the ref contains. - ["blob", rest @ ..] if rest.len() >= 2 => format!( - "https://raw.githubusercontent.com/{}/{}/{}", - repository.owner, - repository.name, - rest.join("/") + ["blob", rest @ ..] if rest.len() >= 2 => ( + format!( + "https://raw.githubusercontent.com/{}/{}/{}", + repository.owner, + repository.name, + rest.join("/") + ), + github_file(&repository, rest), ), _ => { return Err(PluginRejection::new( @@ -525,29 +549,98 @@ fn resolve_source(input: &str) -> Validation { )) } }; - return Ok(json!({ - "indexURL": index_url, - "recommendationsURL": sibling_recommendations_url(&index_url), - "repository": repository.web_url(), - "displayName": format!("{}/{}", repository.owner, repository.name), - })); + ( + json!({ + "indexURL": index_url, + "recommendationsURL": sibling_recommendations_url(&index_url), + "repository": repository.web_url(), + "displayName": format!("{}/{}", repository.owner, repository.name), + }), + file, + ) + } else { + let mut index_url = url.clone(); + index_url.set_fragment(None); + let repository = if host == "raw.githubusercontent.com" && segments.len() >= 4 { + repository_from_parts(segments[0], segments[1]) + } else { + None + }; + // A query (such as a private file's token) would be lost by pinning. + let file = repository + .as_ref() + .filter(|_| url.query().is_none()) + .and_then(|repository| github_file(repository, &segments[2..])); + ( + json!({ + "indexURL": index_url.as_str(), + "recommendationsURL": sibling_recommendations_url(index_url.as_str()), + "repository": repository.as_ref().map(GitHubRepository::web_url), + "displayName": repository + .map(|repository| format!("{}/{}", repository.owner, repository.name)) + .unwrap_or(host), + }), + file, + ) + }; + source["revision"] = file.as_ref().map_or(Value::Null, |file| { + json!({ + "repository": { "owner": file.repository.owner, "name": file.repository.name }, + "ref": file.git_ref, + }) + }); + if let Some(commit) = commit { + source["pinned"] = file.as_ref().map_or(Value::Null, |file| { + let index_url = format!( + "https://raw.githubusercontent.com/{}/{}/{commit}/{}", + file.repository.owner, file.repository.name, file.path + ); + json!({ + "commit": commit, + "recommendationsURL": sibling_recommendations_url(&index_url), + "indexURL": index_url, + }) + }); } + Ok(source) +} - let mut index_url = url.clone(); - index_url.set_fragment(None); - let repository = if host == "raw.githubusercontent.com" && segments.len() >= 4 { - repository_from_parts(segments[0], segments[1]) - } else { - None +/// One file of a GitHub repository as a branch or tag URL names it. +struct GitHubFile { + repository: GitHubRepository, + /// `HEAD`, a branch or tag name, or `refs/heads/` / `refs/tags/`. + git_ref: String, + /// Repository-relative path, still percent-encoded as in the URL. + path: String, +} + +/// Splits `/` of a raw URL. A short ref is its first segment: a +/// branch whose name contains `/` is only found when written as +/// `refs/heads/`; otherwise the commit lookup or the pinned fetch fails +/// and the host keeps the unpinned URL. A URL already at a commit, or a ref +/// spelled with escapes, has nothing to pin. +fn github_file(repository: &GitHubRepository, rest: &[&str]) -> Option { + let ref_len = match rest { + ["refs", "heads" | "tags", ..] => 3, + _ => 1, }; - Ok(json!({ - "indexURL": index_url.as_str(), - "recommendationsURL": sibling_recommendations_url(index_url.as_str()), - "repository": repository.as_ref().map(GitHubRepository::web_url), - "displayName": repository - .map(|repository| format!("{}/{}", repository.owner, repository.name)) - .unwrap_or(host), - })) + if rest.len() <= ref_len { + return None; + } + let git_ref = rest[..ref_len].join("/"); + if is_object_name(&git_ref) || git_ref.contains('%') { + return None; + } + Some(GitHubFile { + repository: repository.clone(), + git_ref, + path: rest[ref_len..].join("/"), + }) +} + +/// A full SHA-1 or SHA-256 Git object name. +fn is_object_name(value: &str) -> bool { + matches!(value.len(), 40 | 64) && value.bytes().all(|byte| byte.is_ascii_hexdigit()) } /// Derives the companion `lithe-plugin-recommendations.json` URL in the same @@ -773,6 +866,9 @@ struct ValidateIndexPayload { #[serde(rename_all = "camelCase")] struct ResolveSourcePayload { url: String, + /// Newest commit of `source.revision`, looked up by the host. + #[serde(default)] + commit: Option, } #[derive(Deserialize)] @@ -1185,11 +1281,15 @@ pub fn validate_index_command(payload: Value) -> Result { } /// `plugins.marketplace.resolveSource`: returns `{status: "ok", source: -/// {indexURL, repository?, displayName}}`. +/// {indexURL, recommendationsURL, repository, displayName, revision}}`, plus +/// `pinned` when the payload carries a `commit`. pub fn resolve_source_command(payload: Value) -> Result { let payload: ResolveSourcePayload = decode_payload(payload, "plugins.marketplace.resolveSource")?; - Ok(outcome("source", resolve_source(&payload.url))) + Ok(outcome( + "source", + resolve_source(&payload.url, payload.commit.as_deref()), + )) } /// `plugins.marketplace.installReview`: returns `{status: "ok", review: diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 9a1b72c9..8149b773 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -1878,6 +1878,21 @@ every product shows the same catalog and the same install review. It also returns `recommendationsURL`, the sibling `lithe-plugin-recommendations.json` beside `indexURL` (query and fragment cleared). Plain http, embedded credentials, and other GitHub pages are refused with `plugin.source.invalid`. +- raw.githubusercontent.com serves a branch URL from a cache for minutes, so a + just-merged index can look unchanged. For a GitHub-hosted index without a + query, `resolveSource` also returns `revision: { repository: { owner, name }, + ref }`, the ref the URL follows (`HEAD`, the first path segment, or + `refs/heads/` / `refs/tags/`); it is null for other sources and + for a URL already at a full commit. A host may look the ref's newest commit + up with the GitHub `latestCommit` operation and call `resolveSource` again + with `commit`, a full SHA-1 or SHA-256 object name (otherwise + `plugin.source.commitInvalid`); the answer then adds `pinned: { commit, + indexURL, recommendationsURL }`, the same files at that commit, or null when + nothing can be pinned. The host fetches the pinned URLs and falls back to the + unpinned ones when the lookup or the pinned fetch fails. `indexURL` stays the + source's identity: a host records and compares that one, never the pinned + URL. A branch whose name contains `/` is only pinned when written as + `refs/heads/`. - Hosts cache fetched indexes in platform cache or application-support storage, never inside the installation. diff --git a/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json b/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json index 309fe754..5e09ad67 100644 --- a/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json +++ b/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json @@ -1,17 +1,23 @@ { "schemaVersion": 1, - "description": "plugins.marketplace.resolveSource inputs and the index and companion recommendations URLs every host must fetch, or the rejection code.", + "description": "plugins.marketplace.resolveSource inputs and the index and companion recommendations URLs every host must fetch, the GitHub repository and ref a host may look the newest commit of, the same files pinned at a commit the host passes back, or the rejection code.", "cases": [ - { "input": "https://github.com/example/lithe-plugins", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, - { "input": " https://github.com/example/lithe-plugins.git/ ", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, - { "input": "https://github.com/example/lithe-plugins/blob/release/v1/indexes/lithe-plugin-index.json", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, - { "input": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "expected": { "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins" } }, - { "input": "https://plugins.example.com/lithe/index.json#latest", "expected": { "indexURL": "https://plugins.example.com/lithe/index.json", "recommendationsURL": "https://plugins.example.com/lithe/lithe-plugin-recommendations.json", "repository": null, "displayName": "plugins.example.com" } }, - { "input": "http://plugins.example.com/index.json", "expectedCode": "plugin.source.invalid" }, - { "input": "https://token@github.com/example/lithe-plugins", "expectedCode": "plugin.source.invalid" }, - { "input": "https://github.com/example", "expectedCode": "plugin.source.invalid" }, - { "input": "https://github.com/example/lithe-plugins/issues", "expectedCode": "plugin.source.invalid" }, - { "input": "file:///tmp/index.json", "expectedCode": "plugin.source.invalid" }, - { "input": "github.com/example/lithe-plugins", "expectedCode": "plugin.source.invalid" } + {"input": "https://github.com/example/lithe-plugins", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "HEAD"}}}, + {"input": " https://github.com/example/lithe-plugins.git/ ", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "HEAD"}}}, + {"input": "https://github.com/example/lithe-plugins/blob/release/v1/indexes/lithe-plugin-index.json", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "release"}}}, + {"input": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "main"}}}, + {"input": "https://plugins.example.com/lithe/index.json#latest", "expected": {"indexURL": "https://plugins.example.com/lithe/index.json", "recommendationsURL": "https://plugins.example.com/lithe/lithe-plugin-recommendations.json", "repository": null, "displayName": "plugins.example.com", "revision": null}}, + {"input": "https://github.com/example/lithe-plugins", "commit": "0123456789ABCDEF0123456789ABCDEF01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "HEAD"}, "pinned": {"commit": "0123456789abcdef0123456789abcdef01234567", "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-recommendations.json"}}}, + {"input": "https://raw.githubusercontent.com/example/lithe-plugins/refs/heads/release/v1/indexes/lithe-plugin-index.json", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/refs/heads/release/v1/indexes/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/refs/heads/release/v1/indexes/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "refs/heads/release"}, "pinned": {"commit": "0123456789abcdef0123456789abcdef01234567", "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/v1/indexes/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/v1/indexes/lithe-plugin-recommendations.json"}}}, + {"input": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-index.json", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": null, "pinned": null}}, + {"input": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json?token=abc", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json?token=abc", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": null, "pinned": null}}, + {"input": "https://plugins.example.com/lithe/index.json", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://plugins.example.com/lithe/index.json", "recommendationsURL": "https://plugins.example.com/lithe/lithe-plugin-recommendations.json", "repository": null, "displayName": "plugins.example.com", "revision": null, "pinned": null}}, + {"input": "http://plugins.example.com/index.json", "expectedCode": "plugin.source.invalid"}, + {"input": "https://token@github.com/example/lithe-plugins", "expectedCode": "plugin.source.invalid"}, + {"input": "https://github.com/example", "expectedCode": "plugin.source.invalid"}, + {"input": "https://github.com/example/lithe-plugins/issues", "expectedCode": "plugin.source.invalid"}, + {"input": "file:///tmp/index.json", "expectedCode": "plugin.source.invalid"}, + {"input": "github.com/example/lithe-plugins", "expectedCode": "plugin.source.invalid"}, + {"input": "https://github.com/example/lithe-plugins", "commit": "0123abc", "expectedCode": "plugin.source.commitInvalid"} ] } diff --git a/shared/plugins/reference/domains/marketplace.md b/shared/plugins/reference/domains/marketplace.md index 58e8f36e..d8711358 100644 --- a/shared/plugins/reference/domains/marketplace.md +++ b/shared/plugins/reference/domains/marketplace.md @@ -42,6 +42,8 @@ | `…/blob//` | 对应的 raw 文件 | | http、带账号密码的地址、其他 GitHub 页面 | `plugin.source.invalid` | +raw.githubusercontent.com 会把分支地址缓存几分钟,刚合入的索引可能还是旧的。索引托管在 GitHub 上且地址不带查询参数时,`resolveSource` 还返回 `revision: { repository: { owner, name }, ref }`,也就是地址跟随的分支或标签:`HEAD`、路径的第一段,或者 `refs/heads/`、`refs/tags/`。其他来源和已经指向完整提交的地址,`revision` 为 null。宿主可以用 GitHub 的 `latestCommit` 操作查到这个 ref 当前的提交,再带上 `commit`(完整的 SHA-1 或 SHA-256,否则返回 `plugin.source.commitInvalid`)调用一次 `resolveSource`,结果多出 `pinned: { commit, indexURL, recommendationsURL }`,即同一批文件在这个提交上的地址;无法固定时为 null。宿主下载固定地址,查询或下载失败时退回原地址。`indexURL` 始终是来源的身份,宿主记录和比较的都是它,不是固定地址。分支名含 `/` 时,只有写成 `refs/heads/` 才能固定。 + 获取到的索引缓存在平台缓存或 Application Support,不写进安装目录。 ### 索引条目 @@ -131,7 +133,7 @@ | [`marketplace/index-cases.json`](../../contract/v1/fixtures/marketplace/index-cases.json) | 7 个 `validateIndex` 用例:没有宿主能力表的官方来源、第三方来源不能列官方命名空间、Windows 平台选自己的压缩包、宿主能运行语言服务器但不能运行构建系统、有构建系统但没有构建提供者时保留只含语言的版本、没有语言服务器时不提供语言插件、Core 无法校验的能力永远不可用 | | [`marketplace/invalid-index-entries.json`](../../contract/v1/fixtures/marketplace/invalid-index-entries.json) | 26 个条目错误用例:25 个 `plugin.index.invalid`,1 个 `plugin.index.officialNamespace` | | [`marketplace/install-reviews.json`](../../contract/v1/fixtures/marketplace/install-reviews.json) | 19 个 `installReview` 用例:首次安装、无变化更新、改了参数或探针需要重新批准、包与条目不符、官方命名空间的未签名包、构建插件的能力要求 | -| [`marketplace/source-urls.json`](../../contract/v1/fixtures/marketplace/source-urls.json) | 11 个 `resolveSource` 用例:5 个解析成功,6 个 `plugin.source.invalid` | +| [`marketplace/source-urls.json`](../../contract/v1/fixtures/marketplace/source-urls.json) | 17 个 `resolveSource` 用例:10 个解析成功(其中 5 个带 `commit`),6 个 `plugin.source.invalid`,1 个 `plugin.source.commitInvalid` | ### 相关指南 @@ -179,6 +181,8 @@ A marketplace is a JSON index that lists plugins and the release archives of eac | `…/blob//` | The matching raw file | | Plain http, embedded credentials, other GitHub pages | `plugin.source.invalid` | +raw.githubusercontent.com caches a branch URL for minutes, so a just-merged index can look unchanged. For a GitHub-hosted index without a query, `resolveSource` also returns `revision: { repository: { owner, name }, ref }`, the branch or tag the URL follows: `HEAD`, the first path segment, or `refs/heads/` / `refs/tags/`. It is null for other sources and for a URL already at a full commit. A host may look the ref's current commit up with the GitHub `latestCommit` operation and call `resolveSource` again with `commit` (a full SHA-1 or SHA-256, otherwise `plugin.source.commitInvalid`); the answer then adds `pinned: { commit, indexURL, recommendationsURL }`, the same files at that commit, or null when nothing can be pinned. The host fetches the pinned URLs and falls back to the unpinned ones when the lookup or the fetch fails. `indexURL` stays the source's identity: the host records and compares it, never the pinned URL. A branch whose name contains `/` is only pinned when written as `refs/heads/`. + Fetched indexes are cached in platform cache or Application Support storage, never inside the installation. ### Index entries @@ -268,7 +272,7 @@ When several sources list the same ID, the user chooses the source at install ti | [`marketplace/index-cases.json`](../../contract/v1/fixtures/marketplace/index-cases.json) | 7 `validateIndex` cases: the official source without a host capability table, a third-party source listing the official namespace, a Windows platform picking its own archive, a host that runs language servers but not build systems, a host with build systems but no build providers keeping the language-only version, a host without language servers offered no language plugin, and a capability Core cannot validate never being offered | | [`marketplace/invalid-index-entries.json`](../../contract/v1/fixtures/marketplace/invalid-index-entries.json) | 26 entry error cases: 25 `plugin.index.invalid` and 1 `plugin.index.officialNamespace` | | [`marketplace/install-reviews.json`](../../contract/v1/fixtures/marketplace/install-reviews.json) | 19 `installReview` cases: first install, an unchanged update, argument or probe changes needing new approval, a package that does not match its entry, an unsigned official-namespace package, and the capability requirements of build plugins | -| [`marketplace/source-urls.json`](../../contract/v1/fixtures/marketplace/source-urls.json) | 11 `resolveSource` cases: 5 resolved and 6 `plugin.source.invalid` | +| [`marketplace/source-urls.json`](../../contract/v1/fixtures/marketplace/source-urls.json) | 17 `resolveSource` cases: 10 resolved (5 of them with a `commit`), 6 `plugin.source.invalid` and 1 `plugin.source.commitInvalid` | ### Related guides diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 804a6081..ae8cce72 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,7 @@ ## 待合入 +- [#173](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/173),[@xiaoyumuxi](https://github.com/xiaoyumuxi),市场索引 `schemaVersion` 0 内的补充(—):`plugins.marketplace.resolveSource` 的结果新增 `revision: { repository: { owner, name }, ref }`(托管在 GitHub 且不带查询参数的索引才有,否则为 null),输入新增可选的 `commit`,带上后结果多出 `pinned: { commit, indexURL, recommendationsURL }`,即同一批文件在该提交上的地址;`commit` 不是完整的 SHA-1 或 SHA-256 时返回新的拒绝码 `plugin.source.commitInvalid`。`indexURL` 仍是来源身份。宿主借此绕过 raw.githubusercontent.com 对分支地址约 5 分钟的缓存,查询或固定下载失败时退回原地址。fixture `marketplace/source-urls.json` 从 11 个用例增加到 17 个。索引格式、插件清单、宿主方法和能力版本都不变。 - [#171](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/171),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的说明修正(Go SDK):Go SDK 需要的最低 Go 版本从 1.22 提高到 1.27.4,和桌面端构建用的 Go 一致。`shared/plugins/sdk/go/go.mod` 改为 `go 1.27.4`,契约 README 的 Official backend SDK 中 `sdk/go` 一段、插件总览、原生构建指南和四个 SDK 的 README 随之更新。插件升级到这个版本的 SDK 后,自己的 `go.mod` 也要写 `go 1.27.4` 或更高。SDK 代码和对外接口不变,没有新增版本号、宿主方法、通知或协议字段。 - [#151](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/151),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-05、API-35、API-40):远程工作区上下文的 `authority` 新增 `platform: { os, arch }`,取值同托管运行时(`os` 为 `linux`,`arch` 为 `arm64` 或 `x86_64`),本地上下文没有这个字段。新增宿主方法 `workspace/getHostPaths`:返回远程上下文的根目录在远端主机上的绝对 POSIX 路径 `hostPath`,可选的 `rootIDs`(1–256 个不重复的根目录 ID)决定返回哪些根目录和顺序;它是 `workspace.metadata` 下单独的方法授权,本地上下文返回 `plugin.host.authorityUnsupported`,未知根目录返回 `plugin.host.notFound`;声明 `workspace.metadata` 的插件,启动计划的 `backend.hostServices` 因此多出 `lithe/host/workspace/getHostPaths`,宿主传给 `lsp.startServer` 时去掉自己没有注册处理器的方法授权,后端调用它们得到 `plugin.host.permissionDenied`。新增失败码 `plugin.host.remoteDisconnected`(`-32078`,操作进行中与远端主机断开)和 `plugin.host.platformUnavailable`(`-32079`,插件没有适合远端平台的程序包或托管运行时)。插件函数中转不再拒绝远程工作区的上下文,导出的 `context: "workspace"` 指两种来源的工作区,Core 不读也不改写参数和结果里的路径。四个官方 SDK 新增远端平台读取、`getHostPaths`、按来源选择进程所用路径的辅助方法和两个失败码,`path` 与 `hostPath` 是不同类型。没有新增能力版本、通知或 SDK 版本。 - [#150](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/150),[@Mucheen](https://github.com/Mucheen),`runConfigurationTypes` 0 内的行为修正(API-29)。`build.runConfigurationPlan` 在工作目录为工作区根且没有匹配实例时,用唯一生效的文件字段解析后的工作区内目标定位最深的构建实例。`./` 等价于工作区根,指向工作区外的链接不参与定位。进程工作目录和执行前任务选择规则保持原样。没有新增宿主方法、通知或协议版本。