Skip to content

Commit 4430719

Browse files
authored
feat(marketplace): resolveSource 报告索引跟随的仓库和分支,可按提交固定地址绕过 raw 缓存;GitHub 新增 latestCommit 和 listReleases (#173)
* feat(marketplace): resolveSource 报告索引跟随的仓库和分支,可按提交固定地址绕过 raw 缓存;GitHub 新增 latestCommit 和 listReleases raw.githubusercontent.com 对分支地址缓存 5 分钟,Store 合入新版本后宿主还会读到旧索引。 resolveSource 对托管在 GitHub 的索引返回 revision(仓库和 ref),宿主用新的匿名操作 github latestCommit 查到当前提交后带 commit 再调一次,得到 pinned(同一批文件在该提交上 的地址)。indexURL 仍是来源身份。listReleases 给插件详情的更新日志用,匿名读取、去掉草稿、 按发布时间倒序。 * docs(plugins): 插件协议更新记录补上 #173
1 parent a5806bc commit 4430719

10 files changed

Lines changed: 447 additions & 52 deletions

File tree

‎rust/contracts/github.md‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,21 @@ Supported operations are `deviceCode`, `deviceToken`, `currentUser`,
8888
`listBranches`, `compareBranches`, `listPullRequests`, `getPullRequest`, `createPullRequest`, `updatePullRequest`,
8989
`listPullRequestFiles`, `listPullRequestComments`,
9090
`createPullRequestComment`, `createPullRequestReview`, `mergePullRequest`,
91-
`updatePullRequestMetadata`, `listReviewComments`, `listCheckRuns`, and
92-
`getCombinedStatus`.
91+
`updatePullRequestMetadata`, `listReviewComments`, `listCheckRuns`,
92+
`getCombinedStatus`, `latestCommit`, and `listReleases`.
93+
94+
`latestCommit` and `listReleases` read public data, so their plans set
95+
`requiresAuthentication: false` and work without a signed-in account.
96+
`latestCommit` (`GET /repos/{owner}/{name}/commits?sha={ref}&per_page=1`) needs
97+
`ref` (`HEAD`, a branch or tag name, or a `refs/...` name; whitespace, `..`, a
98+
leading `-` and the revision operators `~ ^ : ? * [ \` are refused) and returns
99+
`{ sha }`, the ref's newest commit as a full lowercase SHA-1 or SHA-256 name.
100+
Hosts use it to pin a marketplace index to a commit, because raw file URLs of a
101+
branch are cached for minutes (see `plugins.marketplace.resolveSource`).
102+
`listReleases` (`GET /repos/{owner}/{name}/releases`, first page of 20) returns
103+
`[{ tagName, name, body, publishedAt, prerelease, url }]` newest publication
104+
first, ties ordered by tag; drafts are dropped, an empty title is `null` and
105+
missing notes are `""`.
93106

94107
`listReviewComments` (`GET /repos/{owner}/{name}/pulls/{number}/comments`, first
95108
page of 100) needs `pullNumber` and returns a flat array of

‎rust/contracts/rust-core-api.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5438,8 +5438,11 @@ archives and pass the parsed JSON. `validateIndex` accepts
54385438
`{ index, sourceKind: "official" | "thirdParty", platform, hostCapabilities? }`
54395439
and returns `{ status: "ok", index: { plugins, rejected } }` with per-entry
54405440
`availability`; a listed version is available only when its `pluginAPIVersion`
5441-
is one Core supports and every capability it requires is in `hostCapabilities`; `resolveSource` accepts `{ url }` and returns
5442-
`{ status: "ok", source: { indexURL, recommendationsURL, repository, displayName } }`;
5441+
is one Core supports and every capability it requires is in `hostCapabilities`; `resolveSource` accepts `{ url, commit? }` and returns
5442+
`{ status: "ok", source: { indexURL, recommendationsURL, repository, displayName, revision, pinned? } }`,
5443+
where `revision` names the GitHub repository and ref a host may look the newest commit of
5444+
(`github.latestCommit`) and `pinned` holds the same URLs at the `commit` passed back;
5445+
`indexURL` remains the source identity;
54435446
`installReview` accepts `{ manifest, expectedID?, expectedVersion?,
54445447
approvedPrograms?, hostCapabilities? }` and returns `{ status: "ok", review: { id, version,
54455448
permissions, programs, newPrograms } }`;

‎rust/crates/core/src/tests/github.rs‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,3 +394,127 @@ fn request_plan_and_normalize_review_comment_threads() {
394394
assert!(response["data"][1]["line"].is_null());
395395
assert_eq!(response["data"][1]["createdAt"], "2026-11-01T00:05:00Z");
396396
}
397+
398+
#[test]
399+
fn request_plan_reads_the_newest_commit_and_releases_without_credentials() {
400+
let response = execute(
401+
"github.requestPlan",
402+
json!({
403+
"operation": "latestCommit",
404+
"repository": {"owner": "example", "name": "lithe-plugins"},
405+
"ref": "refs/heads/release"
406+
}),
407+
);
408+
assert_eq!(response["ok"], true, "{response:?}");
409+
assert_eq!(response["data"]["host"], "api");
410+
assert_eq!(response["data"]["method"], "GET");
411+
assert_eq!(
412+
response["data"]["path"],
413+
"/repos/example/lithe-plugins/commits"
414+
);
415+
assert_eq!(
416+
response["data"]["query"],
417+
json!({"per_page": "1", "sha": "refs/heads/release"})
418+
);
419+
assert_eq!(response["data"]["requiresAuthentication"], false);
420+
421+
let response = execute(
422+
"github.requestPlan",
423+
json!({
424+
"operation": "listReleases",
425+
"repository": {"owner": "example", "name": "lithe-plugin-rust"}
426+
}),
427+
);
428+
assert_eq!(response["ok"], true, "{response:?}");
429+
assert_eq!(
430+
response["data"]["path"],
431+
"/repos/example/lithe-plugin-rust/releases"
432+
);
433+
assert_eq!(response["data"]["query"], json!({"per_page": "20"}));
434+
assert_eq!(response["data"]["requiresAuthentication"], false);
435+
436+
for git_ref in ["", "main..x", "-x", "main x", "HEAD~1", "a:b"] {
437+
let response = execute(
438+
"github.requestPlan",
439+
json!({
440+
"operation": "latestCommit",
441+
"repository": {"owner": "example", "name": "lithe-plugins"},
442+
"ref": git_ref
443+
}),
444+
);
445+
assert_eq!(response["ok"], false, "{git_ref}: {response:?}");
446+
assert_eq!(response["error"]["code"], "invalid_request");
447+
}
448+
}
449+
450+
#[test]
451+
fn normalizes_the_newest_commit_to_a_full_lowercase_object_name() {
452+
let sha = "0123456789ABCDEF0123456789ABCDEF01234567";
453+
let response = execute(
454+
"github.normalizeResponse",
455+
json!({
456+
"operation": "latestCommit",
457+
"status": 200,
458+
"body": json!([{"sha": sha, "commit": {"message": "x"}}]).to_string()
459+
}),
460+
);
461+
assert_eq!(response["ok"], true, "{response:?}");
462+
assert_eq!(response["data"], json!({"sha": sha.to_ascii_lowercase()}));
463+
464+
for body in [json!([]), json!([{"sha": "0123abc"}]), json!({"sha": sha})] {
465+
let response = execute(
466+
"github.normalizeResponse",
467+
json!({"operation": "latestCommit", "status": 200, "body": body.to_string()}),
468+
);
469+
assert_eq!(response["ok"], false, "{body}: {response:?}");
470+
assert_eq!(response["error"]["code"], "parse_failed");
471+
}
472+
}
473+
474+
#[test]
475+
fn normalizes_releases_newest_first_without_drafts() {
476+
let body = json!([
477+
{
478+
"tag_name": "v0.1.0", "name": "v0.1.0", "body": "First.", "draft": false,
479+
"prerelease": true, "published_at": "2026-11-21T08:00:00Z",
480+
"html_url": "https://github.com/example/p/releases/tag/v0.1.0"
481+
},
482+
{
483+
"tag_name": "v0.2.0", "name": null, "body": null, "draft": true,
484+
"prerelease": false, "published_at": null,
485+
"html_url": "https://github.com/example/p/releases/tag/untagged"
486+
},
487+
{
488+
"tag_name": "v0.1.1", "name": " ", "body": "## Fixes\n- One.", "draft": false,
489+
"prerelease": false, "published_at": "2026-11-22T13:31:49Z",
490+
"html_url": "https://github.com/example/p/releases/tag/v0.1.1"
491+
}
492+
]);
493+
let response = execute(
494+
"github.normalizeResponse",
495+
json!({"operation": "listReleases", "status": 200, "body": body.to_string()}),
496+
);
497+
assert_eq!(response["ok"], true, "{response:?}");
498+
assert_eq!(
499+
response["data"],
500+
json!([
501+
{
502+
"tagName": "v0.1.1", "name": null, "body": "## Fixes\n- One.",
503+
"publishedAt": "2026-11-22T13:31:49Z", "prerelease": false,
504+
"url": "https://github.com/example/p/releases/tag/v0.1.1"
505+
},
506+
{
507+
"tagName": "v0.1.0", "name": "v0.1.0", "body": "First.",
508+
"publishedAt": "2026-11-21T08:00:00Z", "prerelease": true,
509+
"url": "https://github.com/example/p/releases/tag/v0.1.0"
510+
}
511+
])
512+
);
513+
514+
let response = execute(
515+
"github.normalizeResponse",
516+
json!({"operation": "listReleases", "status": 404, "body": "{\"message\":\"Not Found\"}"}),
517+
);
518+
assert_eq!(response["ok"], false, "{response:?}");
519+
assert_eq!(response["error"]["code"], "invalid_request");
520+
}

‎rust/crates/core/src/tests/marketplace_plugins.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,11 @@ fn source_url_fixtures_resolve_to_expected_index_urls() {
197197
let cases = json_file(SOURCE_URLS);
198198
for case in cases["cases"].as_array().unwrap() {
199199
let input = case["input"].as_str().unwrap();
200-
let outcome = resolve_source_command(json!({ "url": input })).unwrap();
200+
let mut payload = json!({ "url": input });
201+
if let Some(commit) = case.get("commit") {
202+
payload["commit"] = commit.clone();
203+
}
204+
let outcome = resolve_source_command(payload).unwrap();
201205
if let Some(code) = case.get("expectedCode") {
202206
assert_eq!(outcome["status"], "rejected", "{input}: {outcome}");
203207
assert_eq!(&outcome["error"]["code"], code, "{input}: {outcome}");

‎rust/crates/github/src/lib.rs‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@ const DEVICE_EXPIRATION_MAX_SECONDS: u64 = 86_400;
1515
// Once an interval reaches the maximum lifetime, no further poll can occur.
1616
const DEVICE_INTERVAL_MAX_SECONDS: u64 = DEVICE_EXPIRATION_MAX_SECONDS;
1717
const DEVICE_SLOW_DOWN_SECONDS: u64 = 5;
18+
// The changelog shows the newest releases; one bounded page keeps the
19+
// anonymous request small.
20+
const RELEASE_PAGE_SIZE: u64 = 20;
21+
// A Git ref name is bounded like a file name; GitHub refuses longer ones.
22+
const GIT_REF_MAX_BYTES: usize = 255;
1823

1924
#[derive(Debug, Deserialize)]
2025
#[serde(rename_all = "camelCase")]
@@ -200,6 +205,9 @@ pub struct RequestPlanRequest {
200205
/// Full commit SHA required by commit-status operations.
201206
#[serde(default)]
202207
pub commit: Option<String>,
208+
/// Branch, tag or `HEAD` whose newest commit `latestCommit` looks up.
209+
#[serde(default, rename = "ref")]
210+
pub git_ref: Option<String>,
203211
/// OAuth application's public client identifier.
204212
#[serde(default)]
205213
pub client_id: Option<String>,
@@ -452,6 +460,24 @@ pub struct GitHubComparison {
452460
pub files: Vec<GitHubPullRequestFile>,
453461
}
454462

463+
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
464+
#[serde(rename_all = "camelCase")]
465+
/// Normalized published release of a repository, as a changelog lists it.
466+
pub struct GitHubRelease {
467+
/// Git tag the release was published from.
468+
pub tag_name: String,
469+
/// Release title; null when the author left it empty.
470+
pub name: Option<String>,
471+
/// Markdown release notes; empty when the author wrote none.
472+
pub body: String,
473+
/// ISO-8601 publication timestamp.
474+
pub published_at: Option<String>,
475+
/// Whether the author marked the release as a pre-release.
476+
pub prerelease: bool,
477+
/// Browser URL of the release page.
478+
pub url: String,
479+
}
480+
455481
/// Parses one supported GitHub remote URL.
456482
pub fn parse_remote(request: ParseRemoteRequest) -> Result<GitHubRepository, CoreError> {
457483
let value = request.remote_url.trim().trim_end_matches('/');
@@ -634,6 +660,32 @@ pub fn request_plan(request: RequestPlanRequest) -> Result<GitHubRequestPlan, Co
634660
true,
635661
)
636662
}
663+
// Public reads: an anonymous request works on any public repository,
664+
// so a signed-out user gets the same answer.
665+
"latestCommit" => {
666+
let repository = repository_path(&request)?;
667+
let git_ref = git_ref(&request)?;
668+
query.insert("sha".to_string(), git_ref.to_string());
669+
query.insert("per_page".to_string(), "1".to_string());
670+
(
671+
GitHubHost::Api,
672+
"GET",
673+
format!("/repos/{repository}/commits"),
674+
None,
675+
false,
676+
)
677+
}
678+
"listReleases" => {
679+
let repository = repository_path(&request)?;
680+
query.insert("per_page".to_string(), RELEASE_PAGE_SIZE.to_string());
681+
(
682+
GitHubHost::Api,
683+
"GET",
684+
format!("/repos/{repository}/releases"),
685+
None,
686+
false,
687+
)
688+
}
637689
"listPullRequestComments" => {
638690
let repository = repository_path(&request)?;
639691
let number = pull_number(&request)?;
@@ -744,6 +796,8 @@ pub fn normalize_response(request: NormalizeResponseRequest) -> Result<Value, Co
744796
"listReviewComments" => normalize_review_comment_list(value),
745797
"listCheckRuns" => normalize_check_run_list(value),
746798
"getCombinedStatus" => normalize_combined_status(value),
799+
"latestCommit" => normalize_latest_commit(value),
800+
"listReleases" => normalize_release_list(value),
747801
"createPullRequestComment" => {
748802
Ok(serde_json::to_value(normalize_comment(&value)?).expect("comment encodes"))
749803
}
@@ -766,6 +820,24 @@ fn commit_path(request: &RequestPlanRequest) -> Result<(String, String), CoreErr
766820
Ok((repository, commit.to_string()))
767821
}
768822

823+
/// The ref travels as a query value, so it is only bounded here; GitHub
824+
/// answers an unknown ref with an error.
825+
fn git_ref(request: &RequestPlanRequest) -> Result<&str, CoreError> {
826+
let value = required_text(request.git_ref.as_deref(), "ref")?;
827+
let valid = value.len() <= GIT_REF_MAX_BYTES
828+
&& !value.contains("..")
829+
&& !value.starts_with('-')
830+
&& value.chars().all(|character| {
831+
character.is_ascii_graphic()
832+
&& !matches!(character, '~' | '^' | ':' | '?' | '*' | '[' | '\\')
833+
});
834+
if valid {
835+
Ok(value)
836+
} else {
837+
Err(invalid_field("ref"))
838+
}
839+
}
840+
769841
fn repository_path(request: &RequestPlanRequest) -> Result<String, CoreError> {
770842
request
771843
.repository
@@ -1097,6 +1169,59 @@ fn normalize_combined_status(value: Value) -> Result<Value, CoreError> {
10971169
Ok(serde_json::to_value(checks).expect("combined status encodes"))
10981170
}
10991171

1172+
/// The commit list is asked for one entry: the ref's newest commit. A full
1173+
/// SHA-1 or SHA-256 object name is required, because the caller builds an
1174+
/// immutable file URL from it.
1175+
fn normalize_latest_commit(value: Value) -> Result<Value, CoreError> {
1176+
let first = value
1177+
.as_array()
1178+
.and_then(|commits| commits.first())
1179+
.ok_or_else(parse_shape_error)?;
1180+
let sha = text(object(first)?, "sha")?;
1181+
if !matches!(sha.len(), 40 | 64) || !sha.bytes().all(|byte| byte.is_ascii_hexdigit()) {
1182+
return Err(parse_shape_error());
1183+
}
1184+
Ok(json!({ "sha": sha.to_ascii_lowercase() }))
1185+
}
1186+
1187+
/// Drafts are dropped (an anonymous reader never sees them). The newest
1188+
/// publication comes first; equal timestamps fall back to the tag so the
1189+
/// order does not depend on GitHub's.
1190+
fn normalize_release_list(value: Value) -> Result<Value, CoreError> {
1191+
let mut releases = Vec::new();
1192+
for value in value.as_array().ok_or_else(parse_shape_error)? {
1193+
let object = object(value)?;
1194+
if object.get("draft").and_then(Value::as_bool) == Some(true) {
1195+
continue;
1196+
}
1197+
let optional = |key: &str| {
1198+
object
1199+
.get(key)
1200+
.and_then(Value::as_str)
1201+
.filter(|value| !value.trim().is_empty())
1202+
.map(str::to_string)
1203+
};
1204+
releases.push(GitHubRelease {
1205+
tag_name: text(object, "tag_name")?.to_string(),
1206+
name: optional("name"),
1207+
body: optional("body").unwrap_or_default(),
1208+
published_at: optional("published_at"),
1209+
prerelease: object
1210+
.get("prerelease")
1211+
.and_then(Value::as_bool)
1212+
.unwrap_or(false),
1213+
url: text(object, "html_url")?.to_string(),
1214+
});
1215+
}
1216+
releases.sort_by(|left, right| {
1217+
right
1218+
.published_at
1219+
.cmp(&left.published_at)
1220+
.then_with(|| right.tag_name.cmp(&left.tag_name))
1221+
});
1222+
Ok(serde_json::to_value(releases).expect("release list encodes"))
1223+
}
1224+
11001225
fn normalize_file_list(value: Value) -> Result<Value, CoreError> {
11011226
let array = value.as_array().ok_or_else(parse_shape_error)?;
11021227
let mut files = array

0 commit comments

Comments
 (0)