-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT

{- | npm mirror upload data, publication, and the first-party upload guard.
The checked mirror upload data keeps publication fields paired with the admitted tarball.
-}
module Ecluse.Core.Registry.Npm.Publish (
    NpmUploadMetadata,
    prepareNpmSource,
    prepareNpmUpload,
    npmPublishCodec,
    publishRequest,
    npmPublishDocument,
    uploadClaims,
    npmNewReleaseOnly,
    npmPublishAllowed,
) where

import Data.Aeson (Value (Object, String), object, (.=))
import Data.Aeson qualified as Aeson
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap (KeyMap)
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Parser (jsonNoDup')
import Data.Attoparsec.ByteString (endOfInput, parseOnly, skipWhile)
import Data.ByteArray.Encoding (Base (Base64), convertToBase)
import Data.ByteString qualified as BS
import Data.Map.Strict qualified as Map
import Data.Text qualified as T

import Lens.Micro ((^?))
import Lens.Micro.Aeson (key, _Object)
import Network.HTTP.Client (Request)

import Ecluse.Core.Credential (ClientCredential)
import Ecluse.Core.Ecosystem (Ecosystem (Npm))
import Ecluse.Core.Package (Artifact (..), HashAlg (SHA1, SRI), PackageDetails (..), PackageInfo (..), PackageName, Scope, hashAlg, hashValue, pkgEcosystem, pkgNamespace, renderPackageName)
import Ecluse.Core.Package.Hash (canonicalHashValue)
import Ecluse.Core.Package.Integrity (assertedAlg, authoritativeDigest)
import Ecluse.Core.Registry (
    FetchFault (FetchUrlUnformable),
    MirrorArtifact (maFilename, maHashes),
    ParseError (ParseError),
    PublishBodyFault (PublishMalformed, PublishUnsupported),
    PublishError (PublishError),
    PublishFault (PublishFetch, PublishRejected, PublishSourceUnavailable),
    UrlFormationError,
    firstHashValue,
    isSuccessStatus,
 )
import Ecluse.Core.Registry.CachedDocument (npmCached)
import Ecluse.Core.Registry.JsonStream (isJsonSpace)
import Ecluse.Core.Registry.Metadata (VersionDoc (vdRaw))
import Ecluse.Core.Registry.Metadata.Fetch.Preparation (presentedRead)
import Ecluse.Core.Registry.MirrorUpload
import Ecluse.Core.Registry.MirrorUpload.Internal (checkedMirrorUploadData)
import Ecluse.Core.Registry.Npm.Credential (npmCredential)
import Ecluse.Core.Registry.Npm.DependencySource (externalDependencyOf, renderExternalDependency)
import Ecluse.Core.Registry.Npm.Metadata (npmChargeFactors, prepareNpmRead)
import Ecluse.Core.Registry.Npm.Project qualified as Project
import Ecluse.Core.Registry.Npm.Request (MetadataForm (Abbreviated), jsonPutRequest, metadataRequest, packageUrl)
import Ecluse.Core.Registry.Npm.VersionListReader (npmVersionListWalk)
import Ecluse.Core.Registry.Publish (PublishCodec (..), PublishPlan (ppLatest))
import Ecluse.Core.Registry.Request (CredentialMapping, ServicePresentation, StoreOperation (StoreRead, StoreWrite), presentedMapping, presentedRequest)
import Ecluse.Core.Registry.ServedDocument (objectField)
import Ecluse.Core.Registry.VersionList (collectVersionList, emptyVersionList)
import Ecluse.Core.Server.Admission.Types (ChargeFactors (cfFullReadPermille))
import Ecluse.Core.Server.Path (unFilename)
import Ecluse.Core.Version (Version, renderVersion)

-- | Original source fields bind the publication metadata to its admitted snapshot.
newtype NpmUploadMetadata = NpmUploadMetadata (KeyMap Value)
    deriving stock (NpmUploadMetadata -> NpmUploadMetadata -> Bool
(NpmUploadMetadata -> NpmUploadMetadata -> Bool)
-> (NpmUploadMetadata -> NpmUploadMetadata -> Bool)
-> Eq NpmUploadMetadata
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: NpmUploadMetadata -> NpmUploadMetadata -> Bool
== :: NpmUploadMetadata -> NpmUploadMetadata -> Bool
$c/= :: NpmUploadMetadata -> NpmUploadMetadata -> Bool
/= :: NpmUploadMetadata -> NpmUploadMetadata -> Bool
Eq, Int -> NpmUploadMetadata -> ShowS
[NpmUploadMetadata] -> ShowS
NpmUploadMetadata -> String
(Int -> NpmUploadMetadata -> ShowS)
-> (NpmUploadMetadata -> String)
-> ([NpmUploadMetadata] -> ShowS)
-> Show NpmUploadMetadata
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> NpmUploadMetadata -> ShowS
showsPrec :: Int -> NpmUploadMetadata -> ShowS
$cshow :: NpmUploadMetadata -> String
show :: NpmUploadMetadata -> String
$cshowList :: [NpmUploadMetadata] -> ShowS
showList :: [NpmUploadMetadata] -> ShowS
Show)

-- | Preserve the paired source fields and refuse an npm inventory with more than one physical tarball.
prepareNpmSource :: PackageName -> Version -> VersionDoc -> Either PublishFault (MirrorInventory, NpmUploadMetadata)
prepareNpmSource :: PackageName
-> Version
-> VersionDoc
-> Either PublishFault (MirrorInventory, NpmUploadMetadata)
prepareNpmSource PackageName
name Version
version VersionDoc
doc = do
    Bool -> Either PublishFault () -> Either PublishFault ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (PackageName -> Ecosystem
pkgEcosystem PackageName
name Ecosystem -> Ecosystem -> Bool
forall a. Eq a => a -> a -> Bool
== Ecosystem
Npm) (PublishFault -> Either PublishFault ()
forall a b. a -> Either a b
Left (Text -> PublishFault
PublishSourceUnavailable Text
"the mirror snapshot is not npm"))
    raw <- PublishFault -> Maybe CachedDoc -> Either PublishFault CachedDoc
forall l r. l -> Maybe r -> Either l r
maybeToRight (Text -> PublishFault
PublishSourceUnavailable Text
"the resolver carried no source version object") (VersionDoc -> Maybe CachedDoc
vdRaw VersionDoc
doc)
    fields <- case snd npmCached raw of
        Just (Object KeyMap Value
objectFields) -> KeyMap Value -> Either PublishFault (KeyMap Value)
forall a b. b -> Either a b
Right KeyMap Value
objectFields
        Maybe Value
_ -> PublishFault -> Either PublishFault (KeyMap Value)
forall a b. a -> Either a b
Left (Text -> PublishFault
PublishSourceUnavailable Text
"the source version object is not an npm object")
    inventory <- checkedMirrorInventory name version doc (NpmMirrorRead fields)
    case inventoryFiles inventory of
        ExpectedMirrorFile
_ :| [] -> () -> Either PublishFault ()
forall a. a -> Either PublishFault a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        NonEmpty ExpectedMirrorFile
_ -> PublishFault -> Either PublishFault ()
forall a b. a -> Either a b
Left (Text -> PublishFault
PublishSourceUnavailable Text
"the npm inventory contains more than one physical tarball")
    pure (inventory, NpmUploadMetadata fields)

-- | Bind npm source fields to this verified member of the complete version inventory.
prepareNpmUpload :: MirrorInventory -> NpmUploadMetadata -> ExpectedMirrorFile -> VerifiedArtifactBytes -> Either PublishFault (MirrorUploadData NpmUploadMetadata)
prepareNpmUpload :: MirrorInventory
-> NpmUploadMetadata
-> ExpectedMirrorFile
-> VerifiedArtifactBytes
-> Either PublishFault (MirrorUploadData NpmUploadMetadata)
prepareNpmUpload MirrorInventory
inventory metadata :: NpmUploadMetadata
metadata@(NpmUploadMetadata KeyMap Value
fields) ExpectedMirrorFile
file VerifiedArtifactBytes
verified = do
    Bool -> Either PublishFault () -> Either PublishFault ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (MirrorInventory -> MirrorReadData
inventoryReadData MirrorInventory
inventory MirrorReadData -> MirrorReadData -> Bool
forall a. Eq a => a -> a -> Bool
== KeyMap Value -> MirrorReadData
NpmMirrorRead KeyMap Value
fields) (Either PublishFault () -> Either PublishFault ())
-> Either PublishFault () -> Either PublishFault ()
forall a b. (a -> b) -> a -> b
$
        PublishFault -> Either PublishFault ()
forall a b. a -> Either a b
Left (Text -> PublishFault
PublishSourceUnavailable Text
"npm upload fields belong to another source snapshot")
    MirrorInventory
-> ExpectedMirrorFile
-> VerifiedArtifactBytes
-> NpmUploadMetadata
-> Either PublishFault (MirrorUploadData NpmUploadMetadata)
forall metadata.
MirrorInventory
-> ExpectedMirrorFile
-> VerifiedArtifactBytes
-> metadata
-> Either PublishFault (MirrorUploadData metadata)
checkedMirrorUploadData MirrorInventory
inventory ExpectedMirrorFile
file VerifiedArtifactBytes
verified NpmUploadMetadata
metadata

-- | npm uses its ordinary bounded metadata reader and one immutable tarball upload per version.
npmPublishCodec :: ServicePresentation -> PublishCodec
npmPublishCodec :: ServicePresentation -> PublishCodec
npmPublishCodec ServicePresentation
presentation =
    PublishCodec
        { pcPrepareSource :: PackageName
-> Version
-> VersionDoc
-> Either PublishFault (MirrorInventory, NpmUploadMetadata)
pcPrepareSource = PackageName
-> Version
-> VersionDoc
-> Either PublishFault (MirrorInventory, NpmUploadMetadata)
prepareNpmSource
        , pcPrepareUpload :: Deadlines
-> Limits
-> (Int -> IO ())
-> MirrorInventory
-> NpmUploadMetadata
-> ExpectedMirrorFile
-> VerifiedArtifactBytes
-> IO (Either PublishFault (MirrorUploadData NpmUploadMetadata))
pcPrepareUpload = \Deadlines
_ Limits
_ Int -> IO ()
_ MirrorInventory
inventory NpmUploadMetadata
metadata ExpectedMirrorFile
file VerifiedArtifactBytes
bytes -> Either PublishFault (MirrorUploadData NpmUploadMetadata)
-> IO (Either PublishFault (MirrorUploadData NpmUploadMetadata))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MirrorInventory
-> NpmUploadMetadata
-> ExpectedMirrorFile
-> VerifiedArtifactBytes
-> Either PublishFault (MirrorUploadData NpmUploadMetadata)
prepareNpmUpload MirrorInventory
inventory NpmUploadMetadata
metadata ExpectedMirrorFile
file VerifiedArtifactBytes
bytes)
        , pcMirrorCompanion :: Maybe MirrorCompanion
pcMirrorCompanion = Maybe MirrorCompanion
forall a. Maybe a
Nothing
        , pcNativeComplete :: PackageName -> Version -> PackageInfo -> Bool
pcNativeComplete = PackageName -> Version -> PackageInfo -> Bool
nativeNpmComplete
        , pcTargetRead :: PrepareRead
pcTargetRead = CredentialMapping -> PrepareRead -> PrepareRead
presentedRead CredentialMapping
readAs PrepareRead
prepareNpmRead
        , pcTargetReadPermille :: Int
pcTargetReadPermille = ChargeFactors -> Int
cfFullReadPermille ChargeFactors
npmChargeFactors
        , pcProbeRequest :: Text
-> Maybe ClientCredential
-> PackageName
-> Either UrlFormationError Request
pcProbeRequest = \Text
targetUrl Maybe ClientCredential
credential PackageName
name -> CredentialMapping
-> Maybe ClientCredential
-> (Maybe ClientCredential -> Either UrlFormationError Request)
-> Either UrlFormationError Request
forall e.
CredentialMapping
-> Maybe ClientCredential
-> (Maybe ClientCredential -> Either e Request)
-> Either e Request
presentedRequest CredentialMapping
readAs Maybe ClientCredential
credential (\Maybe ClientCredential
anonymous -> Text
-> Maybe ClientCredential
-> MetadataForm
-> PackageName
-> Either UrlFormationError Request
metadataRequest Text
targetUrl Maybe ClientCredential
anonymous MetadataForm
Abbreviated PackageName
name)
        , pcVersionListWalk :: Maybe (Limits -> Cursor -> Step VersionListState)
pcVersionListWalk = (Limits -> Cursor -> Step VersionListState)
-> Maybe (Limits -> Cursor -> Step VersionListState)
forall a. a -> Maybe a
Just (\Limits
limits -> Limits
-> (VersionListState
    -> VersionListItem -> Either LimitError VersionListState)
-> VersionListState
-> Cursor
-> Step VersionListState
forall s.
Limits
-> (s -> VersionListItem -> Either LimitError s)
-> s
-> Cursor
-> Step s
npmVersionListWalk Limits
limits (Limits
-> VersionListState
-> VersionListItem
-> Either LimitError VersionListState
collectVersionList Limits
limits) VersionListState
emptyVersionList)
        , pcPrepareTarget :: OriginClient
-> RegistryUrl -> IO (Either MetadataError RegistryUrl)
pcPrepareTarget = \OriginClient
_ RegistryUrl
target -> Either MetadataError RegistryUrl
-> IO (Either MetadataError RegistryUrl)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (RegistryUrl -> Either MetadataError RegistryUrl
forall a b. b -> Either a b
Right RegistryUrl
target)
        , pcPublishRequest :: Text
-> Maybe ClientCredential
-> PublishPlan
-> MirrorUploadData NpmUploadMetadata
-> Either PublishFault Request
pcPublishRequest = CredentialMapping
-> Text
-> Maybe ClientCredential
-> PublishPlan
-> MirrorUploadData NpmUploadMetadata
-> Either PublishFault Request
npmPublishRequestFor (ServicePresentation
-> StoreOperation -> CredentialMapping -> CredentialMapping
presentedMapping ServicePresentation
presentation StoreOperation
StoreWrite CredentialMapping
npmCredential)
        , pcPublishOutcome :: Int -> ByteString -> Either PublishFault ()
pcPublishOutcome = \Int
status ByteString
_ -> Int -> Either PublishFault ()
classifyPublish Int
status
        }
  where
    readAs :: CredentialMapping
readAs = ServicePresentation
-> StoreOperation -> CredentialMapping -> CredentialMapping
presentedMapping ServicePresentation
presentation StoreOperation
StoreRead CredentialMapping
npmCredential

nativeNpmComplete :: PackageName -> Version -> PackageInfo -> Bool
nativeNpmComplete :: PackageName -> Version -> PackageInfo -> Bool
nativeNpmComplete PackageName
name Version
version PackageInfo
info = Bool -> Maybe Bool -> Bool
forall a. a -> Maybe a -> a
fromMaybe Bool
False (Maybe Bool -> Bool) -> Maybe Bool -> Bool
forall a b. (a -> b) -> a -> b
$ do
    Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (PackageName -> Ecosystem
pkgEcosystem PackageName
name Ecosystem -> Ecosystem -> Bool
forall a. Eq a => a -> a -> Bool
== Ecosystem
Npm Bool -> Bool -> Bool
&& PackageInfo -> PackageName
infoName PackageInfo
info PackageName -> PackageName -> Bool
forall a. Eq a => a -> a -> Bool
== PackageName
name)
    details <- Text -> Map Text PackageDetails -> Maybe PackageDetails
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (Version -> Text
renderVersion Version
version) (PackageInfo -> Map Text PackageDetails
infoVersions PackageInfo
info)
    guard (pkgName details == name && renderVersion (pkgVersion details) == renderVersion version)
    case pkgArtifacts details of
        Artifact
artifact :| [] -> do
            (fileVersion, _) <- PackageName -> Text -> Maybe (Version, Filename)
Project.tarballCoordinate PackageName
name (Artifact -> Text
artFilename Artifact
artifact)
            guard (renderVersion fileVersion == renderVersion version && maybe True (>= 0) (artSize artifact))
            hashes <- nonEmpty (artHashes artifact)
            pure (all (isJust . canonicalHashValue) hashes && isJust (canonicalHashValue (authoritativeDigest hashes)))
        NonEmpty Artifact
_ -> Maybe Bool
forall a. Maybe a
Nothing

npmPublishRequestFor :: CredentialMapping -> Text -> Maybe ClientCredential -> PublishPlan -> MirrorUploadData NpmUploadMetadata -> Either PublishFault Request
npmPublishRequestFor :: CredentialMapping
-> Text
-> Maybe ClientCredential
-> PublishPlan
-> MirrorUploadData NpmUploadMetadata
-> Either PublishFault Request
npmPublishRequestFor CredentialMapping
writeAs Text
targetUrl Maybe ClientCredential
credential PublishPlan
plan MirrorUploadData NpmUploadMetadata
uploadData =
    (UrlFormationError -> PublishFault)
-> Either UrlFormationError Request -> Either PublishFault Request
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (FetchFault -> PublishFault
PublishFetch (FetchFault -> PublishFault)
-> (UrlFormationError -> FetchFault)
-> UrlFormationError
-> PublishFault
forall b c a. (b -> c) -> (a -> b) -> a -> c
. UrlFormationError -> FetchFault
FetchUrlUnformable) (Either UrlFormationError Request -> Either PublishFault Request)
-> ((Maybe ClientCredential -> Either UrlFormationError Request)
    -> Either UrlFormationError Request)
-> (Maybe ClientCredential -> Either UrlFormationError Request)
-> Either PublishFault Request
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CredentialMapping
-> Maybe ClientCredential
-> (Maybe ClientCredential -> Either UrlFormationError Request)
-> Either UrlFormationError Request
forall e.
CredentialMapping
-> Maybe ClientCredential
-> (Maybe ClientCredential -> Either e Request)
-> Either e Request
presentedRequest CredentialMapping
writeAs Maybe ClientCredential
credential ((Maybe ClientCredential -> Either UrlFormationError Request)
 -> Either PublishFault Request)
-> (Maybe ClientCredential -> Either UrlFormationError Request)
-> Either PublishFault Request
forall a b. (a -> b) -> a -> b
$ \Maybe ClientCredential
anonymous ->
        Text
-> Maybe ClientCredential
-> PackageName
-> ByteString
-> Either UrlFormationError Request
publishRequest Text
targetUrl Maybe ClientCredential
anonymous (MirrorInventory -> PackageName
inventoryPackage (MirrorUploadData NpmUploadMetadata -> MirrorInventory
forall metadata. MirrorUploadData metadata -> MirrorInventory
uploadInventory MirrorUploadData NpmUploadMetadata
uploadData)) (PublishPlan -> MirrorUploadData NpmUploadMetadata -> ByteString
npmPublishDocument PublishPlan
plan MirrorUploadData NpmUploadMetadata
uploadData)

strongestSriValue :: MirrorArtifact -> Maybe Text
strongestSriValue :: MirrorArtifact -> Maybe Text
strongestSriValue MirrorArtifact
artifact = do
    hashes <- [Hash] -> Maybe (NonEmpty Hash)
forall a. [a] -> Maybe (NonEmpty a)
nonEmpty ((Hash -> Bool) -> [Hash] -> [Hash]
forall a. (a -> Bool) -> [a] -> [a]
filter ((HashAlg -> HashAlg -> Bool
forall a. Eq a => a -> a -> Bool
== HashAlg
SRI) (HashAlg -> Bool) -> (Hash -> HashAlg) -> Hash -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Hash -> HashAlg
hashAlg) (NonEmpty Hash -> [Hash]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (MirrorArtifact -> NonEmpty Hash
maHashes MirrorArtifact
artifact)))
    let strongestAlg = Hash -> Maybe HashAlg
assertedAlg (NonEmpty Hash -> Hash
authoritativeDigest NonEmpty Hash
hashes)
    pure (T.unwords [hashValue h | h <- toList hashes, assertedAlg h == strongestAlg])

classifyPublish :: Int -> Either PublishFault ()
classifyPublish :: Int -> Either PublishFault ()
classifyPublish Int
code
    | Int -> Bool
isSuccessStatus Int
code = () -> Either PublishFault ()
forall a b. b -> Either a b
Right ()
    | Int
code Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
409 = () -> Either PublishFault ()
forall a b. b -> Either a b
Right () -- version already present, immutable, so success-equivalent
    | Bool
otherwise =
        PublishFault -> Either PublishFault ()
forall a b. a -> Either a b
Left (PublishError -> PublishFault
PublishRejected (Text -> PublishError
PublishError (Text
"publish failed with HTTP status " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Int -> Text
forall b a. (Show a, IsString b) => a -> b
show Int
code)))

-- | Build the publish request with its credential, failing when the URL cannot be formed.
publishRequest ::
    Text ->
    Maybe ClientCredential ->
    PackageName ->
    ByteString ->
    Either UrlFormationError Request
publishRequest :: Text
-> Maybe ClientCredential
-> PackageName
-> ByteString
-> Either UrlFormationError Request
publishRequest Text
baseUrl Maybe ClientCredential
credential PackageName
name ByteString
document = do
    url <- Text -> PackageName -> Either UrlFormationError Text
packageUrl Text
baseUrl PackageName
name
    jsonPutRequest credential url document

-- | Preserve source metadata fields while replacing identity, attachment controls, and verified distribution facts.
npmPublishDocument :: PublishPlan -> MirrorUploadData NpmUploadMetadata -> ByteString
npmPublishDocument :: PublishPlan -> MirrorUploadData NpmUploadMetadata -> ByteString
npmPublishDocument PublishPlan
plan MirrorUploadData NpmUploadMetadata
uploadData =
    ByteString -> ByteString
forall l s. LazyStrict l s => l -> s
toStrict (ByteString -> ByteString)
-> (Value -> ByteString) -> Value -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Value -> ByteString
forall a. ToJSON a => a -> ByteString
Aeson.encode (Value -> ByteString) -> Value -> ByteString
forall a b. (a -> b) -> a -> b
$
        [Pair] -> Value
object
            [ Key
"_id" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Text
rendered
            , Key
"name" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Text
rendered
            , Key
"dist-tags" Key -> Value -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [Pair] -> Value
object [Key
"latest" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Version -> Text
renderVersion (PublishPlan -> Version
ppLatest PublishPlan
plan)]
            , Key
"versions" Key -> Value -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [Pair] -> Value
object [Text -> Key
Key.fromText Text
versionText Key -> Value -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Value
manifest]
            , Key
"_attachments" Key -> Value -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= [Pair] -> Value
object [Text -> Key
Key.fromText Text
filename Key -> Value -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= ByteString -> Value
attachmentObject ByteString
tarball]
            ]
  where
    artifact :: MirrorArtifact
artifact = ExpectedMirrorFile -> MirrorArtifact
expectedDescriptor (MirrorUploadData NpmUploadMetadata -> ExpectedMirrorFile
forall metadata. MirrorUploadData metadata -> ExpectedMirrorFile
uploadFile MirrorUploadData NpmUploadMetadata
uploadData)
    tarball :: ByteString
tarball = MirrorUploadData NpmUploadMetadata -> ByteString
forall metadata. MirrorUploadData metadata -> ByteString
uploadBytes MirrorUploadData NpmUploadMetadata
uploadData
    filename :: Text
filename = Filename -> Text
unFilename (MirrorArtifact -> Filename
maFilename MirrorArtifact
artifact)
    NpmUploadMetadata KeyMap Value
fields = MirrorUploadData NpmUploadMetadata -> NpmUploadMetadata
forall metadata. MirrorUploadData metadata -> metadata
uploadMetadata MirrorUploadData NpmUploadMetadata
uploadData
    authored :: KeyMap Value
authored = KeyMap Value -> KeyMap Value
authoredFields KeyMap Value
fields
    dist :: Value
dist = Text -> Maybe Text -> Maybe Text -> KeyMap Value -> Value
distObject Text
filename (MirrorArtifact -> Maybe Text
strongestSriValue MirrorArtifact
artifact) (HashAlg -> MirrorArtifact -> Maybe Text
firstHashValue HashAlg
SHA1 MirrorArtifact
artifact) (KeyMap Value -> Maybe (KeyMap Value) -> KeyMap Value
forall a. a -> Maybe a -> a
fromMaybe KeyMap Value
forall a. Monoid a => a
mempty (Key -> KeyMap Value -> Maybe (KeyMap Value)
objectField Key
"dist" KeyMap Value
authored))
    manifest :: Value
manifest = Text -> Text -> Value -> KeyMap Value -> Value
versionManifestObject Text
rendered Text
versionText Value
dist KeyMap Value
authored
    versionText :: Text
versionText = Version -> Text
renderVersion (MirrorInventory -> Version
inventoryVersion (MirrorUploadData NpmUploadMetadata -> MirrorInventory
forall metadata. MirrorUploadData metadata -> MirrorInventory
uploadInventory MirrorUploadData NpmUploadMetadata
uploadData))
    rendered :: Text
rendered = PackageName -> Text
renderPackageName (MirrorInventory -> PackageName
inventoryPackage (MirrorUploadData NpmUploadMetadata -> MirrorInventory
forall metadata. MirrorUploadData metadata -> MirrorInventory
uploadInventory MirrorUploadData NpmUploadMetadata
uploadData))

-- Keep the shrinkwrap installation marker, but drop the source registry's bookkeeping.
authoredFields :: KeyMap Value -> KeyMap Value
authoredFields :: KeyMap Value -> KeyMap Value
authoredFields = (Key -> Value -> Bool) -> KeyMap Value -> KeyMap Value
forall v. (Key -> v -> Bool) -> KeyMap v -> KeyMap v
KeyMap.filterWithKey (\Key
keyName Value
_ -> Key
keyName Key -> Key -> Bool
forall a. Eq a => a -> a -> Bool
== Key
"_hasShrinkwrap" Bool -> Bool -> Bool
|| Bool -> Bool
not (Text -> Text -> Bool
T.isPrefixOf Text
"_" (Key -> Text
Key.toText Key
keyName)))

-- 'KeyMap.union' is left-biased, so the local authority fields win over the authored ones.
versionManifestObject :: Text -> Text -> Aeson.Value -> KeyMap Value -> Aeson.Value
versionManifestObject :: Text -> Text -> Value -> KeyMap Value -> Value
versionManifestObject Text
rendered Text
versionText Value
dist KeyMap Value
authored =
    KeyMap Value -> Value
Object ([Pair] -> KeyMap Value
forall v. [(Key, v)] -> KeyMap v
KeyMap.fromList [(Key
"name", Text -> Value
String Text
rendered), (Key
"version", Text -> Value
String Text
versionText), (Key
"dist", Value
dist)] KeyMap Value -> KeyMap Value -> KeyMap Value
forall v. KeyMap v -> KeyMap v -> KeyMap v
`KeyMap.union` KeyMap Value
authored)

{- The verified location and digests replace the source's, and an unverified source digest never
survives their absence. Signatures and attestations reference the public registry's own keys. -}
distObject :: Text -> Maybe Text -> Maybe Text -> KeyMap Value -> Aeson.Value
distObject :: Text -> Maybe Text -> Maybe Text -> KeyMap Value -> Value
distObject Text
filename Maybe Text
integrity Maybe Text
shasum KeyMap Value
authored =
    KeyMap Value -> Value
Object (KeyMap Value
verified KeyMap Value -> KeyMap Value -> KeyMap Value
forall v. KeyMap v -> KeyMap v -> KeyMap v
`KeyMap.union` (Key -> Value -> Bool) -> KeyMap Value -> KeyMap Value
forall v. (Key -> v -> Bool) -> KeyMap v -> KeyMap v
KeyMap.filterWithKey (\Key
k Value
_ -> Key
k Key -> [Key] -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`notElem` [Key]
registryDistKeys) KeyMap Value
authored)
  where
    verified :: KeyMap Value
verified =
        [Pair] -> KeyMap Value
forall v. [(Key, v)] -> KeyMap v
KeyMap.fromList
            ( (Key
"tarball", Text -> Value
String Text
filename)
                Pair -> [Pair] -> [Pair]
forall a. a -> [a] -> [a]
: [Pair] -> (Text -> [Pair]) -> Maybe Text -> [Pair]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (\Text
i -> [(Key
"integrity", Text -> Value
String Text
i)]) Maybe Text
integrity
                    [Pair] -> [Pair] -> [Pair]
forall a. Semigroup a => a -> a -> a
<> [Pair] -> (Text -> [Pair]) -> Maybe Text -> [Pair]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (\Text
s -> [(Key
"shasum", Text -> Value
String Text
s)]) Maybe Text
shasum
            )

registryDistKeys :: [Key.Key]
registryDistKeys :: [Key]
registryDistKeys = [Key
"tarball", Key
"integrity", Key
"shasum", Key
"signatures", Key
"attestations"]

attachmentObject :: ByteString -> Aeson.Value
attachmentObject :: ByteString -> Value
attachmentObject ByteString
tarball =
    [Pair] -> Value
object
        [ Key
"content_type" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= (Text
"application/octet-stream" :: Text)
        , Key
"data" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Text
encodedTarball
        , Key
"length" Key -> Int -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= ByteString -> Int
BS.length ByteString
tarball
        ]
  where
    encodedTarball :: Text
    encodedTarball :: Text
encodedTarball = ByteString -> Text
forall a b. ConvertUtf8 a b => b -> a
decodeUtf8 (Base -> ByteString -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
Base -> bin -> bout
convertToBase Base
Base64 ByteString
tarball :: ByteString)

{- | The declared names of a new-release document, which never reads the attachment data beyond the JSON parse.
A dependency a consumer's install would fetch from outside this proxy refuses the release.
-}
uploadClaims :: ByteString -> Either PublishBodyFault [Text]
uploadClaims :: ByteString -> Either PublishBodyFault [Text]
uploadClaims ByteString
body = case Parser Value -> ByteString -> Either String Value
forall a. Parser a -> ByteString -> Either String a
parseOnly (Parser Value
jsonNoDup' Parser Value -> Parser ByteString () -> Parser Value
forall a b.
Parser ByteString a -> Parser ByteString b -> Parser ByteString a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* (Word8 -> Bool) -> Parser ByteString ()
skipWhile Word8 -> Bool
isJsonSpace Parser Value -> Parser ByteString () -> Parser Value
forall a b.
Parser ByteString a -> Parser ByteString b -> Parser ByteString a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Parser ByteString ()
forall t. Chunk t => Parser t ()
endOfInput) ByteString
body of
    Right document :: Value
document@(Object KeyMap Value
fields)
        | Bool -> Bool
not (KeyMap Value -> Bool
isNewRelease KeyMap Value
fields) -> PublishBodyFault -> Either PublishBodyFault [Text]
forall a b. a -> Either a b
Left (Text -> PublishBodyFault
PublishUnsupported Text
npmNewReleaseOnly)
        | Bool -> Bool
not (KeyMap Value -> Bool
keyMatchesVersion KeyMap Value
fields) -> PublishBodyFault -> Either PublishBodyFault [Text]
forall a b. a -> Either a b
Left (ParseError -> PublishBodyFault
PublishMalformed (Text -> ParseError
ParseError Text
"the publish body's version document must be an object whose version field equals its key"))
        | Just (Key
_, Object KeyMap Value
release) <- KeyMap Value -> Maybe Pair
singleVersion KeyMap Value
fields
        , Just ExternalDependency
dependency <- KeyMap Value -> Maybe ExternalDependency
externalDependencyOf KeyMap Value
release ->
            PublishBodyFault -> Either PublishBodyFault [Text]
forall a b. a -> Either a b
Left (ParseError -> PublishBodyFault
PublishMalformed (Text -> ParseError
ParseError (Text
"the publish body's " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> ExternalDependency -> Text
renderExternalDependency ExternalDependency
dependency Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
", which a client would fetch from outside this proxy: depend on a version this proxy serves")))
        | Bool
otherwise -> [Text] -> Either PublishBodyFault [Text]
forall a b. b -> Either a b
Right (Value -> [Text]
declaredNames Value
document)
    Either String Value
_ -> PublishBodyFault -> Either PublishBodyFault [Text]
forall a b. a -> Either a b
Left (ParseError -> PublishBodyFault
PublishMalformed (Text -> ParseError
ParseError Text
"the publish body is not a JSON object without repeated keys"))

-- | The @501@ reason for a write that is not a new release, such as @npm deprecate@ or @npm star@.
npmNewReleaseOnly :: Text
npmNewReleaseOnly :: Text
npmNewReleaseOnly = Text
"this proxy relays new-release publish documents only: change an existing package's metadata, such as a deprecation, at the publication target"

-- One version and a non-empty @_attachments@, with every tag on that version, so a tag can name only the new version.
isNewRelease :: KeyMap Value -> Bool
isNewRelease :: KeyMap Value -> Bool
isNewRelease KeyMap Value
fields = case (Key -> KeyMap Value -> Maybe Value
forall v. Key -> KeyMap v -> Maybe v
KeyMap.lookup Key
"_attachments" KeyMap Value
fields, KeyMap Value -> Maybe Pair
singleVersion KeyMap Value
fields) of
    (Just (Object KeyMap Value
attachments), Just (Key
version, Value
_)) -> Bool -> Bool
not (KeyMap Value -> Bool
forall v. KeyMap v -> Bool
KeyMap.null KeyMap Value
attachments) Bool -> Bool -> Bool
&& Key -> Maybe Value -> Bool
tagsOnly Key
version (Key -> KeyMap Value -> Maybe Value
forall v. Key -> KeyMap v -> Maybe v
KeyMap.lookup Key
"dist-tags" KeyMap Value
fields)
    (Maybe Value, Maybe Pair)
_ -> Bool
False

-- The key equals the document's own version field, so a store that reads either sees one version.
keyMatchesVersion :: KeyMap Value -> Bool
keyMatchesVersion :: KeyMap Value -> Bool
keyMatchesVersion KeyMap Value
fields = case KeyMap Value -> Maybe Pair
singleVersion KeyMap Value
fields of
    Just (Key
version, Object KeyMap Value
document) -> Key -> KeyMap Value -> Maybe Value
forall v. Key -> KeyMap v -> Maybe v
KeyMap.lookup Key
"version" KeyMap Value
document Maybe Value -> Maybe Value -> Bool
forall a. Eq a => a -> a -> Bool
== Value -> Maybe Value
forall a. a -> Maybe a
Just (Text -> Value
String (Key -> Text
Key.toText Key
version))
    Maybe Pair
_ -> Bool
False

singleVersion :: KeyMap Value -> Maybe (Key.Key, Value)
singleVersion :: KeyMap Value -> Maybe Pair
singleVersion KeyMap Value
fields = case Key -> KeyMap Value -> Maybe Value
forall v. Key -> KeyMap v -> Maybe v
KeyMap.lookup Key
"versions" KeyMap Value
fields of
    Just (Object KeyMap Value
versions) | [Pair
entry] <- KeyMap Value -> [Pair]
forall v. KeyMap v -> [(Key, v)]
KeyMap.toList KeyMap Value
versions -> Pair -> Maybe Pair
forall a. a -> Maybe a
Just Pair
entry
    Maybe Value
_ -> Maybe Pair
forall a. Maybe a
Nothing

tagsOnly :: Key.Key -> Maybe Value -> Bool
tagsOnly :: Key -> Maybe Value -> Bool
tagsOnly Key
version = \case
    Maybe Value
Nothing -> Bool
True
    Just (Object KeyMap Value
tags) -> (Value -> Bool) -> KeyMap Value -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Value -> Value -> Bool
forall a. Eq a => a -> a -> Bool
== Text -> Value
String (Key -> Text
Key.toText Key
version)) KeyMap Value
tags
    Just Value
_ -> Bool
False

-- @_id@, @name@ and each version's name, which the anti-shadowing guard compares with the path name.
declaredNames :: Value -> [Text]
declaredNames :: Value -> [Text]
declaredNames Value
document =
    [ Text
declared
    | Maybe Value
slot <-
        [Value
document Value -> Getting (First Value) Value Value -> Maybe Value
forall s a. s -> Getting (First a) s a -> Maybe a
^? Key -> Traversal' Value Value
forall t. AsValue t => Key -> Traversal' t Value
key Key
"_id", Value
document Value -> Getting (First Value) Value Value -> Maybe Value
forall s a. s -> Getting (First a) s a -> Maybe a
^? Key -> Traversal' Value Value
forall t. AsValue t => Key -> Traversal' t Value
key Key
"name"]
            [Maybe Value] -> [Maybe Value] -> [Maybe Value]
forall a. Semigroup a => a -> a -> a
<> [ Value
versionDoc Value -> Getting (First Value) Value Value -> Maybe Value
forall s a. s -> Getting (First a) s a -> Maybe a
^? Key -> Traversal' Value Value
forall t. AsValue t => Key -> Traversal' t Value
key Key
"name"
               | KeyMap Value
versions <- Maybe (KeyMap Value) -> [KeyMap Value]
forall a. Maybe a -> [a]
maybeToList (Value
document Value
-> Getting (First (KeyMap Value)) Value (KeyMap Value)
-> Maybe (KeyMap Value)
forall s a. s -> Getting (First a) s a -> Maybe a
^? Key -> Traversal' Value Value
forall t. AsValue t => Key -> Traversal' t Value
key Key
"versions" ((Value -> Const (First (KeyMap Value)) Value)
 -> Value -> Const (First (KeyMap Value)) Value)
-> Getting (First (KeyMap Value)) Value (KeyMap Value)
-> Getting (First (KeyMap Value)) Value (KeyMap Value)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Getting (First (KeyMap Value)) Value (KeyMap Value)
forall t. AsValue t => Traversal' t (KeyMap Value)
Traversal' Value (KeyMap Value)
_Object)
               , Value
versionDoc <- KeyMap Value -> [Value]
forall v. KeyMap v -> [v]
KeyMap.elems KeyMap Value
versions
               ]
    , Just (String Text
declared) <- [Maybe Value
slot]
    ]

-- | Require an exact configured scope, refusing unscoped names and scope prefixes.
npmPublishAllowed :: [Scope] -> PackageName -> Bool
npmPublishAllowed :: [Scope] -> PackageName -> Bool
npmPublishAllowed [Scope]
scopes PackageName
name = case PackageName -> Maybe Scope
pkgNamespace PackageName
name of
    Just Scope
scope -> Scope
scope Scope -> [Scope] -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [Scope]
scopes
    Maybe Scope
Nothing -> Bool
False