@uapkg/cli 1.3.1 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app/CompositionRoot.js.map +1 -1
- package/dist/app/UAPKGApplication.js.map +1 -1
- package/dist/build/BuildMetadata.js +2 -2
- package/dist/cli/parseCommandLine.js.map +1 -1
- package/dist/cli/parsing/UAPKGCommandLineParser.js.map +1 -1
- package/dist/cli/parsing/UAPKGParserRegistry.js.map +1 -1
- package/dist/cli/parsing/modules/AddCommandModule.js +4 -4
- package/dist/cli/parsing/modules/AddCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/ConfigCommandModule.js +2 -2
- package/dist/cli/parsing/modules/ConfigCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/InitCommandModule.js +2 -2
- package/dist/cli/parsing/modules/InitCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/InstallCommandModule.js +3 -3
- package/dist/cli/parsing/modules/InstallCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/LifecycleCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/ListCommandModule.js +1 -1
- package/dist/cli/parsing/modules/ListCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/LoginCommandModule.js +2 -2
- package/dist/cli/parsing/modules/LoginCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/LogoutCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/OutdatedCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/PackCommandModule.js +2 -2
- package/dist/cli/parsing/modules/PackCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/ProjectGetNameCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/PublishCommandModule.js +3 -3
- package/dist/cli/parsing/modules/PublishCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/RegistryCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/RemoveCommandModule.js +1 -1
- package/dist/cli/parsing/modules/RemoveCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/RequestsCommandModule.js +1 -1
- package/dist/cli/parsing/modules/RequestsCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/UpdateCommandModule.js +3 -3
- package/dist/cli/parsing/modules/UpdateCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/WhoamiCommandModule.d.ts.map +1 -1
- package/dist/cli/parsing/modules/WhoamiCommandModule.js.map +1 -1
- package/dist/cli/parsing/modules/WhyCommandModule.js +1 -1
- package/dist/cli/parsing/modules/WhyCommandModule.js.map +1 -1
- package/dist/cli/runUAPKGCLI.js.map +1 -1
- package/dist/cli-bootstrap.js.map +1 -1
- package/dist/commands/AddCommand.js.map +1 -1
- package/dist/commands/ConfigCommand.js.map +1 -1
- package/dist/commands/InitCommand.d.ts.map +1 -1
- package/dist/commands/InitCommand.js +2 -2
- package/dist/commands/InitCommand.js.map +1 -1
- package/dist/commands/InstallCommand.js.map +1 -1
- package/dist/commands/ListCommand.js.map +1 -1
- package/dist/commands/LoginCommand.js.map +1 -1
- package/dist/commands/LogoutCommand.js.map +1 -1
- package/dist/commands/OutdatedCommand.js.map +1 -1
- package/dist/commands/PackCommand.js.map +1 -1
- package/dist/commands/PackageLifecycleCommand.js.map +1 -1
- package/dist/commands/PostinstallCandidateBuilder.js.map +1 -1
- package/dist/commands/ProjectGetNameCommand.js.map +1 -1
- package/dist/commands/PublishCommand.js.map +1 -1
- package/dist/commands/RegistryCommand.js.map +1 -1
- package/dist/commands/RemoveCommand.js.map +1 -1
- package/dist/commands/RequestsCommand.js.map +1 -1
- package/dist/commands/UpdateCommand.js.map +1 -1
- package/dist/commands/WhoamiCommand.js.map +1 -1
- package/dist/commands/WhyCommand.js.map +1 -1
- package/dist/commands/add/DependencyAddResolver.js.map +1 -1
- package/dist/control-plane/AccountManager.js +1 -1
- package/dist/control-plane/AccountManager.js.map +1 -1
- package/dist/control-plane/AuthMetadataStore.js.map +1 -1
- package/dist/control-plane/AuthenticationSelector.js +5 -5
- package/dist/control-plane/AuthenticationSelector.js.map +1 -1
- package/dist/control-plane/ControlPlaneClient.js.map +1 -1
- package/dist/control-plane/ControlPlaneEndpoints.js.map +1 -1
- package/dist/control-plane/ControlPlaneTypes.js.map +1 -1
- package/dist/control-plane/DPoPKeyStore.js.map +1 -1
- package/dist/control-plane/GitHubActionsOidcCredentialProvider.js.map +1 -1
- package/dist/control-plane/PublishRequestErrorMapper.js.map +1 -1
- package/dist/control-plane/RegistryTrustResolver.js.map +1 -1
- package/dist/postinstall/api/definePostinstall.js.map +1 -1
- package/dist/postinstall/loader/ExportValidator.js.map +1 -1
- package/dist/postinstall/loader/PostinstallLoader.js.map +1 -1
- package/dist/postinstall/markers/MarkerBlockEditor.js.map +1 -1
- package/dist/postinstall/runner/PostinstallOrchestrator.js.map +1 -1
- package/dist/postinstall/unreal/BuildCsInjector.js.map +1 -1
- package/dist/postinstall/unreal/CSharpInjectionEngine.js.map +1 -1
- package/dist/postinstall/unreal/CSharpStructureAnalyzer.d.ts.map +1 -1
- package/dist/postinstall/unreal/CSharpStructureAnalyzer.js.map +1 -1
- package/dist/postinstall/unreal/TargetCsInjector.js.map +1 -1
- package/dist/postinstall/unreal/UnrealSourceCatalog.js.map +1 -1
- package/dist/prompts/InkPromptService.js.map +1 -1
- package/dist/reporting/DiagnosticReporter.js.map +1 -1
- package/dist/reporting/InkDiagnosticRenderer.js.map +1 -1
- package/dist/reporting/InstallProgressReporter.js.map +1 -1
- package/dist/reporting/JsonReporter.js.map +1 -1
- package/dist/reporting/RegistryRequestTerminalFormatter.js +1 -1
- package/dist/reporting/RegistryRequestTerminalFormatter.js.map +1 -1
- package/dist/reporting/TextDiagnosticRenderer.js.map +1 -1
- package/package.json +26 -14
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ControlPlaneEndpoints.js","names":[],"sources":["../../src/control-plane/ControlPlaneEndpoints.ts"],"sourcesContent":["import type { UAPKGBuildMode } from '@uapkg/common';\nimport { UAPKG_BUILD_METADATA } from '
|
|
1
|
+
{"version":3,"file":"ControlPlaneEndpoints.js","names":[],"sources":["../../src/control-plane/ControlPlaneEndpoints.ts"],"sourcesContent":["import type { UAPKGBuildMode } from '@uapkg/common';\nimport { UAPKG_BUILD_METADATA } from '#cli/build/BuildMetadata.ts';\n\nexport interface UAPKGControlPlaneEndpoints {\n readonly issuer: string;\n readonly apiBaseUrl: string;\n}\n\nconst DEVELOPMENT_ENDPOINTS: UAPKGControlPlaneEndpoints = Object.freeze({\n issuer: 'https://account-dev.uapkg.dev/oauth',\n apiBaseUrl: 'https://api-dev.uapkg.dev',\n});\n\nconst PRODUCTION_ENDPOINTS: UAPKGControlPlaneEndpoints = Object.freeze({\n issuer: 'https://account.uapkg.dev/oauth',\n apiBaseUrl: 'https://api.uapkg.dev',\n});\n\n/**\n * Only an explicitly stamped development build can select development trust\n * roots. Source execution and any unrecognized runtime value fail closed to\n * the production control plane.\n */\nexport function controlPlaneEndpointsForBuildMode(mode: UAPKGBuildMode): UAPKGControlPlaneEndpoints {\n return mode === 'development' ? DEVELOPMENT_ENDPOINTS : PRODUCTION_ENDPOINTS;\n}\n\nexport const UAPKG_CONTROL_PLANE_ENDPOINTS = controlPlaneEndpointsForBuildMode(UAPKG_BUILD_METADATA.mode);\n"],"mappings":";;;AAQA,MAAM,wBAAoD,OAAO,OAAO;CACtE,QAAQ;CACR,YAAY;AACd,CAAC;AAED,MAAM,uBAAmD,OAAO,OAAO;CACrE,QAAQ;CACR,YAAY;AACd,CAAC;;;;;;AAOD,SAAgB,kCAAkC,MAAkD;CAClG,OAAO,SAAS,gBAAgB,wBAAwB;AAC1D;AAEA,MAAa,gCAAgC,kCAAkC,qBAAqB,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ControlPlaneTypes.js","names":[],"sources":["../../src/control-plane/ControlPlaneTypes.ts"],"sourcesContent":["import { UAPKG_CONTROL_PLANE_ENDPOINTS } from './ControlPlaneEndpoints.js';\n\nexport const UAPKG_AUTHORIZATION_ISSUER = UAPKG_CONTROL_PLANE_ENDPOINTS.issuer;\nexport const UAPKG_CONTROL_PLANE_API = UAPKG_CONTROL_PLANE_ENDPOINTS.apiBaseUrl;\nexport const UAPKG_CLI_CLIENT_ID = 'uapkg-cli';\nexport const UAPKG_GITHUB_OIDC_AUDIENCE = 'uapkg';\n\nexport const UAPKG_CLI_SCOPES = [\n 'identity.self.read',\n 'publishing.request.create',\n 'publishing.request.read.self',\n 'registry_grant.revoke.self',\n] as const;\n\nexport type UAPKGCliScope = (typeof UAPKG_CLI_SCOPES)[number];\nconst UAPKG_CLI_SCOPE_SET = new Set<string>(UAPKG_CLI_SCOPES);\nconst OAUTH_SCOPE_TOKEN_PATTERN = /^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/;\n\nexport function knownUAPKGCliScopes(value: unknown): UAPKGCliScope[] {\n if (!Array.isArray(value)) return [];\n const candidates = new Set(value.filter((scope): scope is string => typeof scope === 'string'));\n return UAPKG_CLI_SCOPES.filter((scope) => candidates.has(scope));\n}\n\nexport function parseUAPKGCliScopeString(value: unknown): UAPKGCliScope[] {\n return knownUAPKGCliScopes(parseOAuthScopeTokens(value));\n}\n\nexport function parseOAuthScopeTokens(value: unknown): string[] {\n if (typeof value !== 'string' || value.length === 0 || value.trim() !== value) return [];\n const scopes = value.split(' ');\n if (scopes.some((scope) => !isOAuthScopeToken(scope))) return [];\n return [...new Set(scopes)];\n}\n\nexport function isOAuthScopeToken(value: unknown): value is string {\n return typeof value === 'string' && OAUTH_SCOPE_TOKEN_PATTERN.test(value);\n}\n\nexport function isUAPKGCliScope(value: unknown): value is UAPKGCliScope {\n return typeof value === 'string' && UAPKG_CLI_SCOPE_SET.has(value);\n}\n\nexport type ControlPlaneAuthMode = 'auto' | 'login' | 'gat' | 'oidc';\n\nexport interface RegistryTrust {\n readonly alias: string;\n readonly registryId: string;\n readonly registryName: string;\n readonly repositoryUrl: string;\n readonly repositoryFingerprint: string;\n readonly issuer: string;\n readonly apiBaseUrl: string;\n readonly resource: string;\n readonly cacheShortId: string;\n}\n\nexport interface AccountDisplayMetadata {\n readonly id: string;\n readonly username: string;\n readonly displayName: string;\n}\n\nexport interface AccountSelf {\n readonly account: AccountDisplayMetadata;\n readonly registry: {\n readonly id: string;\n };\n readonly grant: {\n readonly id: string;\n readonly deviceName: string;\n readonly idleExpiresAt: string;\n readonly absoluteExpiresAt: string;\n readonly scopes: readonly string[];\n };\n}\n\nexport interface CliLoginConfirmation extends AccountSelf {\n readonly grant: AccountSelf['grant'] & {\n readonly status: 'pending' | 'active';\n readonly activationExpiresAt: string;\n readonly replacesGrantId: string | null;\n };\n}\n\nexport interface ActivatedCliLoginGrant {\n readonly id: string;\n readonly status: 'active';\n readonly replacesGrantId: string | null;\n}\n\nexport interface RegistryGrantMetadata {\n readonly issuer: string;\n readonly registryId: string;\n readonly registryName: string;\n readonly grantId: string;\n readonly clientId: string;\n readonly keyReference: string;\n readonly refreshTokenReference: string;\n readonly publicKeyThumbprint: string;\n readonly deviceName: string;\n readonly repositoryFingerprint: string;\n readonly account: AccountDisplayMetadata;\n readonly createdAt: number;\n readonly idleExpiresAt: number;\n readonly expiresAt: number;\n}\n\nexport interface AuthMetadataFile {\n readonly schemaVersion: 1;\n readonly grants: Readonly<Record<string, RegistryGrantMetadata>>;\n}\n\nexport interface RegistryRequestSource {\n readonly type: 'github_release';\n readonly repository: string;\n readonly releaseTag: string;\n readonly assetName: string;\n}\n\n/** Artifact integrity observed by this client from the exact bytes it inspected. */\nexport interface ObservedArtifactIntegrity {\n /** Exactly `sha256:` + 64 lowercase hex characters. */\n readonly sha256: string;\n readonly sizeBytes: number;\n}\n\n/** Normalized packaged-manifest claims submitted with a publish request. */\nexport interface SubmittedPackageClaims {\n readonly name: string;\n readonly version: string;\n readonly private: boolean;\n readonly dependencies: Readonly<Record<string, { readonly version: string; readonly registry?: string }>>;\n readonly devDependencies: Readonly<Record<string, { readonly version: string; readonly registry?: string }>>;\n readonly peerDependencies: Readonly<Record<string, { readonly version: string; readonly registry?: string }>>;\n}\n\n/** The six route-derived registry operations (PS-REQ-001). */\nexport type RegistryOperation = 'publish' | 'unpublish' | 'yank' | 'unyank' | 'deprecate' | 'undeprecate';\n\n/**\n * Body for `POST /v1/registry-requests/{operation}`. The operation is\n * derived from the route; the body never carries a kind.\n */\nexport interface RegistryRequestSubmission {\n readonly registryId: string;\n readonly ownerOrganizationName?: string;\n readonly payload: {\n readonly packageName: string;\n readonly packageVersion: string;\n readonly source?: RegistryRequestSource;\n readonly observedIntegrity?: ObservedArtifactIntegrity;\n readonly claims?: SubmittedPackageClaims;\n readonly reason?: string;\n };\n}\n\nexport type RegistryRequestStatus =\n | 'queued'\n | 'checking'\n | 'accepted'\n | 'ready'\n | 'ready_superseded'\n | 'rejected'\n | 'operationally_failed';\n\nexport interface RegistryRequestSummary {\n readonly id: string;\n readonly registryId: string;\n readonly kind: string;\n readonly status: RegistryRequestStatus;\n readonly currentStep?: string;\n readonly createdAt?: number;\n readonly updatedAt?: number;\n readonly payload?: {\n readonly packageName?: string;\n readonly packageVersion?: string;\n };\n}\n\nexport type RegistryRequestCheckExecutionState =\n | 'pending'\n | 'running'\n | 'retrying'\n | 'blocked_by_dependency'\n | 'completed';\n\nexport type RegistryRequestCheckConclusion = 'success' | 'failure' | 'skipped';\n\n/** One bounded, caller-visible result from the request's sealed check plan. */\nexport interface RegistryRequestCheck {\n readonly checkId: string;\n readonly executionState: RegistryRequestCheckExecutionState;\n readonly conclusion?: RegistryRequestCheckConclusion;\n readonly reasonCode?: string;\n}\n\n/** Sanitized durable retry-exhaustion details for an operational failure. */\nexport interface RegistryRequestTerminalFailure {\n readonly reasonCode: string;\n readonly attempts?: number;\n readonly maxAttempts?: number;\n}\n\n/** Additive detail returned by the request-status endpoint. */\nexport interface RegistryRequestDetail {\n readonly request: RegistryRequestSummary;\n readonly checks?: readonly RegistryRequestCheck[];\n readonly terminalFailure?: RegistryRequestTerminalFailure;\n}\n\nexport interface ControlPlaneApiErrorBody {\n readonly ok: false;\n readonly error: {\n readonly code: string;\n readonly message: string;\n readonly details?: Readonly<Record<string, unknown>>;\n };\n}\n\nexport class ControlPlaneError extends Error {\n public constructor(\n public readonly code: string,\n message: string,\n public readonly status?: number,\n public readonly details?: Readonly<Record<string, unknown>>,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'ControlPlaneError';\n }\n}\n\nexport class OAuthScopeInsufficientError extends ControlPlaneError {\n public readonly requestedScopes: readonly UAPKGCliScope[];\n public readonly requiredScopes: readonly UAPKGCliScope[];\n public readonly missingScopes: readonly UAPKGCliScope[];\n\n public constructor(\n message: string,\n public readonly registryAlias: string,\n requestedScopes: readonly UAPKGCliScope[],\n requiredScopes: readonly UAPKGCliScope[],\n missingScopes: readonly UAPKGCliScope[],\n status = 403,\n options?: ErrorOptions,\n ) {\n const requested = knownUAPKGCliScopes(requestedScopes);\n const required = knownUAPKGCliScopes(requiredScopes);\n const missing = knownUAPKGCliScopes(missingScopes).filter(\n (scope) => requested.includes(scope) && required.includes(scope),\n );\n super(\n 'OAUTH_SCOPE_INSUFFICIENT',\n message,\n status,\n { requestedScopes: requested, requiredScopes: required, missingScopes: missing },\n options,\n );\n this.name = 'OAuthScopeInsufficientError';\n this.requestedScopes = requested;\n this.requiredScopes = required;\n this.missingScopes = missing;\n }\n}\n\nexport class OAuthScopeUnsupportedError extends ControlPlaneError {\n public readonly requestedScopes: readonly UAPKGCliScope[];\n public readonly unsupportedScopes: readonly UAPKGCliScope[];\n public readonly reason: 'issuer-does-not-support-requested-scope' | 'cli-update-required';\n\n public constructor(\n public readonly registryAlias: string,\n requestedScopes: readonly UAPKGCliScope[],\n unsupportedScopes: readonly UAPKGCliScope[],\n options?: ErrorOptions & {\n readonly reason?: 'issuer-does-not-support-requested-scope' | 'cli-update-required';\n readonly status?: number;\n },\n ) {\n const requested = knownUAPKGCliScopes(requestedScopes);\n const unsupported = knownUAPKGCliScopes(unsupportedScopes).filter((scope) => requested.includes(scope));\n const reason = options?.reason ?? 'issuer-does-not-support-requested-scope';\n const message =\n reason === 'cli-update-required'\n ? `The authorization service for \"${registryAlias}\" requires an OAuth capability that this UAPKG CLI version does not recognize. Update UAPKG CLI and try again.`\n : unsupportedIssuerScopeMessage(registryAlias, unsupported);\n super(\n 'OAUTH_SCOPE_UNSUPPORTED',\n message,\n options?.status,\n { requestedScopes: requested, unsupportedScopes: unsupported, reason },\n options,\n );\n this.name = 'OAuthScopeUnsupportedError';\n this.requestedScopes = requested;\n this.unsupportedScopes = unsupported;\n this.reason = reason;\n }\n}\n\nfunction unsupportedIssuerScopeMessage(registryAlias: string, unsupportedScopes: readonly UAPKGCliScope[]): string {\n const noun = unsupportedScopes.length === 1 ? 'scope' : 'scopes';\n return `The authorization service for \"${registryAlias}\" does not support the OAuth ${noun} required by this UAPKG CLI: ${unsupportedScopes.join(', ')}. Update UAPKG CLI and try again; if it is already current, the authorization service must be updated.`;\n}\n\nexport function registryAudience(registryId: string): string {\n return `${UAPKG_CONTROL_PLANE_API}/v1/registries/${encodeURIComponent(registryId)}`;\n}\n"],"mappings":";;;AAEA,MAAa,6BAA6B,8BAA8B;AACxE,MAAa,0BAA0B,8BAA8B;AACrE,MAAa,sBAAsB;AACnC,MAAa,6BAA6B;AAE1C,MAAa,mBAAmB;CAC9B;CACA;CACA;CACA;AACF;AAGA,MAAM,sBAAsB,IAAI,IAAY,gBAAgB;AAC5D,MAAM,4BAA4B;AAElC,SAAgB,oBAAoB,OAAiC;CACnE,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC;CACnC,MAAM,aAAa,IAAI,IAAI,MAAM,QAAQ,UAA2B,OAAO,UAAU,QAAQ,CAAC;CAC9F,OAAO,iBAAiB,QAAQ,UAAU,WAAW,IAAI,KAAK,CAAC;AACjE;AAEA,SAAgB,yBAAyB,OAAiC;CACxE,OAAO,oBAAoB,sBAAsB,KAAK,CAAC;AACzD;AAEA,SAAgB,sBAAsB,OAA0B;CAC9D,IAAI,OA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;EACA,MAAM,YAAY,oBAAoB,eAAe;EACrD,MAAM,cAAc,oBAAoB,iBAAiB,CAAC,CAAC,QAAQ,UAAU,UAAU,SAAS,KAAK,CAAC;EACtG,MAAM,SAAS,SAAS,UAAU;EAClC,MAAM,UACJ,WAAW,wBACP,kCAAkC,cAAc,kHAChD,8BAA8B,eAAe,WAAW;EAC9D,MACE,2BACA,SACA,SAAS,QACT;GAAE,iBAAiB;GAAW,mBAAmB;GAAa;EAAO,GACrE,OACF;EArBgB;EAsBhB,KAAK,OAAO;EACZ,KAAK,kBAAkB;EACvB,KAAK,oBAAoB;EACzB,KAAK,SAAS;CAChB;AACF;AAEA,SAAS,8BAA8B,eAAuB,mBAAqD;CAEjH,OAAO,kCAAkC,cAAc,+BAD1C,kBAAkB,WAAW,IAAI,UAAU,SACmC,+BAA+B,kBAAkB,KAAK,IAAI,EAAE;AACzJ;AAEA,SAAgB,iBAAiB,YAA4B;CAC3D,OAAO,GAAG,wBAAwB,iBAAiB,mBAAmB,UAAU;AAClF"}
|
|
1
|
+
{"version":3,"file":"ControlPlaneTypes.js","names":[],"sources":["../../src/control-plane/ControlPlaneTypes.ts"],"sourcesContent":["import { UAPKG_CONTROL_PLANE_ENDPOINTS } from '#cli/control-plane/ControlPlaneEndpoints.ts';\n\nexport const UAPKG_AUTHORIZATION_ISSUER = UAPKG_CONTROL_PLANE_ENDPOINTS.issuer;\nexport const UAPKG_CONTROL_PLANE_API = UAPKG_CONTROL_PLANE_ENDPOINTS.apiBaseUrl;\nexport const UAPKG_CLI_CLIENT_ID = 'uapkg-cli';\nexport const UAPKG_GITHUB_OIDC_AUDIENCE = 'uapkg';\n\nexport const UAPKG_CLI_SCOPES = [\n 'identity.self.read',\n 'publishing.request.create',\n 'publishing.request.read.self',\n 'registry_grant.revoke.self',\n] as const;\n\nexport type UAPKGCliScope = (typeof UAPKG_CLI_SCOPES)[number];\nconst UAPKG_CLI_SCOPE_SET = new Set<string>(UAPKG_CLI_SCOPES);\nconst OAUTH_SCOPE_TOKEN_PATTERN = /^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/;\n\nexport function knownUAPKGCliScopes(value: unknown): UAPKGCliScope[] {\n if (!Array.isArray(value)) return [];\n const candidates = new Set(value.filter((scope): scope is string => typeof scope === 'string'));\n return UAPKG_CLI_SCOPES.filter((scope) => candidates.has(scope));\n}\n\nexport function parseUAPKGCliScopeString(value: unknown): UAPKGCliScope[] {\n return knownUAPKGCliScopes(parseOAuthScopeTokens(value));\n}\n\nexport function parseOAuthScopeTokens(value: unknown): string[] {\n if (typeof value !== 'string' || value.length === 0 || value.trim() !== value) return [];\n const scopes = value.split(' ');\n if (scopes.some((scope) => !isOAuthScopeToken(scope))) return [];\n return [...new Set(scopes)];\n}\n\nexport function isOAuthScopeToken(value: unknown): value is string {\n return typeof value === 'string' && OAUTH_SCOPE_TOKEN_PATTERN.test(value);\n}\n\nexport function isUAPKGCliScope(value: unknown): value is UAPKGCliScope {\n return typeof value === 'string' && UAPKG_CLI_SCOPE_SET.has(value);\n}\n\nexport type ControlPlaneAuthMode = 'auto' | 'login' | 'gat' | 'oidc';\n\nexport interface RegistryTrust {\n readonly alias: string;\n readonly registryId: string;\n readonly registryName: string;\n readonly repositoryUrl: string;\n readonly repositoryFingerprint: string;\n readonly issuer: string;\n readonly apiBaseUrl: string;\n readonly resource: string;\n readonly cacheShortId: string;\n}\n\nexport interface AccountDisplayMetadata {\n readonly id: string;\n readonly username: string;\n readonly displayName: string;\n}\n\nexport interface AccountSelf {\n readonly account: AccountDisplayMetadata;\n readonly registry: {\n readonly id: string;\n };\n readonly grant: {\n readonly id: string;\n readonly deviceName: string;\n readonly idleExpiresAt: string;\n readonly absoluteExpiresAt: string;\n readonly scopes: readonly string[];\n };\n}\n\nexport interface CliLoginConfirmation extends AccountSelf {\n readonly grant: AccountSelf['grant'] & {\n readonly status: 'pending' | 'active';\n readonly activationExpiresAt: string;\n readonly replacesGrantId: string | null;\n };\n}\n\nexport interface ActivatedCliLoginGrant {\n readonly id: string;\n readonly status: 'active';\n readonly replacesGrantId: string | null;\n}\n\nexport interface RegistryGrantMetadata {\n readonly issuer: string;\n readonly registryId: string;\n readonly registryName: string;\n readonly grantId: string;\n readonly clientId: string;\n readonly keyReference: string;\n readonly refreshTokenReference: string;\n readonly publicKeyThumbprint: string;\n readonly deviceName: string;\n readonly repositoryFingerprint: string;\n readonly account: AccountDisplayMetadata;\n readonly createdAt: number;\n readonly idleExpiresAt: number;\n readonly expiresAt: number;\n}\n\nexport interface AuthMetadataFile {\n readonly schemaVersion: 1;\n readonly grants: Readonly<Record<string, RegistryGrantMetadata>>;\n}\n\nexport interface RegistryRequestSource {\n readonly type: 'github_release';\n readonly repository: string;\n readonly releaseTag: string;\n readonly assetName: string;\n}\n\n/** Artifact integrity observed by this client from the exact bytes it inspected. */\nexport interface ObservedArtifactIntegrity {\n /** Exactly `sha256:` + 64 lowercase hex characters. */\n readonly sha256: string;\n readonly sizeBytes: number;\n}\n\n/** Normalized packaged-manifest claims submitted with a publish request. */\nexport interface SubmittedPackageClaims {\n readonly name: string;\n readonly version: string;\n readonly private: boolean;\n readonly dependencies: Readonly<Record<string, { readonly version: string; readonly registry?: string }>>;\n readonly devDependencies: Readonly<Record<string, { readonly version: string; readonly registry?: string }>>;\n readonly peerDependencies: Readonly<Record<string, { readonly version: string; readonly registry?: string }>>;\n}\n\n/** The six route-derived registry operations (PS-REQ-001). */\nexport type RegistryOperation = 'publish' | 'unpublish' | 'yank' | 'unyank' | 'deprecate' | 'undeprecate';\n\n/**\n * Body for `POST /v1/registry-requests/{operation}`. The operation is\n * derived from the route; the body never carries a kind.\n */\nexport interface RegistryRequestSubmission {\n readonly registryId: string;\n readonly ownerOrganizationName?: string;\n readonly payload: {\n readonly packageName: string;\n readonly packageVersion: string;\n readonly source?: RegistryRequestSource;\n readonly observedIntegrity?: ObservedArtifactIntegrity;\n readonly claims?: SubmittedPackageClaims;\n readonly reason?: string;\n };\n}\n\nexport type RegistryRequestStatus =\n | 'queued'\n | 'checking'\n | 'accepted'\n | 'ready'\n | 'ready_superseded'\n | 'rejected'\n | 'operationally_failed';\n\nexport interface RegistryRequestSummary {\n readonly id: string;\n readonly registryId: string;\n readonly kind: string;\n readonly status: RegistryRequestStatus;\n readonly currentStep?: string;\n readonly createdAt?: number;\n readonly updatedAt?: number;\n readonly payload?: {\n readonly packageName?: string;\n readonly packageVersion?: string;\n };\n}\n\nexport type RegistryRequestCheckExecutionState =\n | 'pending'\n | 'running'\n | 'retrying'\n | 'blocked_by_dependency'\n | 'completed';\n\nexport type RegistryRequestCheckConclusion = 'success' | 'failure' | 'skipped';\n\n/** One bounded, caller-visible result from the request's sealed check plan. */\nexport interface RegistryRequestCheck {\n readonly checkId: string;\n readonly executionState: RegistryRequestCheckExecutionState;\n readonly conclusion?: RegistryRequestCheckConclusion;\n readonly reasonCode?: string;\n}\n\n/** Sanitized durable retry-exhaustion details for an operational failure. */\nexport interface RegistryRequestTerminalFailure {\n readonly reasonCode: string;\n readonly attempts?: number;\n readonly maxAttempts?: number;\n}\n\n/** Additive detail returned by the request-status endpoint. */\nexport interface RegistryRequestDetail {\n readonly request: RegistryRequestSummary;\n readonly checks?: readonly RegistryRequestCheck[];\n readonly terminalFailure?: RegistryRequestTerminalFailure;\n}\n\nexport interface ControlPlaneApiErrorBody {\n readonly ok: false;\n readonly error: {\n readonly code: string;\n readonly message: string;\n readonly details?: Readonly<Record<string, unknown>>;\n };\n}\n\nexport class ControlPlaneError extends Error {\n public constructor(\n public readonly code: string,\n message: string,\n public readonly status?: number,\n public readonly details?: Readonly<Record<string, unknown>>,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'ControlPlaneError';\n }\n}\n\nexport class OAuthScopeInsufficientError extends ControlPlaneError {\n public readonly requestedScopes: readonly UAPKGCliScope[];\n public readonly requiredScopes: readonly UAPKGCliScope[];\n public readonly missingScopes: readonly UAPKGCliScope[];\n\n public constructor(\n message: string,\n public readonly registryAlias: string,\n requestedScopes: readonly UAPKGCliScope[],\n requiredScopes: readonly UAPKGCliScope[],\n missingScopes: readonly UAPKGCliScope[],\n status = 403,\n options?: ErrorOptions,\n ) {\n const requested = knownUAPKGCliScopes(requestedScopes);\n const required = knownUAPKGCliScopes(requiredScopes);\n const missing = knownUAPKGCliScopes(missingScopes).filter(\n (scope) => requested.includes(scope) && required.includes(scope),\n );\n super(\n 'OAUTH_SCOPE_INSUFFICIENT',\n message,\n status,\n { requestedScopes: requested, requiredScopes: required, missingScopes: missing },\n options,\n );\n this.name = 'OAuthScopeInsufficientError';\n this.requestedScopes = requested;\n this.requiredScopes = required;\n this.missingScopes = missing;\n }\n}\n\nexport class OAuthScopeUnsupportedError extends ControlPlaneError {\n public readonly requestedScopes: readonly UAPKGCliScope[];\n public readonly unsupportedScopes: readonly UAPKGCliScope[];\n public readonly reason: 'issuer-does-not-support-requested-scope' | 'cli-update-required';\n\n public constructor(\n public readonly registryAlias: string,\n requestedScopes: readonly UAPKGCliScope[],\n unsupportedScopes: readonly UAPKGCliScope[],\n options?: ErrorOptions & {\n readonly reason?: 'issuer-does-not-support-requested-scope' | 'cli-update-required';\n readonly status?: number;\n },\n ) {\n const requested = knownUAPKGCliScopes(requestedScopes);\n const unsupported = knownUAPKGCliScopes(unsupportedScopes).filter((scope) => requested.includes(scope));\n const reason = options?.reason ?? 'issuer-does-not-support-requested-scope';\n const message =\n reason === 'cli-update-required'\n ? `The authorization service for \"${registryAlias}\" requires an OAuth capability that this UAPKG CLI version does not recognize. Update UAPKG CLI and try again.`\n : unsupportedIssuerScopeMessage(registryAlias, unsupported);\n super(\n 'OAUTH_SCOPE_UNSUPPORTED',\n message,\n options?.status,\n { requestedScopes: requested, unsupportedScopes: unsupported, reason },\n options,\n );\n this.name = 'OAuthScopeUnsupportedError';\n this.requestedScopes = requested;\n this.unsupportedScopes = unsupported;\n this.reason = reason;\n }\n}\n\nfunction unsupportedIssuerScopeMessage(registryAlias: string, unsupportedScopes: readonly UAPKGCliScope[]): string {\n const noun = unsupportedScopes.length === 1 ? 'scope' : 'scopes';\n return `The authorization service for \"${registryAlias}\" does not support the OAuth ${noun} required by this UAPKG CLI: ${unsupportedScopes.join(', ')}. Update UAPKG CLI and try again; if it is already current, the authorization service must be updated.`;\n}\n\nexport function registryAudience(registryId: string): string {\n return `${UAPKG_CONTROL_PLANE_API}/v1/registries/${encodeURIComponent(registryId)}`;\n}\n"],"mappings":";;;AAEA,MAAa,6BAA6B,8BAA8B;AACxE,MAAa,0BAA0B,8BAA8B;AACrE,MAAa,sBAAsB;AACnC,MAAa,6BAA6B;AAE1C,MAAa,mBAAmB;CAC9B;CACA;CACA;CACA;AACF;AAGA,MAAM,sBAAsB,IAAI,IAAY,gBAAgB;AAC5D,MAAM,4BAA4B;AAElC,SAAgB,oBAAoB,OAAiC;CACnE,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC;CACnC,MAAM,aAAa,IAAI,IAAI,MAAM,QAAQ,UAA2B,OAAO,UAAU,QAAQ,CAAC;CAC9F,OAAO,iBAAiB,QAAQ,UAAU,WAAW,IAAI,KAAK,CAAC;AACjE;AAEA,SAAgB,yBAAyB,OAAiC;CACxE,OAAO,oBAAoB,sBAAsB,KAAK,CAAC;AACzD;AAEA,SAAgB,sBAAsB,OAA0B;CAC9D,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,KAAK,MAAM,KAAK,MAAM,OAAO,OAAO,CAAC;CACvF,MAAM,SAAS,MAAM,MAAM,GAAG;CAC9B,IAAI,OAAO,MAAM,UAAU,CAAC,kBAAkB,KAAK,CAAC,GAAG,OAAO,CAAC;CAC/D,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC5B;AAEA,SAAgB,kBAAkB,OAAiC;CACjE,OAAO,OAAO,UAAU,YAAY,0BAA0B,KAAK,KAAK;AAC1E;AAEA,SAAgB,gBAAgB,OAAwC;CACtE,OAAO,OAAO,UAAU,YAAY,oBAAoB,IAAI,KAAK;AACnE;AAmLA,IAAa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eAAuB,mBAAqD;CAEjH,OAAO,kCAAkC,cAAc,+BAD1C,kBAAkB,WAAW,IAAI,UAAU,SACmC,+BAA+B,kBAAkB,KAAK,IAAI,EAAE;AACzJ;AAEA,SAAgB,iBAAiB,YAA4B;CAC3D,OAAO,GAAG,wBAAwB,iBAAiB,mBAAmB,UAAU;AAClF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DPoPKeyStore.js","names":[],"sources":["../../src/control-plane/DPoPKeyStore.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport type * as oauth from 'oauth4webapi';\nimport type { CredentialStore } from '
|
|
1
|
+
{"version":3,"file":"DPoPKeyStore.js","names":[],"sources":["../../src/control-plane/DPoPKeyStore.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport type * as oauth from 'oauth4webapi';\nimport type { CredentialStore } from '#cli/control-plane/CredentialStore.ts';\n\ninterface SerializedDPoPKeyPair {\n readonly algorithm: 'ES256';\n readonly publicKey: webcrypto.JsonWebKey;\n readonly privateKey: webcrypto.JsonWebKey;\n}\n\nexport class DPoPKeyStore {\n public constructor(private readonly credentials: CredentialStore) {}\n\n public async generate(): Promise<oauth.CryptoKeyPair> {\n const { generateKeyPair } = await import('oauth4webapi');\n return generateKeyPair('ES256', { extractable: true });\n }\n\n public async save(reference: string, pair: oauth.CryptoKeyPair): Promise<void> {\n const [publicKey, privateKey] = await Promise.all([\n webcrypto.subtle.exportKey('jwk', pair.publicKey),\n webcrypto.subtle.exportKey('jwk', pair.privateKey),\n ]);\n const serialized: SerializedDPoPKeyPair = {\n algorithm: 'ES256',\n publicKey,\n privateKey,\n };\n await this.credentials.set(reference, JSON.stringify(serialized));\n }\n\n public async load(reference: string): Promise<oauth.CryptoKeyPair | undefined> {\n const raw = await this.credentials.get(reference);\n if (!raw) return undefined;\n\n let saved: SerializedDPoPKeyPair;\n try {\n saved = JSON.parse(raw) as SerializedDPoPKeyPair;\n } catch (error) {\n throw new Error('The saved UAPKG DPoP key is not valid JSON.', { cause: error });\n }\n if (saved.algorithm !== 'ES256' || !saved.publicKey || !saved.privateKey) {\n throw new Error('The saved UAPKG DPoP key has an unsupported format.');\n }\n\n const algorithm: webcrypto.EcKeyImportParams = { name: 'ECDSA', namedCurve: 'P-256' };\n const [publicKey, privateKey] = await Promise.all([\n webcrypto.subtle.importKey('jwk', saved.publicKey, algorithm, true, ['verify']),\n webcrypto.subtle.importKey('jwk', saved.privateKey, algorithm, true, ['sign']),\n ]);\n const challenge = webcrypto.getRandomValues(new Uint8Array(32));\n const signature = await webcrypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, challenge);\n const matches = await webcrypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, publicKey, signature, challenge);\n if (!matches) {\n throw new Error('The saved UAPKG DPoP public and private keys do not match.');\n }\n return { publicKey, privateKey } as oauth.CryptoKeyPair;\n }\n\n public async delete(reference: string): Promise<void> {\n await this.credentials.delete(reference);\n }\n}\n"],"mappings":";;;AAUA,IAAa,eAAb,MAA0B;CACY;CAApC,AAAO,YAAY,AAAiB,aAA8B;EAA9B;CAA+B;CAEnE,MAAa,WAAyC;EACpD,MAAM,EAAE,oBAAoB,MAAM,OAAO;EACzC,OAAO,gBAAgB,SAAS,EAAE,aAAa,KAAK,CAAC;CACvD;CAEA,MAAa,KAAK,WAAmB,MAA0C;EAC7E,MAAM,CAAC,WAAW,cAAc,MAAM,QAAQ,IAAI,CAChD,UAAU,OAAO,UAAU,OAAO,KAAK,SAAS,GAChD,UAAU,OAAO,UAAU,OAAO,KAAK,UAAU,CACnD,CAAC;EACD,MAAM,aAAoC;GACxC,WAAW;GACX;GACA;EACF;EACA,MAAM,KAAK,YAAY,IAAI,WAAW,KAAK,UAAU,UAAU,CAAC;CAClE;CAEA,MAAa,KAAK,WAA6D;EAC7E,MAAM,MAAM,MAAM,KAAK,YAAY,IAAI,SAAS;EAChD,IAAI,CAAC,KAAK,OAAO;EAEjB,IAAI;EACJ,IAAI;GACF,QAAQ,KAAK,MAAM,GAAG;EACxB,SAAS,OAAO;GACd,MAAM,IAAI,MAAM,+CAA+C,EAAE,OAAO,MAAM,CAAC;EACjF;EACA,IAAI,MAAM,cAAc,WAAW,CAAC,MAAM,aAAa,CAAC,MAAM,YAC5D,MAAM,IAAI,MAAM,qDAAqD;EAGvE,MAAM,YAAyC;GAAE,MAAM;GAAS,YAAY;EAAQ;EACpF,MAAM,CAAC,WAAW,cAAc,MAAM,QAAQ,IAAI,CAChD,UAAU,OAAO,UAAU,OAAO,MAAM,WAAW,WAAW,MAAM,CAAC,QAAQ,CAAC,GAC9E,UAAU,OAAO,UAAU,OAAO,MAAM,YAAY,WAAW,MAAM,CAAC,MAAM,CAAC,CAC/E,CAAC;EACD,MAAM,YAAY,UAAU,gCAAgB,IAAI,WAAW,EAAE,CAAC;EAC9D,MAAM,YAAY,MAAM,UAAU,OAAO,KAAK;GAAE,MAAM;GAAS,MAAM;EAAU,GAAG,YAAY,SAAS;EAEvG,IAAI,CAAC,MADiB,UAAU,OAAO,OAAO;GAAE,MAAM;GAAS,MAAM;EAAU,GAAG,WAAW,WAAW,SAAS,GAE/G,MAAM,IAAI,MAAM,4DAA4D;EAE9E,OAAO;GAAE;GAAW;EAAW;CACjC;CAEA,MAAa,OAAO,WAAkC;EACpD,MAAM,KAAK,YAAY,OAAO,SAAS;CACzC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GitHubActionsOidcCredentialProvider.js","names":[],"sources":["../../src/control-plane/GitHubActionsOidcCredentialProvider.ts"],"sourcesContent":["import { z } from 'zod';\nimport {\n ControlPlaneError,\n type RegistryTrust,\n UAPKG_CONTROL_PLANE_API,\n UAPKG_GITHUB_OIDC_AUDIENCE,\n} from './ControlPlaneTypes.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_RESPONSE_BYTES = 64 * 1024;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_RETRY_DELAY_MS = 1_000;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 30_000;\nconst RETRYABLE_STATUS_CODES = new Set([429, 503]);\n\nconst githubResponseSchema = z.strictObject({ value: z.string().min(1) });\nconst exchangeResponseSchema = z.strictObject({\n ok: z.literal(true),\n token: z.string().min(1),\n expiresAt: z.number().int().positive(),\n});\nconst exchangeErrorSchema = z.strictObject({\n ok: z.literal(false),\n error: z.strictObject({\n code: z.string().min(1),\n message: z.string().min(1),\n details: z.record(z.string(), z.unknown()).optional(),\n }),\n});\n\nexport type GitHubActionsOidcErrorCode =\n | 'OIDC_CONTROL_PLANE_UNTRUSTED'\n | 'OIDC_EXCHANGE_TARGET_INVALID'\n | 'OIDC_GITHUB_CONTEXT_UNAVAILABLE'\n | 'OIDC_GITHUB_ENDPOINT_INVALID'\n | 'OIDC_GITHUB_TOKEN_REQUEST_FAILED'\n | 'OIDC_GITHUB_TOKEN_REQUEST_TIMEOUT'\n | 'OIDC_GITHUB_TOKEN_REJECTED'\n | 'OIDC_GITHUB_TOKEN_RESPONSE_INVALID'\n | 'OIDC_GITHUB_TOKEN_RESPONSE_TOO_LARGE'\n | 'OIDC_EXCHANGE_REQUEST_FAILED'\n | 'OIDC_EXCHANGE_REQUEST_TIMEOUT'\n | 'OIDC_EXCHANGE_REJECTED'\n | 'OIDC_EXCHANGE_RESPONSE_INVALID'\n | 'OIDC_EXCHANGE_RESPONSE_TOO_LARGE';\n\n/** Stable local failures from the GitHub Actions OIDC credential flow. */\nexport class GitHubActionsOidcError extends Error {\n public constructor(\n public readonly code: GitHubActionsOidcErrorCode,\n message: string,\n public readonly status?: number,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'GitHubActionsOidcError';\n }\n}\n\nexport interface GitHubActionsOidcCredentialProviderOptions {\n readonly fetch?: typeof fetch;\n readonly sleep?: (milliseconds: number) => Promise<void>;\n readonly requestTimeoutMs?: number;\n readonly maxResponseBytes?: number;\n readonly maxAttempts?: number;\n readonly maxRetryDelayMs?: number;\n}\n\n/** Package selector bound into every UAPKG OIDC exchange. */\nexport interface GitHubActionsOidcTarget {\n readonly registryId: string;\n readonly packageName: string;\n}\n\ntype OidcEndpoint = 'github' | 'exchange';\n\nexport class GitHubActionsOidcCredentialProvider {\n private readonly fetch: typeof fetch;\n private readonly sleep: (milliseconds: number) => Promise<void>;\n private readonly requestTimeoutMs: number;\n private readonly maxResponseBytes: number;\n private readonly maxAttempts: number;\n private readonly maxRetryDelayMs: number;\n\n public constructor(options: GitHubActionsOidcCredentialProviderOptions = {}) {\n this.fetch = options.fetch ?? globalThis.fetch;\n this.sleep = options.sleep ?? delay;\n this.requestTimeoutMs = positiveInteger(options.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS);\n this.maxResponseBytes = positiveInteger(options.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES);\n this.maxAttempts = positiveInteger(options.maxAttempts, DEFAULT_MAX_ATTEMPTS);\n this.maxRetryDelayMs = positiveInteger(options.maxRetryDelayMs, DEFAULT_MAX_RETRY_DELAY_MS);\n }\n\n public isAvailable(): boolean {\n return Boolean(\n process.env.GITHUB_ACTIONS === 'true' ||\n process.env.ACTIONS_ID_TOKEN_REQUEST_URL ||\n process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN,\n );\n }\n\n public async exchange(trust: RegistryTrust, target: GitHubActionsOidcTarget): Promise<string> {\n if (trust.apiBaseUrl !== UAPKG_CONTROL_PLANE_API) {\n throw new GitHubActionsOidcError(\n 'OIDC_CONTROL_PLANE_UNTRUSTED',\n `UAPKG v1 OIDC exchange is pinned to ${UAPKG_CONTROL_PLANE_API}.`,\n );\n }\n const packageName = target.packageName.trim();\n if (target.registryId !== trust.registryId || !packageName) {\n throw new GitHubActionsOidcError(\n 'OIDC_EXCHANGE_TARGET_INVALID',\n 'GitHub Actions OIDC requires the exact trusted registry and packaged package name.',\n );\n }\n const requestUrl = process.env.ACTIONS_ID_TOKEN_REQUEST_URL;\n const requestToken = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;\n if (!this.isAvailable() || !requestUrl || !requestToken) {\n throw new GitHubActionsOidcError(\n 'OIDC_GITHUB_CONTEXT_UNAVAILABLE',\n 'GitHub Actions OIDC was selected but its identity-token endpoint is unavailable. The workflow must grant `id-token: write`.',\n );\n }\n\n const url = parseGitHubOidcEndpoint(requestUrl);\n url.searchParams.set('audience', UAPKG_GITHUB_OIDC_AUDIENCE);\n\n const githubResponse = await this.fetchWithRetry(\n url,\n {\n headers: { authorization: `Bearer ${requestToken}` },\n },\n 'github',\n );\n const githubValue = githubResponseSchema.safeParse(await this.readJson(githubResponse, 'github'));\n if (!githubResponse.ok) {\n throw new GitHubActionsOidcError(\n 'OIDC_GITHUB_TOKEN_REJECTED',\n `GitHub Actions did not issue an OIDC identity token (HTTP ${githubResponse.status}).`,\n githubResponse.status,\n );\n }\n if (!githubValue.success) {\n throw new GitHubActionsOidcError(\n 'OIDC_GITHUB_TOKEN_RESPONSE_INVALID',\n 'GitHub Actions returned an invalid OIDC identity-token response.',\n githubResponse.status,\n );\n }\n\n const exchangeResponse = await this.fetchWithRetry(\n new URL('/v1/oidc/github-actions/exchange', trust.apiBaseUrl),\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n provider: 'github_actions',\n audience: UAPKG_GITHUB_OIDC_AUDIENCE,\n idToken: githubValue.data.value,\n target: {\n registryId: target.registryId,\n packageName,\n },\n }),\n },\n 'exchange',\n );\n const exchangeValue = await this.readJson(exchangeResponse, 'exchange');\n if (!exchangeResponse.ok) {\n const error = exchangeErrorSchema.safeParse(exchangeValue);\n if (error.success) {\n throw new ControlPlaneError(\n error.data.error.code,\n error.data.error.message,\n exchangeResponse.status,\n error.data.error.details,\n );\n }\n throw new GitHubActionsOidcError(\n 'OIDC_EXCHANGE_REJECTED',\n `UAPKG rejected the GitHub Actions identity (HTTP ${exchangeResponse.status}).`,\n exchangeResponse.status,\n );\n }\n const parsed = exchangeResponseSchema.safeParse(exchangeValue);\n if (!parsed.success) {\n throw new GitHubActionsOidcError(\n 'OIDC_EXCHANGE_RESPONSE_INVALID',\n 'The UAPKG OIDC exchange response was invalid.',\n exchangeResponse.status,\n );\n }\n return parsed.data.token;\n }\n\n private async fetchWithRetry(url: URL, init: RequestInit, endpoint: OidcEndpoint): Promise<Response> {\n for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {\n let response: Response;\n try {\n response = await this.fetch(url, {\n ...init,\n redirect: 'error',\n signal: AbortSignal.timeout(this.requestTimeoutMs),\n });\n } catch (error) {\n if (attempt < this.maxAttempts) {\n await this.sleep(this.retryDelay(undefined, attempt));\n continue;\n }\n throw requestFailure(endpoint, error);\n }\n\n if (!RETRYABLE_STATUS_CODES.has(response.status) || attempt === this.maxAttempts) return response;\n\n const retryAfter = response.headers.get('retry-after');\n await response.body?.cancel().catch(() => undefined);\n await this.sleep(this.retryDelay(retryAfter, attempt));\n }\n\n throw new Error('OIDC retry loop exhausted unexpectedly.');\n }\n\n private retryDelay(retryAfter: string | null | undefined, attempt: number): number {\n const parsed = parseRetryAfter(retryAfter);\n const fallback = DEFAULT_RETRY_DELAY_MS * 2 ** (attempt - 1);\n return Math.min(parsed ?? fallback, this.maxRetryDelayMs);\n }\n\n private async readJson(response: Response, endpoint: OidcEndpoint): Promise<unknown> {\n const contentLength = parseContentLength(response.headers.get('content-length'));\n if (contentLength !== undefined && contentLength > this.maxResponseBytes) {\n await response.body?.cancel().catch(() => undefined);\n throw responseTooLarge(endpoint, response.status);\n }\n\n const chunks: Uint8Array[] = [];\n let byteLength = 0;\n if (response.body) {\n const reader = response.body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n byteLength += value.byteLength;\n if (byteLength > this.maxResponseBytes) {\n await reader.cancel().catch(() => undefined);\n throw responseTooLarge(endpoint, response.status);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n if (byteLength === 0) return {};\n const contentType = response.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase();\n if (contentType !== 'application/json' && !contentType?.endsWith('+json')) {\n throw responseInvalid(endpoint, response.status);\n }\n\n const bytes = new Uint8Array(byteLength);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n try {\n return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as unknown;\n } catch (error) {\n throw responseInvalid(endpoint, response.status, error);\n }\n }\n}\n\nfunction parseGitHubOidcEndpoint(value: string): URL {\n let url: URL;\n try {\n url = new URL(value);\n } catch (error) {\n throw new GitHubActionsOidcError(\n 'OIDC_GITHUB_ENDPOINT_INVALID',\n 'GitHub Actions supplied an unexpected OIDC token endpoint.',\n undefined,\n { cause: error },\n );\n }\n const hostname = url.hostname.toLowerCase();\n if (\n url.protocol !== 'https:' ||\n url.username ||\n url.password ||\n url.port ||\n (hostname !== 'actions.githubusercontent.com' && !hostname.endsWith('.actions.githubusercontent.com'))\n ) {\n throw new GitHubActionsOidcError(\n 'OIDC_GITHUB_ENDPOINT_INVALID',\n 'GitHub Actions supplied an unexpected OIDC token endpoint.',\n );\n }\n return url;\n}\n\nfunction requestFailure(endpoint: OidcEndpoint, error: unknown): GitHubActionsOidcError {\n const timedOut = error instanceof DOMException && error.name === 'TimeoutError';\n if (endpoint === 'github') {\n return new GitHubActionsOidcError(\n timedOut ? 'OIDC_GITHUB_TOKEN_REQUEST_TIMEOUT' : 'OIDC_GITHUB_TOKEN_REQUEST_FAILED',\n timedOut\n ? 'Timed out while requesting a GitHub Actions OIDC identity token.'\n : 'Unable to request a GitHub Actions OIDC identity token.',\n undefined,\n { cause: error },\n );\n }\n return new GitHubActionsOidcError(\n timedOut ? 'OIDC_EXCHANGE_REQUEST_TIMEOUT' : 'OIDC_EXCHANGE_REQUEST_FAILED',\n timedOut\n ? 'Timed out while exchanging the GitHub Actions identity with UAPKG.'\n : 'Unable to exchange the GitHub Actions identity with UAPKG.',\n undefined,\n { cause: error },\n );\n}\n\nfunction responseTooLarge(endpoint: OidcEndpoint, status: number): GitHubActionsOidcError {\n return endpoint === 'github'\n ? new GitHubActionsOidcError(\n 'OIDC_GITHUB_TOKEN_RESPONSE_TOO_LARGE',\n 'GitHub Actions returned an oversized OIDC identity-token response.',\n status,\n )\n : new GitHubActionsOidcError(\n 'OIDC_EXCHANGE_RESPONSE_TOO_LARGE',\n 'The UAPKG OIDC exchange returned an oversized response.',\n status,\n );\n}\n\nfunction responseInvalid(endpoint: OidcEndpoint, status: number, cause?: unknown): GitHubActionsOidcError {\n return endpoint === 'github'\n ? new GitHubActionsOidcError(\n 'OIDC_GITHUB_TOKEN_RESPONSE_INVALID',\n 'GitHub Actions returned an invalid OIDC identity-token response.',\n status,\n { cause },\n )\n : new GitHubActionsOidcError(\n 'OIDC_EXCHANGE_RESPONSE_INVALID',\n 'The UAPKG OIDC exchange response was invalid.',\n status,\n { cause },\n );\n}\n\nfunction parseContentLength(value: string | null): number | undefined {\n if (value === null || !/^\\d+$/.test(value)) return undefined;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) ? parsed : undefined;\n}\n\nfunction parseRetryAfter(value: string | null | undefined, now = Date.now()): number | undefined {\n if (!value) return undefined;\n if (/^\\d+$/.test(value)) return Number(value) * 1_000;\n const timestamp = Date.parse(value);\n return Number.isFinite(timestamp) ? Math.max(0, timestamp - now) : undefined;\n}\n\nfunction positiveInteger(value: number | undefined, fallback: number): number {\n return value !== undefined && Number.isSafeInteger(value) && value > 0 ? value : fallback;\n}\n\nfunction delay(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n"],"mappings":";;;;AAQA,MAAM,6BAA6B;AACnC,MAAM,6BAA6B;AACnC,MAAM,uBAAuB;AAC7B,MAAM,yBAAyB;AAC/B,MAAM,6BAA6B;AACnC,MAAM,yCAAyB,IAAI,IAAI,CAAC,KAAK,GAAG,CAAC;AAEjD,MAAM,uBAAuB,EAAE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I,GAAG,YAAY,GAAG,IAAI;AACrE;AAEA,SAAS,gBAAgB,OAA2B,UAA0B;CAC5E,OAAO,UAAU,UAAa,OAAO,cAAc,KAAK,KAAK,QAAQ,IAAI,QAAQ;AACnF;AAEA,SAAS,MAAM,cAAqC;CAClD,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,YAAY,CAAC;AACnE"}
|
|
1
|
+
{"version":3,"file":"GitHubActionsOidcCredentialProvider.js","names":[],"sources":["../../src/control-plane/GitHubActionsOidcCredentialProvider.ts"],"sourcesContent":["import { z } from 'zod';\nimport {\n ControlPlaneError,\n type RegistryTrust,\n UAPKG_CONTROL_PLANE_API,\n UAPKG_GITHUB_OIDC_AUDIENCE,\n} from '#cli/control-plane/ControlPlaneTypes.ts';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_RESPONSE_BYTES = 64 * 1024;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_RETRY_DELAY_MS = 1_000;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 30_000;\nconst RETRYABLE_STATUS_CODES = new Set([429, 503]);\n\nconst githubResponseSchema = z.strictObject({ value: z.string().min(1) });\nconst exchangeResponseSchema = z.strictObject({\n ok: z.literal(true),\n token: z.string().min(1),\n expiresAt: z.number().int().positive(),\n});\nconst exchangeErrorSchema = z.strictObject({\n ok: z.literal(false),\n error: z.strictObject({\n code: z.string().min(1),\n message: z.string().min(1),\n details: z.record(z.string(), z.unknown()).optional(),\n }),\n});\n\nexport type GitHubActionsOidcErrorCode =\n | 'OIDC_CONTROL_PLANE_UNTRUSTED'\n | 'OIDC_EXCHANGE_TARGET_INVALID'\n | 'OIDC_GITHUB_CONTEXT_UNAVAILABLE'\n | 'OIDC_GITHUB_ENDPOINT_INVALID'\n | 'OIDC_GITHUB_TOKEN_REQUEST_FAILED'\n | 'OIDC_GITHUB_TOKEN_REQUEST_TIMEOUT'\n | 'OIDC_GITHUB_TOKEN_REJECTED'\n | 'OIDC_GITHUB_TOKEN_RESPONSE_INVALID'\n | 'OIDC_GITHUB_TOKEN_RESPONSE_TOO_LARGE'\n | 'OIDC_EXCHANGE_REQUEST_FAILED'\n | 'OIDC_EXCHANGE_REQUEST_TIMEOUT'\n | 'OIDC_EXCHANGE_REJECTED'\n | 'OIDC_EXCHANGE_RESPONSE_INVALID'\n | 'OIDC_EXCHANGE_RESPONSE_TOO_LARGE';\n\n/** Stable local failures from the GitHub Actions OIDC credential flow. */\nexport class GitHubActionsOidcError extends Error {\n public constructor(\n public readonly code: GitHubActionsOidcErrorCode,\n message: string,\n public readonly status?: number,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'GitHubActionsOidcError';\n }\n}\n\nexport interface GitHubActionsOidcCredentialProviderOptions {\n readonly fetch?: typeof fetch;\n readonly sleep?: (milliseconds: number) => Promise<void>;\n readonly requestTimeoutMs?: number;\n readonly maxResponseBytes?: number;\n readonly maxAttempts?: number;\n readonly maxRetryDelayMs?: number;\n}\n\n/** Package selector bound into every UAPKG OIDC exchange. */\nexport interface GitHubActionsOidcTarget {\n readonly registryId: string;\n readonly packageName: string;\n}\n\ntype OidcEndpoint = 'github' | 'exchange';\n\nexport class GitHubActionsOidcCredentialProvider {\n private readonly fetch: typeof fetch;\n private readonly sleep: (milliseconds: number) => Promise<void>;\n private readonly requestTimeoutMs: number;\n private readonly maxResponseBytes: number;\n private readonly maxAttempts: number;\n private readonly maxRetryDelayMs: number;\n\n public constructor(options: GitHubActionsOidcCredentialProviderOptions = {}) {\n this.fetch = options.fetch ?? globalThis.fetch;\n this.sleep = options.sleep ?? delay;\n this.requestTimeoutMs = positiveInteger(options.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS);\n this.maxResponseBytes = positiveInteger(options.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES);\n this.maxAttempts = positiveInteger(options.maxAttempts, DEFAULT_MAX_ATTEMPTS);\n this.maxRetryDelayMs = positiveInteger(options.maxRetryDelayMs, DEFAULT_MAX_RETRY_DELAY_MS);\n }\n\n public isAvailable(): boolean {\n return Boolean(\n process.env.GITHUB_ACTIONS === 'true' ||\n process.env.ACTIONS_ID_TOKEN_REQUEST_URL ||\n process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN,\n );\n }\n\n public async exchange(trust: RegistryTrust, target: GitHubActionsOidcTarget): Promise<string> {\n if (trust.apiBaseUrl !== UAPKG_CONTROL_PLANE_API) {\n throw new GitHubActionsOidcError(\n 'OIDC_CONTROL_PLANE_UNTRUSTED',\n `UAPKG v1 OIDC exchange is pinned to ${UAPKG_CONTROL_PLANE_API}.`,\n );\n }\n const packageName = target.packageName.trim();\n if (target.registryId !== trust.registryId || !packageName) {\n throw new GitHubActionsOidcError(\n 'OIDC_EXCHANGE_TARGET_INVALID',\n 'GitHub Actions OIDC requires the exact trusted registry and packaged package name.',\n );\n }\n const requestUrl = process.env.ACTIONS_ID_TOKEN_REQUEST_URL;\n const requestToken = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;\n if (!this.isAvailable() || !requestUrl || !requestToken) {\n throw new GitHubActionsOidcError(\n 'OIDC_GITHUB_CONTEXT_UNAVAILABLE',\n 'GitHub Actions OIDC was selected but its identity-token endpoint is unavailable. The workflow must grant `id-token: write`.',\n );\n }\n\n const url = parseGitHubOidcEndpoint(requestUrl);\n url.searchParams.set('audience', UAPKG_GITHUB_OIDC_AUDIENCE);\n\n const githubResponse = await this.fetchWithRetry(\n url,\n {\n headers: { authorization: `Bearer ${requestToken}` },\n },\n 'github',\n );\n const githubValue = githubResponseSchema.safeParse(await this.readJson(githubResponse, 'github'));\n if (!githubResponse.ok) {\n throw new GitHubActionsOidcError(\n 'OIDC_GITHUB_TOKEN_REJECTED',\n `GitHub Actions did not issue an OIDC identity token (HTTP ${githubResponse.status}).`,\n githubResponse.status,\n );\n }\n if (!githubValue.success) {\n throw new GitHubActionsOidcError(\n 'OIDC_GITHUB_TOKEN_RESPONSE_INVALID',\n 'GitHub Actions returned an invalid OIDC identity-token response.',\n githubResponse.status,\n );\n }\n\n const exchangeResponse = await this.fetchWithRetry(\n new URL('/v1/oidc/github-actions/exchange', trust.apiBaseUrl),\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n provider: 'github_actions',\n audience: UAPKG_GITHUB_OIDC_AUDIENCE,\n idToken: githubValue.data.value,\n target: {\n registryId: target.registryId,\n packageName,\n },\n }),\n },\n 'exchange',\n );\n const exchangeValue = await this.readJson(exchangeResponse, 'exchange');\n if (!exchangeResponse.ok) {\n const error = exchangeErrorSchema.safeParse(exchangeValue);\n if (error.success) {\n throw new ControlPlaneError(\n error.data.error.code,\n error.data.error.message,\n exchangeResponse.status,\n error.data.error.details,\n );\n }\n throw new GitHubActionsOidcError(\n 'OIDC_EXCHANGE_REJECTED',\n `UAPKG rejected the GitHub Actions identity (HTTP ${exchangeResponse.status}).`,\n exchangeResponse.status,\n );\n }\n const parsed = exchangeResponseSchema.safeParse(exchangeValue);\n if (!parsed.success) {\n throw new GitHubActionsOidcError(\n 'OIDC_EXCHANGE_RESPONSE_INVALID',\n 'The UAPKG OIDC exchange response was invalid.',\n exchangeResponse.status,\n );\n }\n return parsed.data.token;\n }\n\n private async fetchWithRetry(url: URL, init: RequestInit, endpoint: OidcEndpoint): Promise<Response> {\n for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {\n let response: Response;\n try {\n response = await this.fetch(url, {\n ...init,\n redirect: 'error',\n signal: AbortSignal.timeout(this.requestTimeoutMs),\n });\n } catch (error) {\n if (attempt < this.maxAttempts) {\n await this.sleep(this.retryDelay(undefined, attempt));\n continue;\n }\n throw requestFailure(endpoint, error);\n }\n\n if (!RETRYABLE_STATUS_CODES.has(response.status) || attempt === this.maxAttempts) return response;\n\n const retryAfter = response.headers.get('retry-after');\n await response.body?.cancel().catch(() => undefined);\n await this.sleep(this.retryDelay(retryAfter, attempt));\n }\n\n throw new Error('OIDC retry loop exhausted unexpectedly.');\n }\n\n private retryDelay(retryAfter: string | null | undefined, attempt: number): number {\n const parsed = parseRetryAfter(retryAfter);\n const fallback = DEFAULT_RETRY_DELAY_MS * 2 ** (attempt - 1);\n return Math.min(parsed ?? fallback, this.maxRetryDelayMs);\n }\n\n private async readJson(response: Response, endpoint: OidcEndpoint): Promise<unknown> {\n const contentLength = parseContentLength(response.headers.get('content-length'));\n if (contentLength !== undefined && contentLength > this.maxResponseBytes) {\n await response.body?.cancel().catch(() => undefined);\n throw responseTooLarge(endpoint, response.status);\n }\n\n const chunks: Uint8Array[] = [];\n let byteLength = 0;\n if (response.body) {\n const reader = response.body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n byteLength += value.byteLength;\n if (byteLength > this.maxResponseBytes) {\n await reader.cancel().catch(() => undefined);\n throw responseTooLarge(endpoint, response.status);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n if (byteLength === 0) return {};\n const contentType = response.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase();\n if (contentType !== 'application/json' && !contentType?.endsWith('+json')) {\n throw responseInvalid(endpoint, response.status);\n }\n\n const bytes = new Uint8Array(byteLength);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n try {\n return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as unknown;\n } catch (error) {\n throw responseInvalid(endpoint, response.status, error);\n }\n }\n}\n\nfunction parseGitHubOidcEndpoint(value: string): URL {\n let url: URL;\n try {\n url = new URL(value);\n } catch (error) {\n throw new GitHubActionsOidcError(\n 'OIDC_GITHUB_ENDPOINT_INVALID',\n 'GitHub Actions supplied an unexpected OIDC token endpoint.',\n undefined,\n { cause: error },\n );\n }\n const hostname = url.hostname.toLowerCase();\n if (\n url.protocol !== 'https:' ||\n url.username ||\n url.password ||\n url.port ||\n (hostname !== 'actions.githubusercontent.com' && !hostname.endsWith('.actions.githubusercontent.com'))\n ) {\n throw new GitHubActionsOidcError(\n 'OIDC_GITHUB_ENDPOINT_INVALID',\n 'GitHub Actions supplied an unexpected OIDC token endpoint.',\n );\n }\n return url;\n}\n\nfunction requestFailure(endpoint: OidcEndpoint, error: unknown): GitHubActionsOidcError {\n const timedOut = error instanceof DOMException && error.name === 'TimeoutError';\n if (endpoint === 'github') {\n return new GitHubActionsOidcError(\n timedOut ? 'OIDC_GITHUB_TOKEN_REQUEST_TIMEOUT' : 'OIDC_GITHUB_TOKEN_REQUEST_FAILED',\n timedOut\n ? 'Timed out while requesting a GitHub Actions OIDC identity token.'\n : 'Unable to request a GitHub Actions OIDC identity token.',\n undefined,\n { cause: error },\n );\n }\n return new GitHubActionsOidcError(\n timedOut ? 'OIDC_EXCHANGE_REQUEST_TIMEOUT' : 'OIDC_EXCHANGE_REQUEST_FAILED',\n timedOut\n ? 'Timed out while exchanging the GitHub Actions identity with UAPKG.'\n : 'Unable to exchange the GitHub Actions identity with UAPKG.',\n undefined,\n { cause: error },\n );\n}\n\nfunction responseTooLarge(endpoint: OidcEndpoint, status: number): GitHubActionsOidcError {\n return endpoint === 'github'\n ? new GitHubActionsOidcError(\n 'OIDC_GITHUB_TOKEN_RESPONSE_TOO_LARGE',\n 'GitHub Actions returned an oversized OIDC identity-token response.',\n status,\n )\n : new GitHubActionsOidcError(\n 'OIDC_EXCHANGE_RESPONSE_TOO_LARGE',\n 'The UAPKG OIDC exchange returned an oversized response.',\n status,\n );\n}\n\nfunction responseInvalid(endpoint: OidcEndpoint, status: number, cause?: unknown): GitHubActionsOidcError {\n return endpoint === 'github'\n ? new GitHubActionsOidcError(\n 'OIDC_GITHUB_TOKEN_RESPONSE_INVALID',\n 'GitHub Actions returned an invalid OIDC identity-token response.',\n status,\n { cause },\n )\n : new GitHubActionsOidcError(\n 'OIDC_EXCHANGE_RESPONSE_INVALID',\n 'The UAPKG OIDC exchange response was invalid.',\n status,\n { cause },\n );\n}\n\nfunction parseContentLength(value: string | null): number | undefined {\n if (value === null || !/^\\d+$/.test(value)) return undefined;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) ? parsed : undefined;\n}\n\nfunction parseRetryAfter(value: string | null | undefined, now = Date.now()): number | undefined {\n if (!value) return undefined;\n if (/^\\d+$/.test(value)) return Number(value) * 1_000;\n const timestamp = Date.parse(value);\n return Number.isFinite(timestamp) ? Math.max(0, timestamp - now) : undefined;\n}\n\nfunction positiveInteger(value: number | undefined, fallback: number): number {\n return value !== undefined && Number.isSafeInteger(value) && value > 0 ? value : fallback;\n}\n\nfunction delay(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n"],"mappings":";;;;AAQA,MAAM,6BAA6B;AACnC,MAAM,6BAA6B;AACnC,MAAM,uBAAuB;AAC7B,MAAM,yBAAyB;AAC/B,MAAM,6BAA6B;AACnC,MAAM,yCAAyB,IAAI,IAAI,CAAC,KAAK,GAAG,CAAC;AAEjD,MAAM,uBAAuB,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;AACxE,MAAM,yBAAyB,EAAE,aAAa;CAC5C,IAAI,EAAE,QAAQ,IAAI;CAClB,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACvB,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;AACvC,CAAC;AACD,MAAM,sBAAsB,EAAE,aAAa;CACzC,IAAI,EAAE,QAAQ,KAAK;CACnB,OAAO,EAAE,aAAa;EACpB,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EACtB,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EACzB,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;CACtD,CAAC;AACH,CAAC;;AAmBD,IAAa,yBAAb,cAA4C,MAAM;CAE9B;CAEA;CAHlB,AAAO,YACL,AAAgB,MAChB,SACA,AAAgB,QAChB,SACA;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uBACF,oCACA,2DACA,MACF;AACN;AAEA,SAAS,gBAAgB,UAAwB,QAAgB,OAAyC;CACxG,OAAO,aAAa,WAChB,IAAI,uBACF,sCACA,oEACA,QACA,EAAE,MAAM,CACV,IACA,IAAI,uBACF,kCACA,iDACA,QACA,EAAE,MAAM,CACV;AACN;AAEA,SAAS,mBAAmB,OAA0C;CACpE,IAAI,UAAU,QAAQ,CAAC,QAAQ,KAAK,KAAK,GAAG,OAAO;CACnD,MAAM,SAAS,OAAO,KAAK;CAC3B,OAAO,OAAO,cAAc,MAAM,IAAI,SAAS;AACjD;AAEA,SAAS,gBAAgB,OAAkC,MAAM,KAAK,IAAI,GAAuB;CAC/F,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI,QAAQ,KAAK,KAAK,GAAG,OAAO,OAAO,KAAK,IAAI;CAChD,MAAM,YAAY,KAAK,MAAM,KAAK;CAClC,OAAO,OAAO,SAAS,SAAS,IAAI,KAAK,IAAI,GAAG,YAAY,GAAG,IAAI;AACrE;AAEA,SAAS,gBAAgB,OAA2B,UAA0B;CAC5E,OAAO,UAAU,UAAa,OAAO,cAAc,KAAK,KAAK,QAAQ,IAAI,QAAQ;AACnF;AAEA,SAAS,MAAM,cAAqC;CAClD,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,YAAY,CAAC;AACnE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PublishRequestErrorMapper.js","names":[],"sources":["../../src/control-plane/PublishRequestErrorMapper.ts"],"sourcesContent":["import {\n createPublishRequestFailedDiagnostic,\n type PublishDiagnosticFact,\n type PublishDiagnosticResource,\n type PublishRequestFailedDiagnostic,\n} from '@uapkg/diagnostics';\nimport { z } from 'zod';\nimport { ControlPlaneError } from './ControlPlaneTypes.js';\n\nconst SERVER_CODE_PATTERN = /^[A-Z][A-Z0-9_]{0,127}$/u;\n\nconst boundedText = (maximumLength: number) =>\n z\n .string()\n .trim()\n .min(1)\n .max(maximumLength)\n .refine((value) => !hasUnsafeDisplayCharacter(value));\nconst packageNameSchema = boundedText(214);\nconst packageVersionSchema = boundedText(256);\nconst ownerNameSchema = boundedText(100).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/u);\nconst repositorySchema = boundedText(255).regex(/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u);\nconst requestIdSchema = boundedText(128).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u);\nconst accessModeSchema = z.enum(['none', 'selected', 'all']);\nconst missingCapabilitiesSchema = z\n .array(z.enum(['package.publish', 'publishing.request.create']))\n .max(10)\n .transform((values) => [...new Set(values)]);\nconst missingOAuthScopesSchema = z\n .array(z.enum(['publishing.request.create', 'publishing.request.read.self']))\n .max(2)\n .transform((values) => [...new Set(values)]);\nconst ownerNamesSchema = z\n .array(ownerNameSchema)\n .max(20)\n .transform((values) => [...new Set(values)].sort());\n\nconst emptyDetailsSchema = z.object({});\nconst packageDetailsSchema = z.object({ packageName: packageNameSchema.optional() });\nconst ownerRequiredDetailsSchema = packageDetailsSchema;\nconst requestedOwnerDetailsSchema = packageDetailsSchema.extend({\n requestedOwnerOrganizationName: ownerNameSchema.optional(),\n ownerOrganizationName: ownerNameSchema.optional(),\n allowedOwnerOrganizationNames: ownerNamesSchema.optional(),\n});\nconst gatOwnerMismatchDetailsSchema = packageDetailsSchema.extend({\n requestedOwnerOrganizationName: ownerNameSchema.optional(),\n tokenOwnerOrganizationNames: ownerNamesSchema.optional(),\n});\nconst scopeMismatchDetailsSchema = packageDetailsSchema.extend({\n requestedScopeOwner: ownerNameSchema.optional(),\n scopeOwner: ownerNameSchema.optional(),\n allowedScopeOwners: ownerNamesSchema.optional(),\n tokenOwnerOrganizationNames: ownerNamesSchema.optional(),\n});\nconst tokenAccessDetailsSchema = packageDetailsSchema.extend({\n actualPackageAccessMode: accessModeSchema.optional(),\n requiredPackageAccessMode: z.literal('all').optional(),\n missingCapabilities: missingCapabilitiesSchema.optional(),\n packageAccess: z.object({ mode: accessModeSchema }).optional(),\n actualRegistryAccessMode: accessModeSchema.optional(),\n requiredRegistryAccessModes: z\n .array(z.enum(['selected', 'all']))\n .max(2)\n .optional(),\n requiredPackageAccessModes: z\n .array(z.enum(['selected', 'all']))\n .max(2)\n .optional(),\n registryAccess: z.object({ mode: accessModeSchema }).optional(),\n});\nconst tokenPermissionDetailsSchema = z.object({\n missingCapabilities: missingCapabilitiesSchema.optional(),\n});\nconst oauthScopeDetailsSchema = z.object({\n missingScopes: missingOAuthScopesSchema.optional(),\n});\nconst oidcRepositoryDetailsSchema = packageDetailsSchema.extend({\n submittedRepository: repositorySchema.optional(),\n trustedRepository: repositorySchema.optional(),\n});\nconst versionDetailsSchema = z.object({\n packageName: packageNameSchema.optional(),\n packageVersion: packageVersionSchema.optional(),\n});\nconst activeRequestDetailsSchema = versionDetailsSchema.extend({\n activeRequestId: requestIdSchema.optional(),\n});\nconst haltedPackageDetailsSchema = packageDetailsSchema.extend({\n blockingRequestId: requestIdSchema.optional(),\n});\nconst retryDetailsSchema = z.object({\n retryAfterSeconds: z.number().int().min(1).max(86_400).optional(),\n});\n\nexport interface PublishRequestErrorContext {\n readonly packageName: string;\n readonly packageVersion: string;\n readonly registryAlias: string;\n readonly registryName?: string;\n readonly registryIssuer: string;\n readonly credentialKind: 'login' | 'gat' | 'oidc';\n readonly requestedOwner?: string;\n readonly repository: string;\n}\n\ntype ResourceKind =\n | 'access-tokens'\n | 'help'\n | 'login'\n | 'owner-command'\n | 'requests'\n | 'security'\n | 'registries'\n | 'trusted-publishers';\n\ninterface PublishGuidance {\n readonly message: string;\n readonly hint: string;\n readonly facts?: readonly PublishDiagnosticFact[];\n readonly resources?: readonly ResourceKind[];\n readonly requestId?: string;\n}\n\ninterface PublishErrorSpec {\n build(details: unknown, context: PublishRequestErrorContext): PublishGuidance;\n}\n\nfunction defineSpec<Schema extends z.ZodObject>(\n schema: Schema,\n build: (details: z.output<Schema>, context: PublishRequestErrorContext) => PublishGuidance,\n): PublishErrorSpec {\n const empty = schema.parse({});\n return {\n build(details, context) {\n const parsed = schema.safeParse(details ?? {});\n return build(parsed.success ? parsed.data : empty, context);\n },\n };\n}\n\nfunction fixedSpec(message: string, hint: string, resources: readonly ResourceKind[] = []): PublishErrorSpec {\n return defineSpec(emptyDetailsSchema, () => ({ message, hint, resources }));\n}\n\nconst UPDATE_CLIENT_AND_RETRY =\n 'Update UAPKG CLI and try again. If the problem remains, report the server code to the registry operator.';\nconst RETRY_AND_REPORT =\n 'Try publishing again. If the failure continues, report the server code to the registry operator.';\nconst LOGIN_AGAIN = 'Sign in again for this registry, then retry the publication.';\nconst CHECK_TOKEN =\n 'Create or use an active granular access token with the correct owner, permissions, and package access, then try again.';\n\nconst clientRequestSpec = (message: string) => fixedSpec(message, UPDATE_CLIENT_AND_RETRY);\nconst internalServiceSpec = (message: string) => fixedSpec(message, RETRY_AND_REPORT);\nconst loginSpec = (message: string) => fixedSpec(message, LOGIN_AGAIN, ['login']);\nconst tokenSpec = (message: string) => fixedSpec(message, CHECK_TOKEN, ['access-tokens']);\n\nconst unscopedOwnerSpec = defineSpec(ownerRequiredDetailsSchema, (_details, context) => {\n const packageName = safeDisplayValue(context.packageName, 214);\n return {\n message: packageName\n ? `\"${packageName}\" needs an owner organization before it can be published for the first time.`\n : 'This unscoped package needs an owner organization before it can be published for the first time.',\n hint: 'Pass `--owner <organization>`, set `publish.owner` in uapkg.json, or publish the package under an `@organization/name` scope.',\n resources: ['owner-command'],\n };\n});\n\nconst gatOwnerMismatchSpec = defineSpec(gatOwnerMismatchDetailsSchema, (details, context) => {\n const requestedOwner = details.requestedOwnerOrganizationName ?? safeOwner(context.requestedOwner);\n const tokenOwners = details.tokenOwnerOrganizationNames ?? [];\n const ownerDescription = tokenOwners.length > 0 ? quotedList(tokenOwners) : 'a different organization';\n const requestedDescription = requestedOwner ? `\"${requestedOwner}\"` : 'the requested organization';\n const scoped = scopedOwner(context.packageName);\n return {\n message: `The selected token was created for ${ownerDescription}, but this publication asks to use ${requestedDescription}.`,\n hint: scoped\n ? `Use a token created for \"${scoped}\", or rebuild the package under the organization scope this token acts for.`\n : 'Correct or remove the explicit owner, or use a token created for the organization that should own this package.',\n facts: compactFacts([\n fact('requested-owner', requestedOwner),\n ...tokenOwners.map((owner) => fact('token-owner', owner)),\n ]),\n resources: ['access-tokens'],\n };\n});\n\nconst scopeMismatchSpec = defineSpec(scopeMismatchDetailsSchema, (details, context) => {\n const requestedOwner = details.requestedScopeOwner ?? details.scopeOwner ?? scopedOwner(context.packageName);\n const allowedOwners = details.allowedScopeOwners ?? details.tokenOwnerOrganizationNames ?? [];\n const requestedDescription = requestedOwner ? `\"@${requestedOwner}\"` : 'The package scope';\n const allowedDescription =\n allowedOwners.length > 0\n ? quotedList(allowedOwners.map((owner) => `@${owner}`))\n : 'the organization this token acts for';\n return {\n message: `${requestedDescription} does not match ${allowedDescription}.`,\n hint: 'Use a token created for the package scope, or rebuild the package under the organization scope this token acts for.',\n facts: compactFacts([\n fact('requested-owner', requestedOwner),\n ...allowedOwners.map((owner) => fact('allowed-owner', owner)),\n ]),\n resources: ['access-tokens'],\n };\n});\n\nconst initialTokenAccessSpec = defineSpec(tokenAccessDetailsSchema, (details) => {\n const actualMode = details.actualPackageAccessMode ?? details.packageAccess?.mode;\n const requiredMode = details.requiredPackageAccessMode ?? 'all';\n const missing = details.missingCapabilities ?? (actualMode === undefined ? ['package.publish'] : []);\n return {\n message: 'This token cannot create a package during its first publication.',\n hint: 'Create or use a token with Package Access set to All and permission to publish packages.',\n facts: compactFacts([\n fact('actual-access-mode', accessModeLabel(actualMode, 'package')),\n fact('required-access-mode', accessModeLabel(requiredMode, 'package')),\n ...missing.map((capability) => fact('missing-capability', capabilityLabel(capability))),\n ]),\n resources: ['access-tokens'],\n };\n});\n\nconst tokenPermissionSpec = defineSpec(tokenPermissionDetailsSchema, (details) => ({\n message: 'This token does not allow package publication.',\n hint: 'Create or use a token with permission to publish packages, then try again.',\n facts: (details.missingCapabilities ?? ['package.publish']).map((capability) => ({\n kind: 'missing-capability' as const,\n value: capabilityLabel(capability),\n })),\n resources: ['access-tokens'],\n}));\n\nconst oauthScopeSpec = defineSpec(oauthScopeDetailsSchema, (details) => ({\n message: 'This CLI login does not include permission to submit publishing requests.',\n hint: 'Reauthorize the login for this registry, then try publishing again.',\n facts: (details.missingScopes ?? ['publishing.request.create']).map((scope) => ({\n kind: 'missing-capability' as const,\n value: oauthScopeLabel(scope),\n })),\n resources: ['login'],\n}));\n\nconst packageOwnerNotAuthorizedSpec = defineSpec(requestedOwnerDetailsSchema, (details, context) => {\n const owner =\n details.requestedOwnerOrganizationName ?? details.ownerOrganizationName ?? safeOwner(context.requestedOwner);\n const allowedOwners = details.allowedOwnerOrganizationNames ?? [];\n const scoped = scopedOwner(context.packageName);\n const retryOwner = allowedOwners.length === 1 && !scoped ? allowedOwners[0] : undefined;\n return {\n message: owner\n ? `Your account is not allowed to create this package for UAPKG organization \"${owner}\".`\n : 'Your account is not allowed to create this package for the requested UAPKG organization.',\n hint: scoped\n ? allowedOwners.length > 0\n ? 'This package’s `@owner` scope determines ownership. Rebuild it under one of the allowed UAPKG organization scopes shown above.'\n : 'This package’s `@owner` scope determines ownership. Rebuild it under a UAPKG organization scope where you can publish, or ask an organization administrator to grant access.'\n : retryOwner\n ? `Retry with \\`--owner ${retryOwner}\\` to use the allowed UAPKG organization namespace.`\n : allowedOwners.length > 0\n ? 'Choose one of the allowed UAPKG organization namespaces with `--owner`, or ask a UAPKG organization administrator to grant access.'\n : 'Choose a UAPKG organization namespace where you can publish, or ask a UAPKG organization administrator to grant access.',\n facts: compactFacts([\n fact('requested-owner', owner),\n ...allowedOwners.map((allowedOwner) => fact('allowed-owner', allowedOwner)),\n ]),\n };\n});\n\nconst publishingAuthorityDeniedSpec = defineSpec(emptyDetailsSchema, (_details, context) => {\n switch (context.credentialKind) {\n case 'oidc':\n return {\n message: 'This GitHub Actions workflow does not currently have publishing authority for the package.',\n hint: 'Check the package’s trusted-publisher repository, workflow, and optional GitHub Environment setting, then run the workflow again.',\n resources: ['trusted-publishers'],\n };\n case 'gat':\n return {\n message: 'This granular access token does not currently have publishing authority for the package.',\n hint: 'Create or use a token for the package owner with the required package access and publishing permission.',\n resources: ['access-tokens'],\n };\n case 'login':\n return {\n message: 'Your account does not currently have publishing authority for the package.',\n hint: 'Choose an owner organization where you can publish, or ask an organization administrator to grant access.',\n };\n }\n});\n\nconst tokenResourceAccessSpec = defineSpec(tokenAccessDetailsSchema, (details) => {\n const actualPackageMode = details.actualPackageAccessMode ?? details.packageAccess?.mode;\n const actualRegistryMode = details.actualRegistryAccessMode ?? details.registryAccess?.mode;\n const requiredPackageModes = details.requiredPackageAccessModes;\n const requiredRegistryModes = details.requiredRegistryAccessModes;\n return {\n message: 'This token does not cover the package or registry selected for publication.',\n hint: 'Create or use a token whose package and registry access cover this publication.',\n facts: compactFacts([\n fact('actual-access-mode', accessModeLabel(actualPackageMode, 'package')),\n fact('actual-access-mode', accessModeLabel(actualRegistryMode, 'registry')),\n fact('required-access-mode', accessModesLabel(requiredPackageModes, 'package')),\n fact('required-access-mode', accessModesLabel(requiredRegistryModes, 'registry')),\n ]),\n resources: ['access-tokens'],\n };\n});\n\nconst oidcRepositorySpec = defineSpec(oidcRepositoryDetailsSchema, (details, context) => {\n const submitted = details.submittedRepository ?? safeRepository(context.repository);\n const trusted = details.trustedRepository;\n if (!trusted) {\n return {\n message: 'The registry could not determine the trusted repository for this workflow session.',\n hint: 'Start a new trusted-publishing workflow and try again. If the failure continues, review the trusted-publisher rule and report the server code.',\n facts: compactFacts([fact('requested-repository', submitted)]),\n resources: ['trusted-publishers'],\n };\n }\n return {\n message: submitted\n ? `This workflow submitted \"${submitted}\", but its trusted-publisher rule is bound to \"${trusted}\".`\n : 'The registry could not compare the package source with this workflow’s trusted-publisher rule.',\n hint: submitted\n ? 'Publish from the repository named by the trusted-publisher rule, or update the rule for the intended package source.'\n : 'Start a new trusted-publishing workflow and try again. If the failure continues, report the server code.',\n facts: compactFacts([fact('requested-repository', submitted), fact('trusted-repository', trusted)]),\n resources: ['trusted-publishers'],\n };\n});\n\nconst versionConflictSpec = (kind: 'exists' | 'tombstoned') =>\n defineSpec(versionDetailsSchema, (_details, context) => {\n const coordinate = packageCoordinate(context);\n return kind === 'exists'\n ? {\n message: `${coordinate} is already published in this registry.`,\n hint: 'Choose a new version in uapkg.json, rebuild the archive, and publish that version instead.',\n resources: ['requests'],\n }\n : {\n message: `${coordinate} was previously unpublished and cannot be reused.`,\n hint: 'Choose a new version in uapkg.json, rebuild the archive, and publish that version instead.',\n resources: ['requests'],\n };\n });\n\nconst activeRequestSpec = (ownershipConflict: boolean) =>\n defineSpec(activeRequestDetailsSchema, (details, context) => {\n const coordinate = packageCoordinate(context);\n const readableRequestId = ownershipConflict ? undefined : details.activeRequestId;\n return {\n message: ownershipConflict\n ? `Another organization already has an active first-publication request for ${safePackageLabel(context.packageName)}.`\n : `An active publishing request already covers ${coordinate}.`,\n hint: ownershipConflict\n ? 'Wait for that request to finish before trying to claim this package name, or review your own request when a request ID is shown.'\n : 'Wait for the active request to finish instead of submitting the same publication again.',\n facts: compactFacts([fact('request-id', readableRequestId)]),\n resources: ['requests'],\n requestId: readableRequestId,\n };\n });\n\nconst haltedPackageSpec = defineSpec(haltedPackageDetailsSchema, (details, context) => ({\n message: `Publishing for ${safePackageLabel(context.packageName)} is paused because an earlier request could not be completed.`,\n hint: 'Review the earlier request and ask the registry operator to resolve its failure before publishing again.',\n facts: compactFacts([fact('request-id', details.blockingRequestId)]),\n resources: ['requests'],\n requestId: details.blockingRequestId,\n}));\n\nconst rateLimitSpec = defineSpec(retryDetailsSchema, (details) => ({\n message: 'Too many publishing requests were submitted in a short time.',\n hint: details.retryAfterSeconds\n ? `Wait ${formatDuration(details.retryAfterSeconds)}, then try publishing again.`\n : 'Wait a moment, then try publishing again.',\n facts: compactFacts([\n fact('retry-after', details.retryAfterSeconds ? formatDuration(details.retryAfterSeconds) : undefined),\n ]),\n}));\n\n/**\n * Explicit inventory of errors that can be returned synchronously while the\n * CLI submits POST /v1/registry-requests/publish. Unknown future codes use the\n * non-leaking fallback in {@link publishRequestDiagnosticForError}.\n */\nexport const PUBLISH_SUBMISSION_ERROR_CATALOG = {\n // Authentication and request-bound authorization.\n AUTH_REQUIRED: loginSpec('Authentication is required to publish this package.'),\n CONTROL_PLANE_AUTHENTICATION_REQUIRED: loginSpec('The saved registry login was rejected.'),\n DPOP_AUTH_UNAVAILABLE: internalServiceSpec('The registry cannot validate CLI logins right now.'),\n DPOP_AUTH_REQUIRED: loginSpec('The publishing request did not include a valid CLI login.'),\n DPOP_PROOF_INVALID: loginSpec('The saved CLI login proof was rejected.'),\n DPOP_PROOF_REPLAYED: fixedSpec(\n 'The security proof for this CLI login was already used.',\n 'Run the publish command again. If the failure continues, sign in to the selected registry again.',\n ['login'],\n ),\n DPOP_ACCESS_TOKEN_INVALID: loginSpec('The saved CLI login is invalid or no longer usable.'),\n DPOP_PROOF_STALE: fixedSpec(\n 'The security proof for this CLI login expired before the request arrived.',\n 'Run the publish command again. If the failure continues, sign in to the selected registry again.',\n ['login'],\n ),\n DPOP_NONCE_REQUIRED: fixedSpec(\n 'The registry could not complete the security challenge for this CLI login.',\n 'Run the publish command again. If the failure continues, sign in to the selected registry again.',\n ['login'],\n ),\n REGISTRY_GRANT_INVALID: loginSpec('The registry login was revoked, expired, or belongs to another registry.'),\n CLI_LOGIN_ACTIVATION_EXPIRED: loginSpec('This CLI login expired before the device finished confirming it.'),\n ACCOUNT_NOT_ACTIVE: loginSpec('The account for this registry login is not active.'),\n CLI_ACCESS_TOKEN_INVALID: loginSpec('The saved CLI login is invalid.'),\n CLI_ACCESS_TOKEN_EXPIRED: loginSpec('The saved CLI login has expired.'),\n OAUTH_SCOPE_INSUFFICIENT: oauthScopeSpec,\n OAUTH_SCOPE_UNSUPPORTED: fixedSpec(\n 'This CLI version does not understand a capability required by the registry.',\n 'Update UAPKG CLI, sign in again, and retry the publication.',\n ['login'],\n ),\n TOKEN_INVALID: tokenSpec('The selected granular access token is invalid.'),\n TOKEN_REVOKED: tokenSpec('The selected granular access token has been revoked.'),\n TOKEN_EXPIRED: tokenSpec('The selected granular access token has expired.'),\n UAPKG_TOKEN_APPROVAL_PENDING: fixedSpec(\n 'The selected token is still waiting for organization approval.',\n 'Ask an organization administrator to approve the token, or select a different active token.',\n ['access-tokens'],\n ),\n UAPKG_TOKEN_APPROVAL_DENIED: fixedSpec(\n 'The organization denied the selected token request.',\n 'Use an approved token, or request a new token from the organization.',\n ['access-tokens'],\n ),\n UAPKG_TOKEN_ORGANIZATION_POLICY_DENIED: fixedSpec(\n 'The organization’s token policy blocks this publication.',\n 'Ask an organization administrator to review the token policy, or publish with an allowed credential.',\n ['access-tokens'],\n ),\n UAPKG_TOKEN_TEMPORARILY_BLOCKED_OWNER_MFA_REQUIRED: fixedSpec(\n 'This token is temporarily blocked because its owner must enable two-factor authentication.',\n 'Enable two-factor authentication for the token owner, then try again.',\n ['access-tokens', 'security'],\n ),\n UAPKG_TOKEN_LIFECYCLE_DISABLED: tokenSpec('The selected token is not currently usable.'),\n UAPKG_TOKEN_PERMISSION_DENIED: tokenPermissionSpec,\n UAPKG_TOKEN_RESOURCE_ACCESS_DENIED: tokenResourceAccessSpec,\n SECOND_FACTOR_REQUIRED: fixedSpec(\n 'A current two-factor authentication code is required for this publication.',\n 'Run the publish command again and enter the current code when prompted.',\n ['security'],\n ),\n OTP_INVALID: fixedSpec(\n 'The two-factor authentication code was incorrect or expired.',\n 'Run the publish command again and enter a new code when prompted.',\n ['security'],\n ),\n OTP_NOT_ENROLLED: fixedSpec(\n 'This account must enroll in two-factor authentication before publishing.',\n 'Enable two-factor authentication in account settings, then try publishing again.',\n ['security'],\n ),\n OTP_RATE_LIMITED: rateLimitSpec,\n OTP_ERROR: internalServiceSpec('The registry could not verify the two-factor authentication code.'),\n OTP_UNSUPPORTED_PRINCIPAL: fixedSpec(\n 'This credential cannot use an interactive two-factor authentication code.',\n 'Select a CLI login or granular access token that supports attended publication.',\n ),\n SECURED_ACCOUNT_REQUIRED: fixedSpec(\n 'Publishing requires an active account with two-factor authentication enabled.',\n 'Activate the account and enable two-factor authentication, then try again.',\n ['security'],\n ),\n ACTOR_WRITE_FORBIDDEN: fixedSpec(\n 'This account is not allowed to submit registry changes.',\n 'Use an account with publishing access, or ask an organization administrator for access.',\n ),\n UAPKG_PRINCIPAL_NOT_ALLOWED: fixedSpec(\n 'This kind of credential cannot submit a publishing request.',\n 'Use a CLI login, granular access token, or configured GitHub Actions trusted publisher.',\n ),\n\n // Ownership, package naming, and token access.\n UNSCOPED_PACKAGE_OWNER_REQUIRED: unscopedOwnerSpec,\n GAT_OWNER_ORGANIZATION_MISMATCH: gatOwnerMismatchSpec,\n UAPKG_PACKAGE_SCOPE_OWNER_MISMATCH: scopeMismatchSpec,\n UAPKG_REGISTRY_REQUIRES_SCOPED_PACKAGE: defineSpec(packageDetailsSchema, (_details, context) => ({\n message: `This registry requires a scoped name for the first publication of ${safePackageLabel(context.packageName)}.`,\n hint: 'Rename the package to `@organization/name`, rebuild the archive, and publish it again.',\n })),\n INITIAL_PUBLICATION_PACKAGE_ACCESS_ALL_REQUIRED: initialTokenAccessSpec,\n PACKAGE_OWNER_NOT_AUTHORIZED: packageOwnerNotAuthorizedSpec,\n INITIAL_PUBLICATION_CREDENTIAL_UNSUPPORTED: fixedSpec(\n 'This credential cannot create a package during its first publication.',\n 'Publish the package once with an interactive CLI login or an attended granular access token.',\n ['login', 'access-tokens'],\n ),\n CLI_REGISTRY_GRANT_NOT_AUTHORIZED: fixedSpec(\n 'The saved CLI login cannot publish to this registry.',\n 'Reauthorize the login for the selected registry, then try again.',\n ['login'],\n ),\n REGISTRY_WRITE_DENIED_REBAC: publishingAuthorityDeniedSpec,\n GAT_CREDENTIAL_CONTEXT_REQUIRED: internalServiceSpec('The registry could not validate the selected token.'),\n PACKAGE_OWNER_NOT_RESOLVED: internalServiceSpec('The registry could not determine this package’s owner.'),\n\n // GitHub Actions trusted publishing.\n OIDC_SESSION_INVALID: fixedSpec(\n 'The GitHub Actions publishing session expired or is no longer trusted.',\n 'Run the workflow again. If it still fails, verify that the package still has an active trusted-publisher rule for this repository and workflow.',\n ['trusted-publishers'],\n ),\n OIDC_PROVIDER_UNAVAILABLE: fixedSpec(\n 'The registry cannot validate GitHub trusted publishing right now.',\n 'Run the workflow again later. If the failure continues, report the server code to the registry operator.',\n ['trusted-publishers'],\n ),\n OIDC_INITIAL_PUBLICATION_NOT_SUPPORTED: fixedSpec(\n 'GitHub Actions cannot create this package during its first publication.',\n 'Publish the package once with an interactive CLI login, then configure its trusted-publisher rule and rerun the workflow.',\n ['login', 'trusted-publishers'],\n ),\n OIDC_SOURCE_REPOSITORY_MISMATCH: oidcRepositorySpec,\n TRUSTED_PUBLISHER_NOT_AUTHORIZED: fixedSpec(\n 'This GitHub Actions workflow is not authorized to publish the package.',\n 'Check the package’s trusted-publisher repository, workflow, and optional GitHub Environment setting, then rerun the workflow.',\n ['trusted-publishers'],\n ),\n\n // Archive, source, claims, and request-contract validation.\n INVALID_PACKAGE_NAME: fixedSpec(\n 'The packaged manifest contains an invalid package name.',\n 'Set `name` in uapkg.json to a name such as `my-package` or `@organization/my-package`, rebuild the archive, and publish it again.',\n ),\n SCOPED_PACKAGES_DISABLED: fixedSpec(\n 'The selected registry does not accept organization-scoped package names.',\n 'Select a registry that supports scoped packages, or intentionally rename and rebuild the package as an unscoped package with an explicit owner.',\n ['registries', 'owner-command'],\n ),\n INVALID_VERSION: fixedSpec(\n 'The packaged manifest contains an invalid semantic version.',\n 'Set `version` in uapkg.json to a semantic version such as `1.2.3`, rebuild the archive, and publish it again.',\n ),\n INVALID_OWNER_ORGANIZATION_NAME: fixedSpec(\n 'The selected owner is not a valid organization name.',\n 'Correct `--owner <organization>` or `publish.owner` in uapkg.json, then try publishing again.',\n ['owner-command'],\n ),\n SOURCE_REQUIRED: fixedSpec(\n 'The publishing request did not identify its GitHub Release source.',\n 'Set `publish.repository` or pass `--repository owner/repository`, and make sure the release tag and asset exist before retrying.',\n ),\n GITHUB_RELEASE_SOURCE_REQUIRED: fixedSpec(\n 'The publishing request did not identify its GitHub Release source.',\n 'Set `publish.repository` or pass `--repository owner/repository`, and make sure the release tag and asset exist before retrying.',\n ),\n SOURCE_TYPE_UNSUPPORTED: fixedSpec(\n 'The registry does not support this kind of package source.',\n 'Publish from an uploaded GitHub Release asset. If this CLI produced another source type, update it and try again.',\n ),\n GITHUB_REPOSITORY_INVALID: fixedSpec(\n 'The publishing request contains an invalid GitHub repository coordinate.',\n 'Pass `--repository owner/repository` or correct `publish.repository` in uapkg.json, then try again.',\n ),\n RELEASE_TAG_INVALID: fixedSpec(\n 'The publishing request contains an invalid GitHub Release tag.',\n 'Pass a non-empty GitHub Release tag with `--tag <tag>`, or correct the package version used by the default tag.',\n ),\n RELEASE_ASSET_NAME_INVALID: fixedSpec(\n 'The publishing request contains an invalid GitHub Release asset name.',\n 'Pass the uploaded file name—not a path—with `--asset <file-name>`, then try again.',\n ),\n OBSERVED_INTEGRITY_REQUIRED: fixedSpec(\n 'The publishing request is missing the archive’s integrity information.',\n 'Re-read or rebuild the archive and try again. If the problem remains, update UAPKG CLI and report the server code.',\n ),\n OBSERVED_DIGEST_INVALID: fixedSpec(\n 'The publishing request contains an invalid archive digest.',\n 'Re-read or rebuild the archive and try again. If the problem remains, update UAPKG CLI and report the server code.',\n ),\n OBSERVED_SIZE_INVALID: fixedSpec(\n 'The publishing request contains an invalid archive size.',\n 'Re-read or rebuild the archive and try again. If the problem remains, update UAPKG CLI and report the server code.',\n ),\n CLAIMS_REQUIRED: fixedSpec(\n 'The publishing request is missing package information from the packaged manifest.',\n 'Rebuild the archive so it contains a valid uapkg.json, then publish the rebuilt file.',\n ),\n CLAIMS_IDENTITY_MISMATCH: fixedSpec(\n 'The package name or version inside the archive does not match the publication being submitted.',\n 'Rebuild the archive from the intended uapkg.json and publish the rebuilt file.',\n ),\n CLAIMS_PRIVATE_INVALID: fixedSpec(\n 'The packaged manifest has an invalid private-package setting.',\n 'Set `private` in uapkg.json to `true` or `false`, rebuild the archive, and publish it again.',\n ),\n CLAIMS_BUCKET_INVALID: fixedSpec(\n 'The packaged manifest has an invalid dependency section.',\n 'Make each dependency section in uapkg.json an object, rebuild the archive, and publish it again.',\n ),\n CLAIMS_DEPENDENCIES_TOO_MANY: fixedSpec(\n 'A dependency section in the packaged manifest is too large.',\n 'Reduce the dependency entries in uapkg.json, rebuild the archive, and publish it again.',\n ),\n CLAIMS_DEPENDENCY_NAME_INVALID: fixedSpec(\n 'The packaged manifest contains an invalid dependency name.',\n 'Correct the dependency name in uapkg.json, rebuild the archive, and publish it again.',\n ),\n CLAIMS_DEPENDENCY_RANGE_INVALID: fixedSpec(\n 'The packaged manifest contains an invalid dependency version range.',\n 'Set a non-empty bounded version range for the dependency, rebuild the archive, and publish it again.',\n ),\n CLAIMS_DEPENDENCY_REGISTRY_INVALID: fixedSpec(\n 'The packaged manifest contains an invalid dependency registry.',\n 'Correct the dependency registry alias in uapkg.json, rebuild the archive, and publish it again.',\n ),\n CLAIMS_DEPENDENCY_FIELDS_INVALID: fixedSpec(\n 'A packaged dependency contains unsupported fields.',\n 'Remove unsupported dependency fields from uapkg.json, rebuild the archive, and publish it again.',\n ),\n OFFICIAL_REGISTRY_PRIVATE_PACKAGE_FORBIDDEN: fixedSpec(\n 'This package is marked private, but the selected registry accepts only public packages.',\n 'Publish to a private registry, or intentionally remove the private setting, rebuild the archive, and try again.',\n ['registries'],\n ),\n SERVER_RESOLVED_METADATA_NOT_ALLOWED: clientRequestSpec('The publishing request contains server-owned metadata.'),\n UNRECOGNIZED_REQUEST_FIELDS: clientRequestSpec(\n 'The publishing request contains fields this registry does not recognize.',\n ),\n INVALID_REGISTRY_ID: clientRequestSpec('The CLI resolved an invalid registry identity.'),\n PAYLOAD_TOO_LARGE: fixedSpec(\n 'The packaged publication information is too large for this registry.',\n 'Reduce oversized manifest metadata or dependency entries, rebuild the archive, and try again.',\n ),\n REQUEST_BODY_TOO_LARGE: fixedSpec(\n 'The publishing request is too large for this registry.',\n 'Reduce oversized manifest metadata or dependency entries, rebuild the archive, and try again.',\n ),\n UAPKG_OPERATION_INPUT_TOO_LARGE: fixedSpec(\n 'The publishing request is too large for this registry.',\n 'Reduce oversized manifest metadata or dependency entries, rebuild the archive, and try again.',\n ),\n INVALID_CONTENT_LENGTH: clientRequestSpec('The registry received an incomplete publishing request.'),\n INVALID_JSON: clientRequestSpec('The registry could not read the publishing request.'),\n INVALID_REQUEST_BODY: clientRequestSpec('The registry could not understand the publishing request.'),\n UAPKG_OPERATION_INPUT_INVALID: clientRequestSpec('The registry could not understand the publishing request.'),\n IDEMPOTENCY_KEY_REQUIRED: clientRequestSpec('The publishing request was missing its retry-safety key.'),\n REQUEST_KIND_NOT_PUBLIC: internalServiceSpec('The CLI reached the wrong registry operation.'),\n SOURCE_NOT_ALLOWED: internalServiceSpec('The CLI reached the wrong registry operation for an artifact publication.'),\n REASON_REQUIRED: internalServiceSpec('The CLI reached an operation that requires a reason.'),\n DEPRECATION_MESSAGE_REQUIRED: internalServiceSpec(\n 'The CLI reached an operation that requires a deprecation message.',\n ),\n\n // Registry readiness, versions, and concurrent requests.\n REGISTRY_NOT_FOUND: fixedSpec(\n 'The selected registry is no longer available to the publishing service.',\n 'Refresh or reconfigure the registry, then try publishing again.',\n ['registries'],\n ),\n REGISTRY_LINK_MISSING: fixedSpec(\n 'The selected registry is not connected to an initialized repository.',\n 'Finish the registry repository connection in account settings, then try publishing again.',\n ['registries'],\n ),\n REGISTRY_LINK_NOT_READY: fixedSpec(\n 'The selected registry repository connection is incomplete.',\n 'Finish reconnecting the registry repository in account settings, then try publishing again.',\n ['registries'],\n ),\n PACKAGE_POLICY_NOT_CONFIGURED: internalServiceSpec(\n 'The registry is not ready to assign ownership for a new package.',\n ),\n PACKAGE_NOT_FOUND: fixedSpec(\n 'The package does not exist in the selected registry.',\n 'Check the package and registry, then try again.',\n ['registries'],\n ),\n PACKAGE_HALTED: haltedPackageSpec,\n VERSION_ALREADY_EXISTS: versionConflictSpec('exists'),\n VERSION_TOMBSTONED: versionConflictSpec('tombstoned'),\n DUPLICATE_ACTIVE_REQUEST: activeRequestSpec(false),\n PACKAGE_OWNERSHIP_PENDING_CONFLICT: activeRequestSpec(true),\n IDEMPOTENCY_KEY_CONFLICT: fixedSpec(\n 'The retry-safety key for this publication is already attached to a different request.',\n 'Run the publication again. If the conflict continues, report the server code to the registry operator.',\n ['requests'],\n ),\n RATE_LIMIT_EXCEEDED: rateLimitSpec,\n\n // Defensive catalog entries for invalid route state and server failures.\n REQUEST_ATTRIBUTION_INVALID: internalServiceSpec('The registry could not safely attribute this publishing request.'),\n AUTHORIZATION_RECEIPT_REQUIRED: internalServiceSpec(\n 'The registry could not preserve authorization for this request.',\n ),\n REQUEST_CREATE_FAILED: internalServiceSpec('The registry could not save the publishing request.'),\n OPERATION_AUTHORIZATION_ACTION_MISMATCH: internalServiceSpec('The publishing endpoint is misconfigured.'),\n OPERATION_BODY_LIMIT_UNREGISTERED: internalServiceSpec('The publishing endpoint is missing its request-size policy.'),\n UAPKG_OPERATION_BINDING_MISMATCH: internalServiceSpec('The publishing endpoint is bound incorrectly.'),\n UAPKG_OPERATION_BINDER_MISMATCH: internalServiceSpec(\n 'The publishing endpoint uses the wrong authentication boundary.',\n ),\n UAPKG_OPERATION_BODY_LIMIT_UNREGISTERED: internalServiceSpec(\n 'The publishing endpoint is missing its request-size policy.',\n ),\n UAPKG_SERVICE_AUTHENTICATION_REQUIRED: internalServiceSpec(\n 'The publishing endpoint rejected an unsupported credential.',\n ),\n REGISTRY_REQUEST_RESPONSE_INVALID: internalServiceSpec('The registry returned an invalid publishing response.'),\n CONTROL_PLANE_RESPONSE_NOT_JSON: internalServiceSpec('The registry returned an unreadable publishing response.'),\n\n // These normally belong to lifecycle routes, but cataloging them keeps a\n // misrouted publish response helpful and non-leaking.\n DESTRUCTIVE_POLICY_NOT_CONFIGURED: internalServiceSpec('The registry’s version policy is not configured.'),\n PACKAGE_VERSION_TARGET_NOT_FOUND: fixedSpec(\n 'The selected package version does not exist in the registry.',\n 'Check the package version and selected registry.',\n ['requests'],\n ),\n VERSION_ALREADY_UNPUBLISHED: fixedSpec(\n 'This package version is already unpublished.',\n 'No further action is needed.',\n ),\n VERSION_ALREADY_YANKED: fixedSpec('This package version is already yanked.', 'No further action is needed.'),\n VERSION_NOT_YANKED: fixedSpec(\n 'This package version is not yanked.',\n 'Check the current request state before trying again.',\n ),\n VERSION_ALREADY_DEPRECATED: fixedSpec('This package version is already deprecated.', 'No further action is needed.'),\n VERSION_NOT_DEPRECATED: fixedSpec(\n 'This package version is not deprecated.',\n 'Check the current request state before trying again.',\n ),\n UNPUBLISH_WINDOW_EXPIRED: fixedSpec(\n 'The allowed time window for unpublishing this version has closed.',\n 'Contact the registry operator if the version presents a security or legal issue.',\n ),\n} as const satisfies Record<string, PublishErrorSpec>;\n\nexport type PublishSubmissionErrorCode = keyof typeof PUBLISH_SUBMISSION_ERROR_CATALOG;\n\nexport function publishRequestDiagnosticForError(\n error: unknown,\n context: PublishRequestErrorContext,\n): PublishRequestFailedDiagnostic {\n const serverCode = validatedServerCode(error);\n const status = validatedStatus(error);\n const spec = serverCode\n ? (PUBLISH_SUBMISSION_ERROR_CATALOG as Record<string, PublishErrorSpec>)[serverCode]\n : undefined;\n const guidance = spec\n ? spec.build(error instanceof ControlPlaneError ? error.details : undefined, context)\n : fallback(error, status);\n const facts = dedupeFacts([...baseFacts(context), ...(guidance.facts ?? [])]);\n const resources = resourcesFor(guidance.resources ?? [], context, guidance.requestId);\n\n return createPublishRequestFailedDiagnostic(\n guidance.message,\n {\n ...(serverCode ? { serverCode } : {}),\n ...(status !== undefined ? { status } : {}),\n facts,\n resources,\n },\n guidance.hint,\n );\n}\n\nfunction fallback(error: unknown, status: number | undefined): PublishGuidance {\n if (isNetworkFailure(error)) {\n return {\n message: 'UAPKG could not reach the publishing service.',\n hint: 'Check the network connection and registry availability, then try publishing again.',\n };\n }\n if (status !== undefined && status >= 500) {\n return {\n message: 'The publishing service could not complete the request.',\n hint: RETRY_AND_REPORT,\n };\n }\n return {\n message: 'The registry did not accept the publishing request.',\n hint: 'Review the publication details and try again. If the failure continues, report this diagnostic to the registry operator.',\n };\n}\n\nfunction baseFacts(context: PublishRequestErrorContext): PublishDiagnosticFact[] {\n const registryName = safeDisplayValue(context.registryName ?? '', 100);\n const registryAlias = safeDisplayValue(context.registryAlias, 100);\n const registry =\n registryName && registryAlias && registryName !== registryAlias\n ? `${registryName} (${registryAlias})`\n : (registryName ?? registryAlias);\n return compactFacts([\n fact('package', safeDisplayValue(context.packageName, 214)),\n fact('version', safeDisplayValue(context.packageVersion, 256)),\n fact('registry', registry),\n fact('credential-kind', credentialKindLabel(context.credentialKind)),\n fact('requested-owner', safeOwner(context.requestedOwner)),\n fact('repository', safeRepository(context.repository)),\n ]);\n}\n\nfunction resourcesFor(\n requested: readonly ResourceKind[],\n context: PublishRequestErrorContext,\n requestId?: string,\n): PublishDiagnosticResource[] {\n const kinds = [...new Set([...requested, 'help' as const])];\n const accountOrigin = accountOriginForIssuer(context.registryIssuer);\n const resources: PublishDiagnosticResource[] = [];\n for (const kind of kinds) {\n switch (kind) {\n case 'help':\n resources.push({ kind: 'command', command: 'uapkg publish --help', label: 'Publish command help' });\n break;\n case 'login':\n resources.push({\n kind: 'command',\n command: `uapkg login --registry ${shellDisplayArgument(context.registryAlias)} --reauthorize`,\n label: 'Reauthorize this registry login',\n });\n break;\n case 'owner-command':\n resources.push({\n kind: 'command',\n command: 'uapkg publish --owner <organization>',\n label: 'Publish with an explicit owner',\n });\n break;\n case 'requests':\n if (requestId) {\n resources.push({\n kind: 'command',\n command: `uapkg requests status ${requestId}`,\n label: 'Inspect the related request',\n });\n }\n addAccountUrl(resources, accountOrigin, '/requests', 'Publishing requests');\n break;\n case 'access-tokens':\n addAccountUrl(resources, accountOrigin, '/settings/access-tokens', 'Access token settings');\n break;\n case 'trusted-publishers':\n addAccountUrl(resources, accountOrigin, '/trusted-publishers', 'Trusted publishers');\n break;\n case 'registries':\n addAccountUrl(resources, accountOrigin, '/settings/registries', 'Registry settings');\n break;\n case 'security':\n addAccountUrl(\n resources,\n accountOrigin,\n '/settings/two-factor-authentication',\n 'Two-factor authentication settings',\n );\n break;\n }\n }\n return dedupeResources(resources);\n}\n\nfunction addAccountUrl(\n resources: PublishDiagnosticResource[],\n origin: string | undefined,\n path: string,\n label: string,\n): void {\n if (!origin) return;\n resources.push({ kind: 'url', url: new URL(path, origin).href, label });\n}\n\nfunction accountOriginForIssuer(issuer: string): string | undefined {\n try {\n const url = new URL(issuer);\n return url.protocol === 'https:' || url.protocol === 'http:' ? url.origin : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction validatedServerCode(error: unknown): string | undefined {\n return error instanceof ControlPlaneError && SERVER_CODE_PATTERN.test(error.code) ? error.code : undefined;\n}\n\nfunction validatedStatus(error: unknown): number | undefined {\n if (!(error instanceof ControlPlaneError) || error.status === undefined) return undefined;\n return Number.isInteger(error.status) && error.status >= 100 && error.status <= 599 ? error.status : undefined;\n}\n\nfunction isNetworkFailure(error: unknown): boolean {\n return (\n error instanceof TypeError ||\n (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError'))\n );\n}\n\nfunction safeDisplayValue(value: unknown, maximumLength: number): string | undefined {\n if (typeof value !== 'string') return undefined;\n const normalized = value.trim();\n return normalized.length > 0 && normalized.length <= maximumLength && !hasUnsafeDisplayCharacter(normalized)\n ? normalized\n : undefined;\n}\n\nfunction hasUnsafeDisplayCharacter(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0);\n if (\n codePoint !== undefined &&\n (codePoint <= 0x1f ||\n (codePoint >= 0x7f && codePoint <= 0x9f) ||\n codePoint === 0x061c ||\n codePoint === 0x200e ||\n codePoint === 0x200f ||\n (codePoint >= 0x2028 && codePoint <= 0x202e) ||\n (codePoint >= 0x2066 && codePoint <= 0x2069))\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction safeOwner(value: unknown): string | undefined {\n const parsed = ownerNameSchema.safeParse(value);\n return parsed.success ? parsed.data : undefined;\n}\n\nfunction safeRepository(value: unknown): string | undefined {\n const parsed = repositorySchema.safeParse(value);\n return parsed.success ? parsed.data : undefined;\n}\n\nfunction safePackageLabel(packageName: string): string {\n const safe = safeDisplayValue(packageName, 214);\n return safe ? `\"${safe}\"` : 'this package';\n}\n\nfunction packageCoordinate(context: PublishRequestErrorContext): string {\n const packageName = safeDisplayValue(context.packageName, 214);\n const version = safeDisplayValue(context.packageVersion, 256);\n return packageName && version ? `\"${packageName}@${version}\"` : 'This package version';\n}\n\nfunction scopedOwner(packageName: string): string | undefined {\n const match = safeDisplayValue(packageName, 214)?.match(/^@([^/]+)\\//u);\n return safeOwner(match?.[1]);\n}\n\nfunction credentialKindLabel(kind: PublishRequestErrorContext['credentialKind']): string {\n switch (kind) {\n case 'login':\n return 'CLI login';\n case 'gat':\n return 'Granular access token';\n case 'oidc':\n return 'GitHub Actions trusted publishing';\n }\n}\n\nfunction capabilityLabel(capability: z.output<typeof missingCapabilitiesSchema>[number]): string {\n return capability === 'package.publish' ? 'Publish packages' : 'Submit publishing requests';\n}\n\nfunction oauthScopeLabel(scope: z.output<typeof missingOAuthScopesSchema>[number]): string {\n return scope === 'publishing.request.create' ? 'Submit publishing requests' : 'Read your publishing requests';\n}\n\nfunction accessModeLabel(\n mode: z.output<typeof accessModeSchema> | undefined,\n category: 'package' | 'registry',\n): string | undefined {\n if (!mode) return undefined;\n const noun = category === 'package' ? 'packages' : 'registries';\n switch (mode) {\n case 'none':\n return `No ${noun}`;\n case 'selected':\n return `Selected ${noun}`;\n case 'all':\n return `All ${noun}`;\n }\n}\n\nfunction accessModesLabel(\n modes: readonly ('selected' | 'all')[] | undefined,\n category: 'package' | 'registry',\n): string | undefined {\n if (!modes || modes.length === 0) return undefined;\n const labels = [...new Set(modes)].map((mode) => accessModeLabel(mode, category)).filter(Boolean);\n return labels.join(' or ');\n}\n\nfunction formatDuration(seconds: number): string {\n if (seconds === 1) return '1 second';\n if (seconds < 60) return `${seconds} seconds`;\n if (seconds % 60 === 0) {\n const minutes = seconds / 60;\n return `${minutes} ${minutes === 1 ? 'minute' : 'minutes'}`;\n }\n return `${seconds} seconds`;\n}\n\nfunction quotedList(values: readonly string[]): string {\n const quoted = values.map((value) => `\"${value}\"`);\n if (quoted.length === 1) return quoted[0] as string;\n if (quoted.length === 2) return `${quoted[0]} or ${quoted[1]}`;\n return `${quoted.slice(0, -1).join(', ')}, or ${quoted.at(-1)}`;\n}\n\nfunction fact(kind: PublishDiagnosticFact['kind'], value: string | undefined): PublishDiagnosticFact | undefined {\n return value ? { kind, value } : undefined;\n}\n\nfunction compactFacts(facts: readonly (PublishDiagnosticFact | undefined)[]): PublishDiagnosticFact[] {\n return facts.filter((value): value is PublishDiagnosticFact => value !== undefined);\n}\n\nfunction dedupeFacts(facts: readonly PublishDiagnosticFact[]): PublishDiagnosticFact[] {\n const seen = new Set<string>();\n return facts.filter((factValue) => {\n const key = `${factValue.kind}\\0${factValue.value}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction dedupeResources(resources: readonly PublishDiagnosticResource[]): PublishDiagnosticResource[] {\n const seen = new Set<string>();\n return resources.filter((resource) => {\n const key = resource.kind === 'command' ? `command\\0${resource.command}` : `url\\0${resource.url}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction shellDisplayArgument(value: string): string {\n const safe = safeDisplayValue(value, 100);\n return safe && /^[A-Za-z0-9._-]+$/u.test(safe) ? safe : '<registry>';\n}\n"],"mappings":";;;;;AASA,MAAM,sBAAsB;AAE5B,MAAM,eAAe,kBACnB,EACG,OAAO,CAAC,CACR,KAAK,CAAC,CACN,IAAI,CAAC,CAAC,CACN,IAAI,aAAa,CAAC,CAClB,QAAQ,UAAU,CAAC,0BAA0B,KAAK,CAAC;AACxD,MAAM,oBAAoB,YAAY,G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UACtC,2EACA,6HACA,CAAC,SAAS,oBAAoB,CAChC;CACA,iCAAiC;CACjC,kCAAkC,UAChC,0EACA,iIACA,CAAC,oBAAoB,CACvB;CAGA,sBAAsB,UACpB,2DACA,mIACF;CACA,0BAA0B,UACxB,4EACA,mJACA,CAAC,cAAc,eAAe,CAChC;CACA,iBAAiB,UACf,+DACA,+GACF;CACA,iCAAiC,UAC/B,wDACA,iGACA,CAAC,eAAe,CAClB;CACA,iBAAiB,UACf,sEACA,kIACF;CACA,gCAAgC,UAC9B,sEACA,kIACF;CACA,yBAAyB,UACvB,8DACA,mHACF;CACA,2BAA2B,UACzB,4EACA,qGACF;CACA,qBAAqB,UACnB,kEACA,iHACF;CACA,4BAA4B,UAC1B,yEACA,oFACF;CACA,6BAA6B,UAC3B,0EACA,oHACF;CACA,yBAAyB,UACvB,8DACA,oHACF;CACA,uBAAuB,UACrB,4DACA,oHACF;CACA,iBAAiB,UACf,qFACA,uFACF;CACA,0BAA0B,UACxB,kGACA,gFACF;CACA,wBAAwB,UACtB,iEACA,8FACF;CACA,uBAAuB,UACrB,4DACA,kGACF;CACA,8BAA8B,UAC5B,+DACA,yFACF;CACA,gCAAgC,UAC9B,8DACA,uFACF;CACA,iCAAiC,UAC/B,uEACA,sGACF;CACA,oCAAoC,UAClC,kEACA,iGACF;CACA,kCAAkC,UAChC,sDACA,kGACF;CACA,6CAA6C,UAC3C,2FACA,mHACA,CAAC,YAAY,CACf;CACA,sCAAsC,kBAAkB,wDAAwD;CAChH,6BAA6B,kBAC3B,0EACF;CACA,qBAAqB,kBAAkB,gDAAgD;CACvF,mBAAmB,UACjB,wEACA,+FACF;CACA,wBAAwB,UACtB,0DACA,+FACF;CACA,iCAAiC,UAC/B,0DACA,+FACF;CACA,wBAAwB,kBAAkB,yDAAyD;CACnG,cAAc,kBAAkB,qDAAqD;CACrF,sBAAsB,kBAAkB,2DAA2D;CACnG,+BAA+B,kBAAkB,2DAA2D;CAC5G,0BAA0B,kBAAkB,0DAA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,IAAI,MAAM,EAAE;CACjD,IAAI,OAAO,WAAW,GAAG,OAAO,OAAO;CACvC,IAAI,OAAO,WAAW,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,OAAO;CAC1D,OAAO,GAAG,OAAO,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,OAAO,OAAO,GAAG,EAAE;AAC9D;AAEA,SAAS,KAAK,MAAqC,OAA8D;CAC/G,OAAO,QAAQ;EAAE;EAAM;CAAM,IAAI;AACnC;AAEA,SAAS,aAAa,OAAgF;CACpG,OAAO,MAAM,QAAQ,UAA0C,UAAU,MAAS;AACpF;AAEA,SAAS,YAAY,OAAkE;CACrF,MAAM,uBAAO,IAAI,IAAY;CAC7B,OAAO,MAAM,QAAQ,cAAc;EACjC,MAAM,MAAM,GAAG,UAAU,KAAK,IAAI,UAAU;EAC5C,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO;EAC1B,KAAK,IAAI,GAAG;EACZ,OAAO;CACT,CAAC;AACH;AAEA,SAAS,gBAAgB,WAA8E;CACrG,MAAM,uBAAO,IAAI,IAAY;CAC7B,OAAO,UAAU,QAAQ,aAAa;EACpC,MAAM,MAAM,SAAS,SAAS,YAAY,YAAY,SAAS,YAAY,QAAQ,SAAS;EAC5F,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO;EAC1B,KAAK,IAAI,GAAG;EACZ,OAAO;CACT,CAAC;AACH;AAEA,SAAS,qBAAqB,OAAuB;CACnD,MAAM,OAAO,iBAAiB,OAAO,GAAG;CACxC,OAAO,QAAQ,qBAAqB,KAAK,IAAI,IAAI,OAAO;AAC1D"}
|
|
1
|
+
{"version":3,"file":"PublishRequestErrorMapper.js","names":[],"sources":["../../src/control-plane/PublishRequestErrorMapper.ts"],"sourcesContent":["import {\n createPublishRequestFailedDiagnostic,\n type PublishDiagnosticFact,\n type PublishDiagnosticResource,\n type PublishRequestFailedDiagnostic,\n} from '@uapkg/diagnostics';\nimport { z } from 'zod';\nimport { ControlPlaneError } from '#cli/control-plane/ControlPlaneTypes.ts';\n\nconst SERVER_CODE_PATTERN = /^[A-Z][A-Z0-9_]{0,127}$/u;\n\nconst boundedText = (maximumLength: number) =>\n z\n .string()\n .trim()\n .min(1)\n .max(maximumLength)\n .refine((value) => !hasUnsafeDisplayCharacter(value));\nconst packageNameSchema = boundedText(214);\nconst packageVersionSchema = boundedText(256);\nconst ownerNameSchema = boundedText(100).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/u);\nconst repositorySchema = boundedText(255).regex(/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u);\nconst requestIdSchema = boundedText(128).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u);\nconst accessModeSchema = z.enum(['none', 'selected', 'all']);\nconst missingCapabilitiesSchema = z\n .array(z.enum(['package.publish', 'publishing.request.create']))\n .max(10)\n .transform((values) => [...new Set(values)]);\nconst missingOAuthScopesSchema = z\n .array(z.enum(['publishing.request.create', 'publishing.request.read.self']))\n .max(2)\n .transform((values) => [...new Set(values)]);\nconst ownerNamesSchema = z\n .array(ownerNameSchema)\n .max(20)\n .transform((values) => [...new Set(values)].sort());\n\nconst emptyDetailsSchema = z.object({});\nconst packageDetailsSchema = z.object({ packageName: packageNameSchema.optional() });\nconst ownerRequiredDetailsSchema = packageDetailsSchema;\nconst requestedOwnerDetailsSchema = packageDetailsSchema.extend({\n requestedOwnerOrganizationName: ownerNameSchema.optional(),\n ownerOrganizationName: ownerNameSchema.optional(),\n allowedOwnerOrganizationNames: ownerNamesSchema.optional(),\n});\nconst gatOwnerMismatchDetailsSchema = packageDetailsSchema.extend({\n requestedOwnerOrganizationName: ownerNameSchema.optional(),\n tokenOwnerOrganizationNames: ownerNamesSchema.optional(),\n});\nconst scopeMismatchDetailsSchema = packageDetailsSchema.extend({\n requestedScopeOwner: ownerNameSchema.optional(),\n scopeOwner: ownerNameSchema.optional(),\n allowedScopeOwners: ownerNamesSchema.optional(),\n tokenOwnerOrganizationNames: ownerNamesSchema.optional(),\n});\nconst tokenAccessDetailsSchema = packageDetailsSchema.extend({\n actualPackageAccessMode: accessModeSchema.optional(),\n requiredPackageAccessMode: z.literal('all').optional(),\n missingCapabilities: missingCapabilitiesSchema.optional(),\n packageAccess: z.object({ mode: accessModeSchema }).optional(),\n actualRegistryAccessMode: accessModeSchema.optional(),\n requiredRegistryAccessModes: z\n .array(z.enum(['selected', 'all']))\n .max(2)\n .optional(),\n requiredPackageAccessModes: z\n .array(z.enum(['selected', 'all']))\n .max(2)\n .optional(),\n registryAccess: z.object({ mode: accessModeSchema }).optional(),\n});\nconst tokenPermissionDetailsSchema = z.object({\n missingCapabilities: missingCapabilitiesSchema.optional(),\n});\nconst oauthScopeDetailsSchema = z.object({\n missingScopes: missingOAuthScopesSchema.optional(),\n});\nconst oidcRepositoryDetailsSchema = packageDetailsSchema.extend({\n submittedRepository: repositorySchema.optional(),\n trustedRepository: repositorySchema.optional(),\n});\nconst versionDetailsSchema = z.object({\n packageName: packageNameSchema.optional(),\n packageVersion: packageVersionSchema.optional(),\n});\nconst activeRequestDetailsSchema = versionDetailsSchema.extend({\n activeRequestId: requestIdSchema.optional(),\n});\nconst haltedPackageDetailsSchema = packageDetailsSchema.extend({\n blockingRequestId: requestIdSchema.optional(),\n});\nconst retryDetailsSchema = z.object({\n retryAfterSeconds: z.number().int().min(1).max(86_400).optional(),\n});\n\nexport interface PublishRequestErrorContext {\n readonly packageName: string;\n readonly packageVersion: string;\n readonly registryAlias: string;\n readonly registryName?: string;\n readonly registryIssuer: string;\n readonly credentialKind: 'login' | 'gat' | 'oidc';\n readonly requestedOwner?: string;\n readonly repository: string;\n}\n\ntype ResourceKind =\n | 'access-tokens'\n | 'help'\n | 'login'\n | 'owner-command'\n | 'requests'\n | 'security'\n | 'registries'\n | 'trusted-publishers';\n\ninterface PublishGuidance {\n readonly message: string;\n readonly hint: string;\n readonly facts?: readonly PublishDiagnosticFact[];\n readonly resources?: readonly ResourceKind[];\n readonly requestId?: string;\n}\n\ninterface PublishErrorSpec {\n build(details: unknown, context: PublishRequestErrorContext): PublishGuidance;\n}\n\nfunction defineSpec<Schema extends z.ZodObject>(\n schema: Schema,\n build: (details: z.output<Schema>, context: PublishRequestErrorContext) => PublishGuidance,\n): PublishErrorSpec {\n const empty = schema.parse({});\n return {\n build(details, context) {\n const parsed = schema.safeParse(details ?? {});\n return build(parsed.success ? parsed.data : empty, context);\n },\n };\n}\n\nfunction fixedSpec(message: string, hint: string, resources: readonly ResourceKind[] = []): PublishErrorSpec {\n return defineSpec(emptyDetailsSchema, () => ({ message, hint, resources }));\n}\n\nconst UPDATE_CLIENT_AND_RETRY =\n 'Update UAPKG CLI and try again. If the problem remains, report the server code to the registry operator.';\nconst RETRY_AND_REPORT =\n 'Try publishing again. If the failure continues, report the server code to the registry operator.';\nconst LOGIN_AGAIN = 'Sign in again for this registry, then retry the publication.';\nconst CHECK_TOKEN =\n 'Create or use an active granular access token with the correct owner, permissions, and package access, then try again.';\n\nconst clientRequestSpec = (message: string) => fixedSpec(message, UPDATE_CLIENT_AND_RETRY);\nconst internalServiceSpec = (message: string) => fixedSpec(message, RETRY_AND_REPORT);\nconst loginSpec = (message: string) => fixedSpec(message, LOGIN_AGAIN, ['login']);\nconst tokenSpec = (message: string) => fixedSpec(message, CHECK_TOKEN, ['access-tokens']);\n\nconst unscopedOwnerSpec = defineSpec(ownerRequiredDetailsSchema, (_details, context) => {\n const packageName = safeDisplayValue(context.packageName, 214);\n return {\n message: packageName\n ? `\"${packageName}\" needs an owner organization before it can be published for the first time.`\n : 'This unscoped package needs an owner organization before it can be published for the first time.',\n hint: 'Pass `--owner <organization>`, set `publish.owner` in uapkg.json, or publish the package under an `@organization/name` scope.',\n resources: ['owner-command'],\n };\n});\n\nconst gatOwnerMismatchSpec = defineSpec(gatOwnerMismatchDetailsSchema, (details, context) => {\n const requestedOwner = details.requestedOwnerOrganizationName ?? safeOwner(context.requestedOwner);\n const tokenOwners = details.tokenOwnerOrganizationNames ?? [];\n const ownerDescription = tokenOwners.length > 0 ? quotedList(tokenOwners) : 'a different organization';\n const requestedDescription = requestedOwner ? `\"${requestedOwner}\"` : 'the requested organization';\n const scoped = scopedOwner(context.packageName);\n return {\n message: `The selected token was created for ${ownerDescription}, but this publication asks to use ${requestedDescription}.`,\n hint: scoped\n ? `Use a token created for \"${scoped}\", or rebuild the package under the organization scope this token acts for.`\n : 'Correct or remove the explicit owner, or use a token created for the organization that should own this package.',\n facts: compactFacts([\n fact('requested-owner', requestedOwner),\n ...tokenOwners.map((owner) => fact('token-owner', owner)),\n ]),\n resources: ['access-tokens'],\n };\n});\n\nconst scopeMismatchSpec = defineSpec(scopeMismatchDetailsSchema, (details, context) => {\n const requestedOwner = details.requestedScopeOwner ?? details.scopeOwner ?? scopedOwner(context.packageName);\n const allowedOwners = details.allowedScopeOwners ?? details.tokenOwnerOrganizationNames ?? [];\n const requestedDescription = requestedOwner ? `\"@${requestedOwner}\"` : 'The package scope';\n const allowedDescription =\n allowedOwners.length > 0\n ? quotedList(allowedOwners.map((owner) => `@${owner}`))\n : 'the organization this token acts for';\n return {\n message: `${requestedDescription} does not match ${allowedDescription}.`,\n hint: 'Use a token created for the package scope, or rebuild the package under the organization scope this token acts for.',\n facts: compactFacts([\n fact('requested-owner', requestedOwner),\n ...allowedOwners.map((owner) => fact('allowed-owner', owner)),\n ]),\n resources: ['access-tokens'],\n };\n});\n\nconst initialTokenAccessSpec = defineSpec(tokenAccessDetailsSchema, (details) => {\n const actualMode = details.actualPackageAccessMode ?? details.packageAccess?.mode;\n const requiredMode = details.requiredPackageAccessMode ?? 'all';\n const missing = details.missingCapabilities ?? (actualMode === undefined ? ['package.publish'] : []);\n return {\n message: 'This token cannot create a package during its first publication.',\n hint: 'Create or use a token with Package Access set to All and permission to publish packages.',\n facts: compactFacts([\n fact('actual-access-mode', accessModeLabel(actualMode, 'package')),\n fact('required-access-mode', accessModeLabel(requiredMode, 'package')),\n ...missing.map((capability) => fact('missing-capability', capabilityLabel(capability))),\n ]),\n resources: ['access-tokens'],\n };\n});\n\nconst tokenPermissionSpec = defineSpec(tokenPermissionDetailsSchema, (details) => ({\n message: 'This token does not allow package publication.',\n hint: 'Create or use a token with permission to publish packages, then try again.',\n facts: (details.missingCapabilities ?? ['package.publish']).map((capability) => ({\n kind: 'missing-capability' as const,\n value: capabilityLabel(capability),\n })),\n resources: ['access-tokens'],\n}));\n\nconst oauthScopeSpec = defineSpec(oauthScopeDetailsSchema, (details) => ({\n message: 'This CLI login does not include permission to submit publishing requests.',\n hint: 'Reauthorize the login for this registry, then try publishing again.',\n facts: (details.missingScopes ?? ['publishing.request.create']).map((scope) => ({\n kind: 'missing-capability' as const,\n value: oauthScopeLabel(scope),\n })),\n resources: ['login'],\n}));\n\nconst packageOwnerNotAuthorizedSpec = defineSpec(requestedOwnerDetailsSchema, (details, context) => {\n const owner =\n details.requestedOwnerOrganizationName ?? details.ownerOrganizationName ?? safeOwner(context.requestedOwner);\n const allowedOwners = details.allowedOwnerOrganizationNames ?? [];\n const scoped = scopedOwner(context.packageName);\n const retryOwner = allowedOwners.length === 1 && !scoped ? allowedOwners[0] : undefined;\n return {\n message: owner\n ? `Your account is not allowed to create this package for UAPKG organization \"${owner}\".`\n : 'Your account is not allowed to create this package for the requested UAPKG organization.',\n hint: scoped\n ? allowedOwners.length > 0\n ? 'This package’s `@owner` scope determines ownership. Rebuild it under one of the allowed UAPKG organization scopes shown above.'\n : 'This package’s `@owner` scope determines ownership. Rebuild it under a UAPKG organization scope where you can publish, or ask an organization administrator to grant access.'\n : retryOwner\n ? `Retry with \\`--owner ${retryOwner}\\` to use the allowed UAPKG organization namespace.`\n : allowedOwners.length > 0\n ? 'Choose one of the allowed UAPKG organization namespaces with `--owner`, or ask a UAPKG organization administrator to grant access.'\n : 'Choose a UAPKG organization namespace where you can publish, or ask a UAPKG organization administrator to grant access.',\n facts: compactFacts([\n fact('requested-owner', owner),\n ...allowedOwners.map((allowedOwner) => fact('allowed-owner', allowedOwner)),\n ]),\n };\n});\n\nconst publishingAuthorityDeniedSpec = defineSpec(emptyDetailsSchema, (_details, context) => {\n switch (context.credentialKind) {\n case 'oidc':\n return {\n message: 'This GitHub Actions workflow does not currently have publishing authority for the package.',\n hint: 'Check the package’s trusted-publisher repository, workflow, and optional GitHub Environment setting, then run the workflow again.',\n resources: ['trusted-publishers'],\n };\n case 'gat':\n return {\n message: 'This granular access token does not currently have publishing authority for the package.',\n hint: 'Create or use a token for the package owner with the required package access and publishing permission.',\n resources: ['access-tokens'],\n };\n case 'login':\n return {\n message: 'Your account does not currently have publishing authority for the package.',\n hint: 'Choose an owner organization where you can publish, or ask an organization administrator to grant access.',\n };\n }\n});\n\nconst tokenResourceAccessSpec = defineSpec(tokenAccessDetailsSchema, (details) => {\n const actualPackageMode = details.actualPackageAccessMode ?? details.packageAccess?.mode;\n const actualRegistryMode = details.actualRegistryAccessMode ?? details.registryAccess?.mode;\n const requiredPackageModes = details.requiredPackageAccessModes;\n const requiredRegistryModes = details.requiredRegistryAccessModes;\n return {\n message: 'This token does not cover the package or registry selected for publication.',\n hint: 'Create or use a token whose package and registry access cover this publication.',\n facts: compactFacts([\n fact('actual-access-mode', accessModeLabel(actualPackageMode, 'package')),\n fact('actual-access-mode', accessModeLabel(actualRegistryMode, 'registry')),\n fact('required-access-mode', accessModesLabel(requiredPackageModes, 'package')),\n fact('required-access-mode', accessModesLabel(requiredRegistryModes, 'registry')),\n ]),\n resources: ['access-tokens'],\n };\n});\n\nconst oidcRepositorySpec = defineSpec(oidcRepositoryDetailsSchema, (details, context) => {\n const submitted = details.submittedRepository ?? safeRepository(context.repository);\n const trusted = details.trustedRepository;\n if (!trusted) {\n return {\n message: 'The registry could not determine the trusted repository for this workflow session.',\n hint: 'Start a new trusted-publishing workflow and try again. If the failure continues, review the trusted-publisher rule and report the server code.',\n facts: compactFacts([fact('requested-repository', submitted)]),\n resources: ['trusted-publishers'],\n };\n }\n return {\n message: submitted\n ? `This workflow submitted \"${submitted}\", but its trusted-publisher rule is bound to \"${trusted}\".`\n : 'The registry could not compare the package source with this workflow’s trusted-publisher rule.',\n hint: submitted\n ? 'Publish from the repository named by the trusted-publisher rule, or update the rule for the intended package source.'\n : 'Start a new trusted-publishing workflow and try again. If the failure continues, report the server code.',\n facts: compactFacts([fact('requested-repository', submitted), fact('trusted-repository', trusted)]),\n resources: ['trusted-publishers'],\n };\n});\n\nconst versionConflictSpec = (kind: 'exists' | 'tombstoned') =>\n defineSpec(versionDetailsSchema, (_details, context) => {\n const coordinate = packageCoordinate(context);\n return kind === 'exists'\n ? {\n message: `${coordinate} is already published in this registry.`,\n hint: 'Choose a new version in uapkg.json, rebuild the archive, and publish that version instead.',\n resources: ['requests'],\n }\n : {\n message: `${coordinate} was previously unpublished and cannot be reused.`,\n hint: 'Choose a new version in uapkg.json, rebuild the archive, and publish that version instead.',\n resources: ['requests'],\n };\n });\n\nconst activeRequestSpec = (ownershipConflict: boolean) =>\n defineSpec(activeRequestDetailsSchema, (details, context) => {\n const coordinate = packageCoordinate(context);\n const readableRequestId = ownershipConflict ? undefined : details.activeRequestId;\n return {\n message: ownershipConflict\n ? `Another organization already has an active first-publication request for ${safePackageLabel(context.packageName)}.`\n : `An active publishing request already covers ${coordinate}.`,\n hint: ownershipConflict\n ? 'Wait for that request to finish before trying to claim this package name, or review your own request when a request ID is shown.'\n : 'Wait for the active request to finish instead of submitting the same publication again.',\n facts: compactFacts([fact('request-id', readableRequestId)]),\n resources: ['requests'],\n requestId: readableRequestId,\n };\n });\n\nconst haltedPackageSpec = defineSpec(haltedPackageDetailsSchema, (details, context) => ({\n message: `Publishing for ${safePackageLabel(context.packageName)} is paused because an earlier request could not be completed.`,\n hint: 'Review the earlier request and ask the registry operator to resolve its failure before publishing again.',\n facts: compactFacts([fact('request-id', details.blockingRequestId)]),\n resources: ['requests'],\n requestId: details.blockingRequestId,\n}));\n\nconst rateLimitSpec = defineSpec(retryDetailsSchema, (details) => ({\n message: 'Too many publishing requests were submitted in a short time.',\n hint: details.retryAfterSeconds\n ? `Wait ${formatDuration(details.retryAfterSeconds)}, then try publishing again.`\n : 'Wait a moment, then try publishing again.',\n facts: compactFacts([\n fact('retry-after', details.retryAfterSeconds ? formatDuration(details.retryAfterSeconds) : undefined),\n ]),\n}));\n\n/**\n * Explicit inventory of errors that can be returned synchronously while the\n * CLI submits POST /v1/registry-requests/publish. Unknown future codes use the\n * non-leaking fallback in {@link publishRequestDiagnosticForError}.\n */\nexport const PUBLISH_SUBMISSION_ERROR_CATALOG = {\n // Authentication and request-bound authorization.\n AUTH_REQUIRED: loginSpec('Authentication is required to publish this package.'),\n CONTROL_PLANE_AUTHENTICATION_REQUIRED: loginSpec('The saved registry login was rejected.'),\n DPOP_AUTH_UNAVAILABLE: internalServiceSpec('The registry cannot validate CLI logins right now.'),\n DPOP_AUTH_REQUIRED: loginSpec('The publishing request did not include a valid CLI login.'),\n DPOP_PROOF_INVALID: loginSpec('The saved CLI login proof was rejected.'),\n DPOP_PROOF_REPLAYED: fixedSpec(\n 'The security proof for this CLI login was already used.',\n 'Run the publish command again. If the failure continues, sign in to the selected registry again.',\n ['login'],\n ),\n DPOP_ACCESS_TOKEN_INVALID: loginSpec('The saved CLI login is invalid or no longer usable.'),\n DPOP_PROOF_STALE: fixedSpec(\n 'The security proof for this CLI login expired before the request arrived.',\n 'Run the publish command again. If the failure continues, sign in to the selected registry again.',\n ['login'],\n ),\n DPOP_NONCE_REQUIRED: fixedSpec(\n 'The registry could not complete the security challenge for this CLI login.',\n 'Run the publish command again. If the failure continues, sign in to the selected registry again.',\n ['login'],\n ),\n REGISTRY_GRANT_INVALID: loginSpec('The registry login was revoked, expired, or belongs to another registry.'),\n CLI_LOGIN_ACTIVATION_EXPIRED: loginSpec('This CLI login expired before the device finished confirming it.'),\n ACCOUNT_NOT_ACTIVE: loginSpec('The account for this registry login is not active.'),\n CLI_ACCESS_TOKEN_INVALID: loginSpec('The saved CLI login is invalid.'),\n CLI_ACCESS_TOKEN_EXPIRED: loginSpec('The saved CLI login has expired.'),\n OAUTH_SCOPE_INSUFFICIENT: oauthScopeSpec,\n OAUTH_SCOPE_UNSUPPORTED: fixedSpec(\n 'This CLI version does not understand a capability required by the registry.',\n 'Update UAPKG CLI, sign in again, and retry the publication.',\n ['login'],\n ),\n TOKEN_INVALID: tokenSpec('The selected granular access token is invalid.'),\n TOKEN_REVOKED: tokenSpec('The selected granular access token has been revoked.'),\n TOKEN_EXPIRED: tokenSpec('The selected granular access token has expired.'),\n UAPKG_TOKEN_APPROVAL_PENDING: fixedSpec(\n 'The selected token is still waiting for organization approval.',\n 'Ask an organization administrator to approve the token, or select a different active token.',\n ['access-tokens'],\n ),\n UAPKG_TOKEN_APPROVAL_DENIED: fixedSpec(\n 'The organization denied the selected token request.',\n 'Use an approved token, or request a new token from the organization.',\n ['access-tokens'],\n ),\n UAPKG_TOKEN_ORGANIZATION_POLICY_DENIED: fixedSpec(\n 'The organization’s token policy blocks this publication.',\n 'Ask an organization administrator to review the token policy, or publish with an allowed credential.',\n ['access-tokens'],\n ),\n UAPKG_TOKEN_TEMPORARILY_BLOCKED_OWNER_MFA_REQUIRED: fixedSpec(\n 'This token is temporarily blocked because its owner must enable two-factor authentication.',\n 'Enable two-factor authentication for the token owner, then try again.',\n ['access-tokens', 'security'],\n ),\n UAPKG_TOKEN_LIFECYCLE_DISABLED: tokenSpec('The selected token is not currently usable.'),\n UAPKG_TOKEN_PERMISSION_DENIED: tokenPermissionSpec,\n UAPKG_TOKEN_RESOURCE_ACCESS_DENIED: tokenResourceAccessSpec,\n SECOND_FACTOR_REQUIRED: fixedSpec(\n 'A current two-factor authentication code is required for this publication.',\n 'Run the publish command again and enter the current code when prompted.',\n ['security'],\n ),\n OTP_INVALID: fixedSpec(\n 'The two-factor authentication code was incorrect or expired.',\n 'Run the publish command again and enter a new code when prompted.',\n ['security'],\n ),\n OTP_NOT_ENROLLED: fixedSpec(\n 'This account must enroll in two-factor authentication before publishing.',\n 'Enable two-factor authentication in account settings, then try publishing again.',\n ['security'],\n ),\n OTP_RATE_LIMITED: rateLimitSpec,\n OTP_ERROR: internalServiceSpec('The registry could not verify the two-factor authentication code.'),\n OTP_UNSUPPORTED_PRINCIPAL: fixedSpec(\n 'This credential cannot use an interactive two-factor authentication code.',\n 'Select a CLI login or granular access token that supports attended publication.',\n ),\n SECURED_ACCOUNT_REQUIRED: fixedSpec(\n 'Publishing requires an active account with two-factor authentication enabled.',\n 'Activate the account and enable two-factor authentication, then try again.',\n ['security'],\n ),\n ACTOR_WRITE_FORBIDDEN: fixedSpec(\n 'This account is not allowed to submit registry changes.',\n 'Use an account with publishing access, or ask an organization administrator for access.',\n ),\n UAPKG_PRINCIPAL_NOT_ALLOWED: fixedSpec(\n 'This kind of credential cannot submit a publishing request.',\n 'Use a CLI login, granular access token, or configured GitHub Actions trusted publisher.',\n ),\n\n // Ownership, package naming, and token access.\n UNSCOPED_PACKAGE_OWNER_REQUIRED: unscopedOwnerSpec,\n GAT_OWNER_ORGANIZATION_MISMATCH: gatOwnerMismatchSpec,\n UAPKG_PACKAGE_SCOPE_OWNER_MISMATCH: scopeMismatchSpec,\n UAPKG_REGISTRY_REQUIRES_SCOPED_PACKAGE: defineSpec(packageDetailsSchema, (_details, context) => ({\n message: `This registry requires a scoped name for the first publication of ${safePackageLabel(context.packageName)}.`,\n hint: 'Rename the package to `@organization/name`, rebuild the archive, and publish it again.',\n })),\n INITIAL_PUBLICATION_PACKAGE_ACCESS_ALL_REQUIRED: initialTokenAccessSpec,\n PACKAGE_OWNER_NOT_AUTHORIZED: packageOwnerNotAuthorizedSpec,\n INITIAL_PUBLICATION_CREDENTIAL_UNSUPPORTED: fixedSpec(\n 'This credential cannot create a package during its first publication.',\n 'Publish the package once with an interactive CLI login or an attended granular access token.',\n ['login', 'access-tokens'],\n ),\n CLI_REGISTRY_GRANT_NOT_AUTHORIZED: fixedSpec(\n 'The saved CLI login cannot publish to this registry.',\n 'Reauthorize the login for the selected registry, then try again.',\n ['login'],\n ),\n REGISTRY_WRITE_DENIED_REBAC: publishingAuthorityDeniedSpec,\n GAT_CREDENTIAL_CONTEXT_REQUIRED: internalServiceSpec('The registry could not validate the selected token.'),\n PACKAGE_OWNER_NOT_RESOLVED: internalServiceSpec('The registry could not determine this package’s owner.'),\n\n // GitHub Actions trusted publishing.\n OIDC_SESSION_INVALID: fixedSpec(\n 'The GitHub Actions publishing session expired or is no longer trusted.',\n 'Run the workflow again. If it still fails, verify that the package still has an active trusted-publisher rule for this repository and workflow.',\n ['trusted-publishers'],\n ),\n OIDC_PROVIDER_UNAVAILABLE: fixedSpec(\n 'The registry cannot validate GitHub trusted publishing right now.',\n 'Run the workflow again later. If the failure continues, report the server code to the registry operator.',\n ['trusted-publishers'],\n ),\n OIDC_INITIAL_PUBLICATION_NOT_SUPPORTED: fixedSpec(\n 'GitHub Actions cannot create this package during its first publication.',\n 'Publish the package once with an interactive CLI login, then configure its trusted-publisher rule and rerun the workflow.',\n ['login', 'trusted-publishers'],\n ),\n OIDC_SOURCE_REPOSITORY_MISMATCH: oidcRepositorySpec,\n TRUSTED_PUBLISHER_NOT_AUTHORIZED: fixedSpec(\n 'This GitHub Actions workflow is not authorized to publish the package.',\n 'Check the package’s trusted-publisher repository, workflow, and optional GitHub Environment setting, then rerun the workflow.',\n ['trusted-publishers'],\n ),\n\n // Archive, source, claims, and request-contract validation.\n INVALID_PACKAGE_NAME: fixedSpec(\n 'The packaged manifest contains an invalid package name.',\n 'Set `name` in uapkg.json to a name such as `my-package` or `@organization/my-package`, rebuild the archive, and publish it again.',\n ),\n SCOPED_PACKAGES_DISABLED: fixedSpec(\n 'The selected registry does not accept organization-scoped package names.',\n 'Select a registry that supports scoped packages, or intentionally rename and rebuild the package as an unscoped package with an explicit owner.',\n ['registries', 'owner-command'],\n ),\n INVALID_VERSION: fixedSpec(\n 'The packaged manifest contains an invalid semantic version.',\n 'Set `version` in uapkg.json to a semantic version such as `1.2.3`, rebuild the archive, and publish it again.',\n ),\n INVALID_OWNER_ORGANIZATION_NAME: fixedSpec(\n 'The selected owner is not a valid organization name.',\n 'Correct `--owner <organization>` or `publish.owner` in uapkg.json, then try publishing again.',\n ['owner-command'],\n ),\n SOURCE_REQUIRED: fixedSpec(\n 'The publishing request did not identify its GitHub Release source.',\n 'Set `publish.repository` or pass `--repository owner/repository`, and make sure the release tag and asset exist before retrying.',\n ),\n GITHUB_RELEASE_SOURCE_REQUIRED: fixedSpec(\n 'The publishing request did not identify its GitHub Release source.',\n 'Set `publish.repository` or pass `--repository owner/repository`, and make sure the release tag and asset exist before retrying.',\n ),\n SOURCE_TYPE_UNSUPPORTED: fixedSpec(\n 'The registry does not support this kind of package source.',\n 'Publish from an uploaded GitHub Release asset. If this CLI produced another source type, update it and try again.',\n ),\n GITHUB_REPOSITORY_INVALID: fixedSpec(\n 'The publishing request contains an invalid GitHub repository coordinate.',\n 'Pass `--repository owner/repository` or correct `publish.repository` in uapkg.json, then try again.',\n ),\n RELEASE_TAG_INVALID: fixedSpec(\n 'The publishing request contains an invalid GitHub Release tag.',\n 'Pass a non-empty GitHub Release tag with `--tag <tag>`, or correct the package version used by the default tag.',\n ),\n RELEASE_ASSET_NAME_INVALID: fixedSpec(\n 'The publishing request contains an invalid GitHub Release asset name.',\n 'Pass the uploaded file name—not a path—with `--asset <file-name>`, then try again.',\n ),\n OBSERVED_INTEGRITY_REQUIRED: fixedSpec(\n 'The publishing request is missing the archive’s integrity information.',\n 'Re-read or rebuild the archive and try again. If the problem remains, update UAPKG CLI and report the server code.',\n ),\n OBSERVED_DIGEST_INVALID: fixedSpec(\n 'The publishing request contains an invalid archive digest.',\n 'Re-read or rebuild the archive and try again. If the problem remains, update UAPKG CLI and report the server code.',\n ),\n OBSERVED_SIZE_INVALID: fixedSpec(\n 'The publishing request contains an invalid archive size.',\n 'Re-read or rebuild the archive and try again. If the problem remains, update UAPKG CLI and report the server code.',\n ),\n CLAIMS_REQUIRED: fixedSpec(\n 'The publishing request is missing package information from the packaged manifest.',\n 'Rebuild the archive so it contains a valid uapkg.json, then publish the rebuilt file.',\n ),\n CLAIMS_IDENTITY_MISMATCH: fixedSpec(\n 'The package name or version inside the archive does not match the publication being submitted.',\n 'Rebuild the archive from the intended uapkg.json and publish the rebuilt file.',\n ),\n CLAIMS_PRIVATE_INVALID: fixedSpec(\n 'The packaged manifest has an invalid private-package setting.',\n 'Set `private` in uapkg.json to `true` or `false`, rebuild the archive, and publish it again.',\n ),\n CLAIMS_BUCKET_INVALID: fixedSpec(\n 'The packaged manifest has an invalid dependency section.',\n 'Make each dependency section in uapkg.json an object, rebuild the archive, and publish it again.',\n ),\n CLAIMS_DEPENDENCIES_TOO_MANY: fixedSpec(\n 'A dependency section in the packaged manifest is too large.',\n 'Reduce the dependency entries in uapkg.json, rebuild the archive, and publish it again.',\n ),\n CLAIMS_DEPENDENCY_NAME_INVALID: fixedSpec(\n 'The packaged manifest contains an invalid dependency name.',\n 'Correct the dependency name in uapkg.json, rebuild the archive, and publish it again.',\n ),\n CLAIMS_DEPENDENCY_RANGE_INVALID: fixedSpec(\n 'The packaged manifest contains an invalid dependency version range.',\n 'Set a non-empty bounded version range for the dependency, rebuild the archive, and publish it again.',\n ),\n CLAIMS_DEPENDENCY_REGISTRY_INVALID: fixedSpec(\n 'The packaged manifest contains an invalid dependency registry.',\n 'Correct the dependency registry alias in uapkg.json, rebuild the archive, and publish it again.',\n ),\n CLAIMS_DEPENDENCY_FIELDS_INVALID: fixedSpec(\n 'A packaged dependency contains unsupported fields.',\n 'Remove unsupported dependency fields from uapkg.json, rebuild the archive, and publish it again.',\n ),\n OFFICIAL_REGISTRY_PRIVATE_PACKAGE_FORBIDDEN: fixedSpec(\n 'This package is marked private, but the selected registry accepts only public packages.',\n 'Publish to a private registry, or intentionally remove the private setting, rebuild the archive, and try again.',\n ['registries'],\n ),\n SERVER_RESOLVED_METADATA_NOT_ALLOWED: clientRequestSpec('The publishing request contains server-owned metadata.'),\n UNRECOGNIZED_REQUEST_FIELDS: clientRequestSpec(\n 'The publishing request contains fields this registry does not recognize.',\n ),\n INVALID_REGISTRY_ID: clientRequestSpec('The CLI resolved an invalid registry identity.'),\n PAYLOAD_TOO_LARGE: fixedSpec(\n 'The packaged publication information is too large for this registry.',\n 'Reduce oversized manifest metadata or dependency entries, rebuild the archive, and try again.',\n ),\n REQUEST_BODY_TOO_LARGE: fixedSpec(\n 'The publishing request is too large for this registry.',\n 'Reduce oversized manifest metadata or dependency entries, rebuild the archive, and try again.',\n ),\n UAPKG_OPERATION_INPUT_TOO_LARGE: fixedSpec(\n 'The publishing request is too large for this registry.',\n 'Reduce oversized manifest metadata or dependency entries, rebuild the archive, and try again.',\n ),\n INVALID_CONTENT_LENGTH: clientRequestSpec('The registry received an incomplete publishing request.'),\n INVALID_JSON: clientRequestSpec('The registry could not read the publishing request.'),\n INVALID_REQUEST_BODY: clientRequestSpec('The registry could not understand the publishing request.'),\n UAPKG_OPERATION_INPUT_INVALID: clientRequestSpec('The registry could not understand the publishing request.'),\n IDEMPOTENCY_KEY_REQUIRED: clientRequestSpec('The publishing request was missing its retry-safety key.'),\n REQUEST_KIND_NOT_PUBLIC: internalServiceSpec('The CLI reached the wrong registry operation.'),\n SOURCE_NOT_ALLOWED: internalServiceSpec('The CLI reached the wrong registry operation for an artifact publication.'),\n REASON_REQUIRED: internalServiceSpec('The CLI reached an operation that requires a reason.'),\n DEPRECATION_MESSAGE_REQUIRED: internalServiceSpec(\n 'The CLI reached an operation that requires a deprecation message.',\n ),\n\n // Registry readiness, versions, and concurrent requests.\n REGISTRY_NOT_FOUND: fixedSpec(\n 'The selected registry is no longer available to the publishing service.',\n 'Refresh or reconfigure the registry, then try publishing again.',\n ['registries'],\n ),\n REGISTRY_LINK_MISSING: fixedSpec(\n 'The selected registry is not connected to an initialized repository.',\n 'Finish the registry repository connection in account settings, then try publishing again.',\n ['registries'],\n ),\n REGISTRY_LINK_NOT_READY: fixedSpec(\n 'The selected registry repository connection is incomplete.',\n 'Finish reconnecting the registry repository in account settings, then try publishing again.',\n ['registries'],\n ),\n PACKAGE_POLICY_NOT_CONFIGURED: internalServiceSpec(\n 'The registry is not ready to assign ownership for a new package.',\n ),\n PACKAGE_NOT_FOUND: fixedSpec(\n 'The package does not exist in the selected registry.',\n 'Check the package and registry, then try again.',\n ['registries'],\n ),\n PACKAGE_HALTED: haltedPackageSpec,\n VERSION_ALREADY_EXISTS: versionConflictSpec('exists'),\n VERSION_TOMBSTONED: versionConflictSpec('tombstoned'),\n DUPLICATE_ACTIVE_REQUEST: activeRequestSpec(false),\n PACKAGE_OWNERSHIP_PENDING_CONFLICT: activeRequestSpec(true),\n IDEMPOTENCY_KEY_CONFLICT: fixedSpec(\n 'The retry-safety key for this publication is already attached to a different request.',\n 'Run the publication again. If the conflict continues, report the server code to the registry operator.',\n ['requests'],\n ),\n RATE_LIMIT_EXCEEDED: rateLimitSpec,\n\n // Defensive catalog entries for invalid route state and server failures.\n REQUEST_ATTRIBUTION_INVALID: internalServiceSpec('The registry could not safely attribute this publishing request.'),\n AUTHORIZATION_RECEIPT_REQUIRED: internalServiceSpec(\n 'The registry could not preserve authorization for this request.',\n ),\n REQUEST_CREATE_FAILED: internalServiceSpec('The registry could not save the publishing request.'),\n OPERATION_AUTHORIZATION_ACTION_MISMATCH: internalServiceSpec('The publishing endpoint is misconfigured.'),\n OPERATION_BODY_LIMIT_UNREGISTERED: internalServiceSpec('The publishing endpoint is missing its request-size policy.'),\n UAPKG_OPERATION_BINDING_MISMATCH: internalServiceSpec('The publishing endpoint is bound incorrectly.'),\n UAPKG_OPERATION_BINDER_MISMATCH: internalServiceSpec(\n 'The publishing endpoint uses the wrong authentication boundary.',\n ),\n UAPKG_OPERATION_BODY_LIMIT_UNREGISTERED: internalServiceSpec(\n 'The publishing endpoint is missing its request-size policy.',\n ),\n UAPKG_SERVICE_AUTHENTICATION_REQUIRED: internalServiceSpec(\n 'The publishing endpoint rejected an unsupported credential.',\n ),\n REGISTRY_REQUEST_RESPONSE_INVALID: internalServiceSpec('The registry returned an invalid publishing response.'),\n CONTROL_PLANE_RESPONSE_NOT_JSON: internalServiceSpec('The registry returned an unreadable publishing response.'),\n\n // These normally belong to lifecycle routes, but cataloging them keeps a\n // misrouted publish response helpful and non-leaking.\n DESTRUCTIVE_POLICY_NOT_CONFIGURED: internalServiceSpec('The registry’s version policy is not configured.'),\n PACKAGE_VERSION_TARGET_NOT_FOUND: fixedSpec(\n 'The selected package version does not exist in the registry.',\n 'Check the package version and selected registry.',\n ['requests'],\n ),\n VERSION_ALREADY_UNPUBLISHED: fixedSpec(\n 'This package version is already unpublished.',\n 'No further action is needed.',\n ),\n VERSION_ALREADY_YANKED: fixedSpec('This package version is already yanked.', 'No further action is needed.'),\n VERSION_NOT_YANKED: fixedSpec(\n 'This package version is not yanked.',\n 'Check the current request state before trying again.',\n ),\n VERSION_ALREADY_DEPRECATED: fixedSpec('This package version is already deprecated.', 'No further action is needed.'),\n VERSION_NOT_DEPRECATED: fixedSpec(\n 'This package version is not deprecated.',\n 'Check the current request state before trying again.',\n ),\n UNPUBLISH_WINDOW_EXPIRED: fixedSpec(\n 'The allowed time window for unpublishing this version has closed.',\n 'Contact the registry operator if the version presents a security or legal issue.',\n ),\n} as const satisfies Record<string, PublishErrorSpec>;\n\nexport type PublishSubmissionErrorCode = keyof typeof PUBLISH_SUBMISSION_ERROR_CATALOG;\n\nexport function publishRequestDiagnosticForError(\n error: unknown,\n context: PublishRequestErrorContext,\n): PublishRequestFailedDiagnostic {\n const serverCode = validatedServerCode(error);\n const status = validatedStatus(error);\n const spec = serverCode\n ? (PUBLISH_SUBMISSION_ERROR_CATALOG as Record<string, PublishErrorSpec>)[serverCode]\n : undefined;\n const guidance = spec\n ? spec.build(error instanceof ControlPlaneError ? error.details : undefined, context)\n : fallback(error, status);\n const facts = dedupeFacts([...baseFacts(context), ...(guidance.facts ?? [])]);\n const resources = resourcesFor(guidance.resources ?? [], context, guidance.requestId);\n\n return createPublishRequestFailedDiagnostic(\n guidance.message,\n {\n ...(serverCode ? { serverCode } : {}),\n ...(status !== undefined ? { status } : {}),\n facts,\n resources,\n },\n guidance.hint,\n );\n}\n\nfunction fallback(error: unknown, status: number | undefined): PublishGuidance {\n if (isNetworkFailure(error)) {\n return {\n message: 'UAPKG could not reach the publishing service.',\n hint: 'Check the network connection and registry availability, then try publishing again.',\n };\n }\n if (status !== undefined && status >= 500) {\n return {\n message: 'The publishing service could not complete the request.',\n hint: RETRY_AND_REPORT,\n };\n }\n return {\n message: 'The registry did not accept the publishing request.',\n hint: 'Review the publication details and try again. If the failure continues, report this diagnostic to the registry operator.',\n };\n}\n\nfunction baseFacts(context: PublishRequestErrorContext): PublishDiagnosticFact[] {\n const registryName = safeDisplayValue(context.registryName ?? '', 100);\n const registryAlias = safeDisplayValue(context.registryAlias, 100);\n const registry =\n registryName && registryAlias && registryName !== registryAlias\n ? `${registryName} (${registryAlias})`\n : (registryName ?? registryAlias);\n return compactFacts([\n fact('package', safeDisplayValue(context.packageName, 214)),\n fact('version', safeDisplayValue(context.packageVersion, 256)),\n fact('registry', registry),\n fact('credential-kind', credentialKindLabel(context.credentialKind)),\n fact('requested-owner', safeOwner(context.requestedOwner)),\n fact('repository', safeRepository(context.repository)),\n ]);\n}\n\nfunction resourcesFor(\n requested: readonly ResourceKind[],\n context: PublishRequestErrorContext,\n requestId?: string,\n): PublishDiagnosticResource[] {\n const kinds = [...new Set([...requested, 'help' as const])];\n const accountOrigin = accountOriginForIssuer(context.registryIssuer);\n const resources: PublishDiagnosticResource[] = [];\n for (const kind of kinds) {\n switch (kind) {\n case 'help':\n resources.push({ kind: 'command', command: 'uapkg publish --help', label: 'Publish command help' });\n break;\n case 'login':\n resources.push({\n kind: 'command',\n command: `uapkg login --registry ${shellDisplayArgument(context.registryAlias)} --reauthorize`,\n label: 'Reauthorize this registry login',\n });\n break;\n case 'owner-command':\n resources.push({\n kind: 'command',\n command: 'uapkg publish --owner <organization>',\n label: 'Publish with an explicit owner',\n });\n break;\n case 'requests':\n if (requestId) {\n resources.push({\n kind: 'command',\n command: `uapkg requests status ${requestId}`,\n label: 'Inspect the related request',\n });\n }\n addAccountUrl(resources, accountOrigin, '/requests', 'Publishing requests');\n break;\n case 'access-tokens':\n addAccountUrl(resources, accountOrigin, '/settings/access-tokens', 'Access token settings');\n break;\n case 'trusted-publishers':\n addAccountUrl(resources, accountOrigin, '/trusted-publishers', 'Trusted publishers');\n break;\n case 'registries':\n addAccountUrl(resources, accountOrigin, '/settings/registries', 'Registry settings');\n break;\n case 'security':\n addAccountUrl(\n resources,\n accountOrigin,\n '/settings/two-factor-authentication',\n 'Two-factor authentication settings',\n );\n break;\n }\n }\n return dedupeResources(resources);\n}\n\nfunction addAccountUrl(\n resources: PublishDiagnosticResource[],\n origin: string | undefined,\n path: string,\n label: string,\n): void {\n if (!origin) return;\n resources.push({ kind: 'url', url: new URL(path, origin).href, label });\n}\n\nfunction accountOriginForIssuer(issuer: string): string | undefined {\n try {\n const url = new URL(issuer);\n return url.protocol === 'https:' || url.protocol === 'http:' ? url.origin : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction validatedServerCode(error: unknown): string | undefined {\n return error instanceof ControlPlaneError && SERVER_CODE_PATTERN.test(error.code) ? error.code : undefined;\n}\n\nfunction validatedStatus(error: unknown): number | undefined {\n if (!(error instanceof ControlPlaneError) || error.status === undefined) return undefined;\n return Number.isInteger(error.status) && error.status >= 100 && error.status <= 599 ? error.status : undefined;\n}\n\nfunction isNetworkFailure(error: unknown): boolean {\n return (\n error instanceof TypeError ||\n (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError'))\n );\n}\n\nfunction safeDisplayValue(value: unknown, maximumLength: number): string | undefined {\n if (typeof value !== 'string') return undefined;\n const normalized = value.trim();\n return normalized.length > 0 && normalized.length <= maximumLength && !hasUnsafeDisplayCharacter(normalized)\n ? normalized\n : undefined;\n}\n\nfunction hasUnsafeDisplayCharacter(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0);\n if (\n codePoint !== undefined &&\n (codePoint <= 0x1f ||\n (codePoint >= 0x7f && codePoint <= 0x9f) ||\n codePoint === 0x061c ||\n codePoint === 0x200e ||\n codePoint === 0x200f ||\n (codePoint >= 0x2028 && codePoint <= 0x202e) ||\n (codePoint >= 0x2066 && codePoint <= 0x2069))\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction safeOwner(value: unknown): string | undefined {\n const parsed = ownerNameSchema.safeParse(value);\n return parsed.success ? parsed.data : undefined;\n}\n\nfunction safeRepository(value: unknown): string | undefined {\n const parsed = repositorySchema.safeParse(value);\n return parsed.success ? parsed.data : undefined;\n}\n\nfunction safePackageLabel(packageName: string): string {\n const safe = safeDisplayValue(packageName, 214);\n return safe ? `\"${safe}\"` : 'this package';\n}\n\nfunction packageCoordinate(context: PublishRequestErrorContext): string {\n const packageName = safeDisplayValue(context.packageName, 214);\n const version = safeDisplayValue(context.packageVersion, 256);\n return packageName && version ? `\"${packageName}@${version}\"` : 'This package version';\n}\n\nfunction scopedOwner(packageName: string): string | undefined {\n const match = safeDisplayValue(packageName, 214)?.match(/^@([^/]+)\\//u);\n return safeOwner(match?.[1]);\n}\n\nfunction credentialKindLabel(kind: PublishRequestErrorContext['credentialKind']): string {\n switch (kind) {\n case 'login':\n return 'CLI login';\n case 'gat':\n return 'Granular access token';\n case 'oidc':\n return 'GitHub Actions trusted publishing';\n }\n}\n\nfunction capabilityLabel(capability: z.output<typeof missingCapabilitiesSchema>[number]): string {\n return capability === 'package.publish' ? 'Publish packages' : 'Submit publishing requests';\n}\n\nfunction oauthScopeLabel(scope: z.output<typeof missingOAuthScopesSchema>[number]): string {\n return scope === 'publishing.request.create' ? 'Submit publishing requests' : 'Read your publishing requests';\n}\n\nfunction accessModeLabel(\n mode: z.output<typeof accessModeSchema> | undefined,\n category: 'package' | 'registry',\n): string | undefined {\n if (!mode) return undefined;\n const noun = category === 'package' ? 'packages' : 'registries';\n switch (mode) {\n case 'none':\n return `No ${noun}`;\n case 'selected':\n return `Selected ${noun}`;\n case 'all':\n return `All ${noun}`;\n }\n}\n\nfunction accessModesLabel(\n modes: readonly ('selected' | 'all')[] | undefined,\n category: 'package' | 'registry',\n): string | undefined {\n if (!modes || modes.length === 0) return undefined;\n const labels = [...new Set(modes)].map((mode) => accessModeLabel(mode, category)).filter(Boolean);\n return labels.join(' or ');\n}\n\nfunction formatDuration(seconds: number): string {\n if (seconds === 1) return '1 second';\n if (seconds < 60) return `${seconds} seconds`;\n if (seconds % 60 === 0) {\n const minutes = seconds / 60;\n return `${minutes} ${minutes === 1 ? 'minute' : 'minutes'}`;\n }\n return `${seconds} seconds`;\n}\n\nfunction quotedList(values: readonly string[]): string {\n const quoted = values.map((value) => `\"${value}\"`);\n if (quoted.length === 1) return quoted[0] as string;\n if (quoted.length === 2) return `${quoted[0]} or ${quoted[1]}`;\n return `${quoted.slice(0, -1).join(', ')}, or ${quoted.at(-1)}`;\n}\n\nfunction fact(kind: PublishDiagnosticFact['kind'], value: string | undefined): PublishDiagnosticFact | undefined {\n return value ? { kind, value } : undefined;\n}\n\nfunction compactFacts(facts: readonly (PublishDiagnosticFact | undefined)[]): PublishDiagnosticFact[] {\n return facts.filter((value): value is PublishDiagnosticFact => value !== undefined);\n}\n\nfunction dedupeFacts(facts: readonly PublishDiagnosticFact[]): PublishDiagnosticFact[] {\n const seen = new Set<string>();\n return facts.filter((factValue) => {\n const key = `${factValue.kind}\\0${factValue.value}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction dedupeResources(resources: readonly PublishDiagnosticResource[]): PublishDiagnosticResource[] {\n const seen = new Set<string>();\n return resources.filter((resource) => {\n const key = resource.kind === 'command' ? `command\\0${resource.command}` : `url\\0${resource.url}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction shellDisplayArgument(value: string): string {\n const safe = safeDisplayValue(value, 100);\n return safe && /^[A-Za-z0-9._-]+$/u.test(safe) ? safe : '<registry>';\n}\n"],"mappings":";;;;;AASA,MAAM,sBAAsB;AAE5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AAiC,oBAAoB,qDAAqD;CAC1G,4BAA4B,oBAAoB,wDAAwD;CAGxG,sBAAsB,UACpB,0EACA,mJACA,CAAC,oBAAoB,CACvB;CACA,2BAA2B,UACzB,qEACA,4GACA,CAAC,oBAAoB,CACvB;CACA,wCAAwC,UACtC,2EACA,6HACA,CAAC,SAAS,oBAAoB,CAChC;CACA,iCAAiC;CACjC,kCAAkC,UAChC,0EACA,iIACA,CAAC,oBAAoB,CACvB;CAGA,sBAAsB,UACpB,2DACA,mIACF;CACA,0BAA0B,UACxB,4EACA,mJACA,CAAC,cAAc,eAAe,CAChC;CACA,iBAAiB,UACf,+DACA,+GACF;CACA,iCAAiC,UAC/B,wDACA,iGACA,CAAC,eAAe,CAClB;CACA,iBAAiB,UACf,sEACA,kIACF;CACA,gCAAgC,UAC9B,sEACA,kIACF;CACA,yBAAyB,UACvB,8DACA,mHACF;CACA,2BAA2B,UACzB,4EACA,qGACF;CACA,qBAAqB,UACnB,kEACA,iHACF;CACA,4BAA4B,UAC1B,yEACA,oFACF;CACA,6BAA6B,UAC3B,0EACA,oHACF;CACA,yBAAyB,UACvB,8DACA,oHACF;CACA,uBAAuB,UACrB,4DACA,oHACF;CACA,iBAAiB,UACf,qFACA,uFACF;CACA,0BAA0B,UACxB,kGACA,gFACF;CACA,wBAAwB,UACtB,iEACA,8FACF;CACA,uBAAuB,UACrB,4DACA,kGACF;CACA,8BAA8B,UAC5B,+DACA,yFACF;CACA,gCAAgC,UAC9B,8DACA,uFACF;CACA,iCAAiC,UAC/B,uEACA,sGACF;CACA,oCAAoC,UAClC,kEACA,iGACF;CACA,kCAAkC,UAChC,sDACA,kGACF;CACA,6CAA6C,UAC3C,2FACA,mHACA,CAAC,YAAY,CACf;CACA,sCAAsC,kBAAkB,wDAAwD;CAChH,6BAA6B,kBAC3B,0EACF;CACA,qBAAqB,kBAAkB,gDAAgD;CACvF,mBAAmB,UACjB,wEACA,+FACF;CACA,wBAAwB,UACtB,0DACA,+FACF;CACA,iCA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TrustResolver.js","names":[],"sources":["../../src/control-plane/RegistryTrustResolver.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { normalizeUrl } from '@uapkg/common';\nimport { getRegistryRepoPath } from '@uapkg/registry-core';\nimport { RegistryMetaSchema } from '@uapkg/registry-schema';\nimport type { CompositionRoot } from '
|
|
1
|
+
{"version":3,"file":"RegistryTrustResolver.js","names":[],"sources":["../../src/control-plane/RegistryTrustResolver.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { normalizeUrl } from '@uapkg/common';\nimport { getRegistryRepoPath } from '@uapkg/registry-core';\nimport { RegistryMetaSchema } from '@uapkg/registry-schema';\nimport type { CompositionRoot } from '#cli/app/CompositionRoot.ts';\nimport {\n type RegistryTrust,\n registryAudience,\n UAPKG_AUTHORIZATION_ISSUER,\n UAPKG_CONTROL_PLANE_API,\n} from '#cli/control-plane/ControlPlaneTypes.ts';\n\nexport class RegistryTrustResolver {\n public constructor(private readonly root: CompositionRoot) {}\n\n public async resolve(requestedAlias?: string): Promise<RegistryTrust> {\n const alias = requestedAlias ?? this.selectedAlias();\n const result = this.root.registryCore.getOrCreateRegistry(alias);\n if (!result.ok) {\n throw new Error(firstDiagnostic(result.diagnostics, `Registry \"${alias}\" is not configured.`));\n }\n\n const registry = result.value;\n const updated = await registry.ensureUpToDate({\n logicalRegistryName: alias,\n bypassFreshnessCheck: true,\n });\n if (!updated.ok || updated.value === 'Failed') {\n throw new Error(firstDiagnostic(updated.diagnostics, `Unable to update registry \"${alias}\".`));\n }\n\n const metadataPath = join(getRegistryRepoPath(registry.shortId), '.uapkg', 'registry.meta.json');\n let raw: string;\n try {\n raw = await readFile(metadataPath, 'utf8');\n } catch (error) {\n throw new Error(\n `Registry \"${alias}\" does not contain .uapkg/registry.meta.json. It cannot be used for authenticated control-plane commands.`,\n { cause: error },\n );\n }\n\n let json: unknown;\n try {\n json = JSON.parse(raw) as unknown;\n } catch (error) {\n throw new Error(`Registry metadata for \"${alias}\" is not valid JSON.`, { cause: error });\n }\n const parsed = RegistryMetaSchema.safeParse(json);\n if (!parsed.success) {\n throw new Error(`Registry metadata for \"${alias}\" does not match the supported schema.`);\n }\n\n const repositoryUrl = canonicalizeRegistryGitOrigin(registry.descriptor.url);\n return {\n alias,\n registryId: parsed.data.registry.id,\n registryName: parsed.data.registry.name,\n repositoryUrl,\n repositoryFingerprint: fingerprintRegistryGitOrigin(repositoryUrl),\n issuer: UAPKG_AUTHORIZATION_ISSUER,\n apiBaseUrl: UAPKG_CONTROL_PLANE_API,\n resource: registryAudience(parsed.data.registry.id),\n cacheShortId: registry.shortId,\n };\n }\n\n public async forceRefresh(trust: RegistryTrust): Promise<void> {\n const result = this.root.registryCore.getOrCreateRegistry(trust.alias);\n if (!result.ok) {\n throw new Error(firstDiagnostic(result.diagnostics, `Registry \"${trust.alias}\" is not configured.`));\n }\n const updated = await result.value.ensureUpToDate({\n logicalRegistryName: trust.alias,\n bypassFreshnessCheck: true,\n });\n if (!updated.ok || updated.value === 'Failed') {\n throw new Error(firstDiagnostic(updated.diagnostics, `Unable to refresh registry \"${trust.alias}\".`));\n }\n }\n\n private selectedAlias(): string {\n const selected = this.root.config.get('registry');\n if (typeof selected !== 'string' || selected.trim().length === 0) {\n throw new Error('No registry is selected. Configure one with `uapkg registry use <name>`.');\n }\n return selected;\n }\n}\n\n/**\n * GitHub accepts HTTPS, SSH URL, and SCP-like clone coordinates for the same\n * repository. Control-plane authorization must bind all three spellings to one\n * stable source identity.\n */\nexport function canonicalizeRegistryGitOrigin(origin: string): string {\n const value = origin.trim();\n const scpLike = /^(?:git@)?github\\.com:([^/\\s]+)\\/([^/\\s]+?)\\/?$/i.exec(value);\n if (scpLike) {\n return canonicalGitHubRepository(scpLike[1], scpLike[2]);\n }\n\n try {\n const parsed = new URL(value);\n if (parsed.hostname.toLowerCase() === 'github.com') {\n const path = parsed.pathname.replace(/^\\/+|\\/+$/g, '').split('/');\n if (path.length !== 2) {\n throw new Error('A GitHub registry origin must identify exactly one owner and repository.');\n }\n return canonicalGitHubRepository(path[0], path[1]);\n }\n } catch (error) {\n if (error instanceof Error && error.message.startsWith('A GitHub registry origin')) {\n throw error;\n }\n }\n\n return normalizeUrl(value);\n}\n\nexport function fingerprintRegistryGitOrigin(origin: string): string {\n const canonical = canonicalizeRegistryGitOrigin(origin);\n return `sha256:${createHash('sha256').update(canonical).digest('hex')}`;\n}\n\nfunction canonicalGitHubRepository(owner: string, repository: string): string {\n const normalizedOwner = owner.trim().toLowerCase();\n const normalizedRepository = repository\n .trim()\n .replace(/\\.git$/i, '')\n .toLowerCase();\n if (!normalizedOwner || !normalizedRepository) {\n throw new Error('A GitHub registry origin must include an owner and repository.');\n }\n return `https://github.com/${normalizedOwner}/${normalizedRepository}.git`;\n}\n\nfunction firstDiagnostic(diagnostics: readonly { readonly message: string }[], fallback: string): string {\n return diagnostics[0]?.message ?? fallback;\n}\n"],"mappings":";;;;;;;;;AAcA,IAAa,wBAAb,MAAmC;CACG;CAApC,AAAO,YAAY,AAAiB,MAAuB;EAAvB;CAAwB;CAE5D,MAAa,QAAQ,gBAAiD;EACpE,MAAM,QAAQ,kBAAkB,KAAK,cAAc;EACnD,MAAM,SAAS,KAAK,KAAK,aAAa,oBAAoB,KAAK;EAC/D,IAAI,CAAC,OAAO,IACV,MAAM,IAAI,MAAM,gBAAgB,OAAO,aAAa,aAAa,MAAM,qBAAqB,CAAC;EAG/F,MAAM,WAAW,OAAO;EACxB,MAAM,UAAU,MAAM,SAAS,eAAe;GAC5C,qBAAqB;GACrB,sBAAsB;EACxB,CAAC;EACD,IAAI,CAAC,QAAQ,MAAM,QAAQ,UAAU,UACnC,MAAM,IAAI,MAAM,gBAAgB,QAAQ,aAAa,8BAA8B,MAAM,GAAG,CAAC;EAG/F,MAAM,eAAe,KAAK,oBAAoB,SAAS,OAAO,GAAG,UAAU,oBAAoB;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OAAO;CACT;AACF;;;;;;AAOA,SAAgB,8BAA8B,QAAwB;CACpE,MAAM,QAAQ,OAAO,KAAK;CAC1B,MAAM,UAAU,mDAAmD,KAAK,KAAK;CAC7E,IAAI,SACF,OAAO,0BAA0B,QAAQ,IAAI,QAAQ,EAAE;CAGzD,IAAI;EACF,MAAM,SAAS,IAAI,IAAI,KAAK;EAC5B,IAAI,OAAO,SAAS,YAAY,MAAM,cAAc;GAClD,MAAM,OAAO,OAAO,SAAS,QAAQ,cAAc,EAAE,CAAC,CAAC,MAAM,GAAG;GAChE,IAAI,KAAK,WAAW,GAClB,MAAM,IAAI,MAAM,0EAA0E;GAE5F,OAAO,0BAA0B,KAAK,IAAI,KAAK,EAAE;EACnD;CACF,SAAS,OAAO;EACd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,WAAW,0BAA0B,GAC/E,MAAM;CAEV;CAEA,OAAO,aAAa,KAAK;AAC3B;AAEA,SAAgB,6BAA6B,QAAwB;CACnE,MAAM,YAAY,8BAA8B,MAAM;CACtD,OAAO,UAAU,WAAW,QAAQ,CAAC,CAAC,OAAO,SAAS,CAAC,CAAC,OAAO,KAAK;AACtE;AAEA,SAAS,0BAA0B,OAAe,YAA4B;CAC5E,MAAM,kBAAkB,MAAM,KAAK,CAAC,CAAC,YAAY;CACjD,MAAM,uBAAuB,WAC1B,KAAK,CAAC,CACN,QAAQ,WAAW,EAAE,CAAC,CACtB,YAAY;CACf,IAAI,CAAC,mBAAmB,CAAC,sBACvB,MAAM,IAAI,MAAM,gEAAgE;CAElF,OAAO,sBAAsB,gBAAgB,GAAG,qBAAqB;AACvE;AAEA,SAAS,gBAAgB,aAAsD,UAA0B;CACvG,OAAO,YAAY,EAAE,EAAE,WAAW;AACpC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"definePostinstall.js","names":[],"sources":["../../../src/postinstall/api/definePostinstall.ts"],"sourcesContent":["import type { PostinstallDefinition } from '
|
|
1
|
+
{"version":3,"file":"definePostinstall.js","names":[],"sources":["../../../src/postinstall/api/definePostinstall.ts"],"sourcesContent":["import type { PostinstallDefinition } from '#cli/postinstall/api/PostinstallDsl.ts';\n\n/**\n * Identity helper used in user-authored `.uapkg/postinstall.ts` files:\n *\n * ```ts\n * import { definePostinstall } from 'uapkg/postinstall';\n * export default definePostinstall({\n * setupModules: { classBody: '...' },\n * });\n * ```\n *\n * At runtime this is the identity function; at edit time it gives authors\n * full TypeScript autocomplete/validation against {@link PostinstallDefinition}.\n * The loader validates the shape regardless of whether the author used this\n * helper, so it is purely ergonomic.\n */\nexport function definePostinstall(definition: PostinstallDefinition): PostinstallDefinition {\n return definition;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,SAAgB,kBAAkB,YAA0D;CAC1F,OAAO;AACT"}
|