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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions cli/bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
},
"dependencies": {
"cac": "^6.7.14",
"fflate": "^0.8.2",
"fflate": "0.8.3",
"prompts": "^2.4.2",
"proper-lockfile": "4.1.2",
"semver": "^7.6.3",
Expand Down
25 changes: 16 additions & 9 deletions cli/src/clients/skillhub-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ export class SkillHubClient {
try {
response = await this.fetchImpl(
`${this.registry}/api/v1/suites/${encodeURIComponent(namespace)}/${encodeURIComponent(slug)}${params}`,
{ headers: this.headers() }
{ headers: this.headers(), ...(this.token ? { redirect: 'error' as const } : {}) }
)
} catch {
throw new CliError('registry unreachable', EXIT.network, { registry: this.registry, next: 'check network or pass --registry' })
Expand All @@ -284,12 +284,19 @@ export class SkillHubClient {
// Keep the configured registry prefix, as direct download() does.
const relativeUrl = downloadUrl.startsWith('/api/') ? downloadUrl.slice(1) : downloadUrl
const registryBase = `${this.registry.replace(/\/+$/, '')}/`
const url = new URL(relativeUrl, registryBase)
let url = new URL(relativeUrl, registryBase)
const registryApi = new URL('api/', registryBase)
const headers = url.origin === registryApi.origin && url.pathname.startsWith(registryApi.pathname)
? this.headers()
: {}
response = await this.fetchImpl(url.toString(), { headers })
let trusted = true
for (let redirects = 0; ; redirects++) {
trusted = trusted && url.origin === registryApi.origin && url.pathname.startsWith(registryApi.pathname)
response = await this.fetchImpl(url.toString(), { headers: trusted ? this.headers() : {}, redirect: 'manual' })
if (![301, 302, 303, 307, 308].includes(response.status)) break
const location = response.headers.get('location')
await response.body?.cancel()
if (!location || redirects >= 10) throw new Error('Invalid package redirect')
url = new URL(location, url)
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('Invalid download URL')
}
} catch {
throw new CliError('registry unreachable', EXIT.network, { registry: this.registry, next: 'check network or pass --registry' })
}
Expand Down Expand Up @@ -324,7 +331,7 @@ export class SkillHubClient {
const url = await this.downloadUrl(namespace, slug, version)
let response: Response
try {
response = await this.fetchImpl(url, { headers: this.headers() })
response = await this.fetchImpl(url, { headers: this.headers(), ...(this.token ? { redirect: 'error' as const } : {}) })
} catch {
throw new CliError('registry unreachable', EXIT.network, { registry: this.registry, next: 'check network or pass --registry' })
}
Expand Down Expand Up @@ -412,7 +419,7 @@ export class SkillHubClient {
let response: Response
try {
response = await this.fetchImpl(`${this.registry}/api/cli/v1${path}`, {
headers: this.headers()
headers: this.headers(), ...(this.token ? { redirect: 'error' as const } : {})
})
} catch (err) {
throw new CliError('registry unreachable', EXIT.network, { registry: this.registry, next: 'check network or pass --registry' })
Expand Down Expand Up @@ -515,7 +522,7 @@ export class SkillHubClient {
try {
response = await this.fetchImpl(`${this.registry}/api/cli/v1${path}`, {
method: 'DELETE',
headers: this.headers()
headers: this.headers(), ...(this.token ? { redirect: 'error' as const } : {})
})
} catch {
throw new CliError('registry unreachable', EXIT.network, { registry: this.registry, next: 'check network or pass --registry' })
Expand Down
18 changes: 9 additions & 9 deletions cli/src/integrations/native-changes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,12 @@ export async function syncTree(path: string): Promise<void> {
}
/** Exact release only; temporary content is never trusted without hashes and full release identity. */
export async function withRelease<T>(state: string, identity: UpgradeSelection & {versionId: number; fingerprint: string},
run: (directory: string, files: Record<string, string>) => Promise<T>): Promise<T> {
run: (directory: string, files: Record<string, string>) => Promise<T>, token?: string): Promise<T> {
const parent = join(dirname(state), 'change-staging')
await privateDirectory(parent)
const directory = await mkdtemp(join(parent, 'release-'))
try {
const client = new SkillHubClient(identity.registry)
const client = new SkillHubClient(identity.registry, token)
const release = await client.resolve(identity.namespace, identity.slug, identity.version)
if (release.namespace !== identity.namespace || release.slug !== identity.slug || release.version !== identity.version
|| release.versionId !== identity.versionId || release.fingerprint !== identity.fingerprint) throw new Error('Original release identity is unavailable')
Expand All @@ -86,13 +86,13 @@ export async function withRelease<T>(state: string, identity: UpgradeSelection &
return await run(directory, snapshot.files)
} finally { await rm(directory, { recursive: true, force: true }) }
}
export async function withOriginal<T>(state: string, snapshot: ReadyChanges, run: (directory: string) => Promise<T>): Promise<T> {
export async function withOriginal<T>(state: string, snapshot: ReadyChanges, run: (directory: string) => Promise<T>, token?: string): Promise<T> {
const metadata = snapshot.baseline.targets[0]!.metadata
if (!metadata.versionId || !metadata.fingerprint || !metadata.files) throw new Error('Original release baseline is unavailable')
return withRelease(state, { ...snapshot.selection, versionId: metadata.versionId, fingerprint: metadata.fingerprint }, async (directory, files) => {
if (!isDeepStrictEqual(files, metadata.files)) throw new Error('Original release file map mismatch')
return run(directory)
})
}, token)
}
export function boundedDiff(path: string, before: Buffer | undefined, after: Buffer | undefined): BoundedFileDiff {
const result: BoundedFileDiff = { path, state: 'text', lines: [], truncated: false }
Expand Down Expand Up @@ -125,7 +125,7 @@ async function readOptional(directory: string, path: string, files: Record<strin
if (createHash('sha256').update(content).digest('hex') !== files[logical]) throw new Error('Compared file changed')
return content
}
export async function readChangeDiff(state: string, inventory: InventoryStore, snapshot: ReadyChanges | VersionChangesSnapshot, path: string): Promise<BoundedFileDiff> {
export async function readChangeDiff(state: string, inventory: InventoryStore, snapshot: ReadyChanges | VersionChangesSnapshot, path: string, token?: string): Promise<BoundedFileDiff> {
const local = snapshot.kind === 'local' ? snapshot : snapshot.local
const physical = physicalPath(local, path)
if (!snapshot.changes.some(file => file.path === path)) throw new Error('Path is not in the change snapshot')
Expand All @@ -137,13 +137,13 @@ export async function readChangeDiff(state: string, inventory: InventoryStore, s
return withRelease(state, { ...local.selection, ...snapshot.candidate }, async (candidate, files) => {
if (!isDeepStrictEqual(files, snapshot.files)) throw new Error('Candidate changed')
return boundedDiff(path, before, await readOptional(candidate, path, files))
})
})
}, token)
}, token)
await assertChanges(inventory, local)
return result
}
export async function prepareVersionChanges(state: string, inventory: InventoryStore, selected: UpgradeSelection,
target: InstalledProjectionTarget, candidate: VersionChangesSnapshot['candidate']): Promise<VersionChangesSnapshot> {
target: InstalledProjectionTarget, candidate: VersionChangesSnapshot['candidate'], token?: string): Promise<VersionChangesSnapshot> {
const local = await inspectChanges(inventory, selected, target)
if (local.status !== 'ready') throw new Error('Installation cannot be compared')
const assessment = (await import('./update-assessment')).assessSkillUpdate({ version: selected.version,
Expand All @@ -153,7 +153,7 @@ export async function prepareVersionChanges(state: string, inventory: InventoryS
await assertChanges(inventory, local)
return { status: 'ready', kind: 'version', local, candidate: { ...candidate }, files,
changes: changeFiles(local.baseline.targets[0]!.metadata.files!, files) }
}))
}, token), token)
}
export async function rawSnapshot(directory: string): Promise<{files: Record<string, string>; metadata: string}> {
await assertOwnedRegularTree(directory)
Expand Down
2 changes: 1 addition & 1 deletion cli/src/integrations/native-contract.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ export interface NativeInstallExecution {
}

export interface NativeCore {
openNativeRuntime(options: { stateDirectory: string; inventoryHome: string }): Promise<NativeRuntime>
openNativeRuntime(options: { stateDirectory: string; inventoryHome: string; getRegistryToken?: (registry: string) => string | undefined }): Promise<NativeRuntime>
}

export interface NativeUpgradeExecution extends Omit<NativeInstallExecution, 'root' | 'scope'> {
Expand Down
5 changes: 3 additions & 2 deletions cli/src/integrations/native-file-reset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ const terminal = (record: ResetRecord) => ['completed', 'failed'].includes(recor
/** Separate directory and schema: older OperationStore builds never parse extended reset records. */
export class FileResetStore {
readonly root: string
constructor(private state: string, private hostInstanceId: string, private inventory: InventoryStore, private assertOtherOperations: () => Promise<void> = async () => {}) {
constructor(private state: string, private hostInstanceId: string, private inventory: InventoryStore, private assertOtherOperations: () => Promise<void> = async () => {},
private getRegistryToken?: (registry: string) => string | undefined) {
this.root = join(dirname(state), 'file-reset-v1')
}
/** Internal filesystem seam; callers cannot choose a cleanup path through the Remote API. */
Expand Down Expand Up @@ -166,7 +167,7 @@ export class FileResetStore {
await this.removeBackup(backup); await syncDirectory(snapshot.target.root)
record.operation.phase = 'completed'; await this.save(record)
}) } finally { await release() }
})
}, this.getRegistryToken?.(snapshot.selection.registry))
} catch {
const current = await this.get(record.operationId, record.ownerId)
if (current?.intent) {
Expand Down
4 changes: 2 additions & 2 deletions cli/src/integrations/native-install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { createInstallTransactionObserver } from './transaction-journal'
import { confirmExistingNativeInstall } from './native-installed'

/** Claim an accepted operation exactly once before performing network or target writes. */
export async function executeNativeInstall(operations: OperationStore, inventory: InventoryStore, request: NativeInstallExecution & { archive?: Uint8Array }): Promise<NativeRecoveryResult> {
export async function executeNativeInstall(operations: OperationStore, inventory: InventoryStore, request: NativeInstallExecution & { archive?: Uint8Array }, token?: string): Promise<NativeRecoveryResult> {
request = { ...request }
const record = await operations.get(request.operationId, request.ownerId)
if (!record || record.operation.kind !== 'install' || record.operation.status.phase !== 'accepted') throw new Error('Installation is not owned and accepted')
Expand All @@ -30,7 +30,7 @@ export async function executeNativeInstall(operations: OperationStore, inventory
await request.authorize([root, target], 'staging')
const existing = request.registry === 'local:import' ? undefined : await confirmExistingNativeInstall(operations, inventory, request)
if (existing) return existing
const client = new SkillHubClient(request.registry)
const client = new SkillHubClient(request.registry, token)
const imported = request.registry === 'local:import'
if (imported !== !!request.archive || imported && (request.namespace !== 'local' || request.version !== 'local')) throw new Error('Invalid local package source')
const resolved = imported ? { namespace: request.namespace, slug: request.slug, version: request.version, versionId: 1, fingerprint: request.fingerprint, downloadUrl: '' } : await client.resolve(request.namespace, request.slug, request.version)
Expand Down
12 changes: 6 additions & 6 deletions cli/src/integrations/native-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ import { recoverRemoval } from './removal-recovery'
import { acquireSkillTargetLock } from '../services/skill-target-lock'

/** Private native adapter. Paths must come from the Host, never a Remote request or tool argument. */
export async function openNativeRuntime(options: { stateDirectory: string; inventoryHome: string }): Promise<NativeRuntime> {
export async function openNativeRuntime(options: { stateDirectory: string; inventoryHome: string; getRegistryToken?: (registry: string) => string | undefined }): Promise<NativeRuntime> {
const operations = await OperationStore.open(options.stateDirectory)
const inventory = new InventoryStore(options.inventoryHome)
const imports = new InventoryStore(join(options.stateDirectory, 'local-imports'))
const storeFor = (registry: string) => registry === LOCAL_PACKAGE_REGISTRY ? imports : inventory
const resets = new FileResetStore(options.stateDirectory, operations.hostInstanceId, inventory, async () => {
if ((await operations.listForRecovery()).length) throw new Error('Operation recovery required')
})
}, options.getRegistryToken)
const ensureCompatible = async () => {
if (await inventory.diskVersion() === 3 && (await operations.listForRecovery()).length) {
throw new OperationStoreError('TARGET_RECOVERY_REQUIRED')
Expand Down Expand Up @@ -65,8 +65,8 @@ export async function openNativeRuntime(options: { stateDirectory: string; inven
return withOperationLease(operations, request.operationId, request.ownerId, () => executeNativeInstall(operations, imports, {...request, authorize}))
},
inspectChanges: (selected, target) => inspectChanges(inventory, selected, target),
readChangeDiff: (snapshot, path) => readChangeDiff(options.stateDirectory, inventory, snapshot, path),
prepareVersionChanges: (selected, target, candidate) => prepareVersionChanges(options.stateDirectory, inventory, selected, target, candidate),
readChangeDiff: (snapshot, path) => readChangeDiff(options.stateDirectory, inventory, snapshot, path, options.getRegistryToken?.((snapshot.kind === 'local' ? snapshot : snapshot.local).selection.registry)),
prepareVersionChanges: (selected, target, candidate) => prepareVersionChanges(options.stateDirectory, inventory, selected, target, candidate, options.getRegistryToken?.(selected.registry)),
backupChanges: (snapshot, authorize) => backupChanges(options.stateDirectory, inventory, snapshot, authorize),
acceptFileReset: async (request, validate) => {
return resets.accept(request, async () => {
Expand Down Expand Up @@ -158,7 +158,7 @@ export async function openNativeRuntime(options: { stateDirectory: string; inven
await ensureCompatible()
const snapshot = { ...request, baseline: structuredClone(request.baseline), ...(request.localChangesAuthorization ? { localChangesAuthorization: structuredClone(request.localChangesAuthorization) } : {}) }
return withOperationLease(operations, snapshot.operationId, snapshot.ownerId,
() => executeNativeUpgrade(operations, inventory, snapshot))
() => executeNativeUpgrade(operations, inventory, snapshot, options.getRegistryToken?.(snapshot.registry)))
},
acceptUpgrade: async (request, validateNew) => {
const result = await operations.accept({ hostInstanceId: request.hostInstanceId, ownerId: request.ownerId,
Expand All @@ -178,7 +178,7 @@ export async function openNativeRuntime(options: { stateDirectory: string; inven
await ensureCompatible()
const snapshot = { ...request }
return withOperationLease(operations, snapshot.operationId, snapshot.ownerId,
() => executeNativeInstall(operations, inventory, {...snapshot, authorize: guardForeignClaims(snapshot, imports)}))
() => executeNativeInstall(operations, inventory, {...snapshot, authorize: guardForeignClaims(snapshot, imports)}, options.getRegistryToken?.(snapshot.registry)))
},
acceptInstall: async (request, validateNew) => {
const result = await operations.accept({ hostInstanceId: request.hostInstanceId, ownerId: request.ownerId,
Expand Down
4 changes: 2 additions & 2 deletions cli/src/integrations/native-upgrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { assertOwnedRegularTree } from './recovery-files'

/** Execute only the complete confirmed snapshot; the shared core owns target locks and inventory CAS. */
export async function executeNativeUpgrade(operations: OperationStore, inventory: InventoryStore,
input: NativeUpgradeExecution): Promise<NativeRecoveryResult> {
input: NativeUpgradeExecution, token?: string): Promise<NativeRecoveryResult> {
const request = { ...input, baseline: structuredClone(input.baseline), ...(input.localChangesAuthorization ? { localChangesAuthorization: structuredClone(input.localChangesAuthorization) } : {}) }
const { baseline } = request
const record = await operations.get(request.operationId, request.ownerId)
Expand Down Expand Up @@ -50,7 +50,7 @@ export async function executeNativeUpgrade(operations: OperationStore, inventory
await durableJson(join(directory, `${record.operationId}.json`), { ownerId: record.ownerId,
authorization: request.localChangesAuthorization })
}
const client = new SkillHubClient(request.registry)
const client = new SkillHubClient(request.registry, token)
const resolved = await client.resolve(request.namespace, request.slug, request.version)
if (resolved.namespace !== request.namespace || resolved.slug !== request.slug || resolved.version !== request.version
|| resolved.versionId !== request.versionId || resolved.fingerprint !== request.fingerprint) throw new Error('Upgrade release changed')
Expand Down
11 changes: 11 additions & 0 deletions cli/test/unit/clients/skillhub-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ describe('SkillHubClient', () => {
expect(requests).toEqual([{ url: new URL(downloadUrl, registry).toString(), authorization: null }])
})

test('keeps the token within the bound API during package redirects', async () => {
const seen: (string | null)[] = []
const fetchImpl = (async (_url: string, init: RequestInit) => {
seen.push(new Headers(init.headers).get('Authorization'))
return seen.length === 1 ? Response.redirect('https://registry.test/storage/package.zip', 302) : new Response('zip')
}) as unknown as typeof fetch
const client = new SkillHubClient('https://registry.test/team', 'fixture-token', fetchImpl)
expect(await (await client.downloadFromUrl('/api/download')).text()).toBe('zip')
expect(seen).toEqual(['Bearer fixture-token', null])
})

test('uses the provided multipart file name when publishing', async () => {
const fetchImpl = (async (_input: URL | RequestInfo, init?: RequestInit) => {
const formData = init?.body as FormData
Expand Down
Loading
Loading