diff --git a/.ado/publish.yml b/.ado/publish.yml index 71406cfa8f3..32102a2c377 100644 --- a/.ado/publish.yml +++ b/.ado/publish.yml @@ -1,10 +1,6 @@ name: 0.0.$(Date:yyMM.d)$(Rev:rrr) parameters: -- name: performBeachballCheck - displayName: Perform Beachball Check (Disable when promoting) - type: boolean - default: true - name: AgentPool type: object default: @@ -92,10 +88,6 @@ parameters: variables: - template: variables/windows.yml - group: RNW Secrets - - name: FailCGOnAlert - value: false - - name: EnableCodesign - value: true trigger: none pr: none @@ -110,54 +102,50 @@ extends: template: v1/1ES.Official.PipelineTemplate.yml@1ESPipelineTemplates parameters: pool: ${{ parameters.AgentPool.Medium }} - customBuildTags: - - ES365AIMigrationTooling + featureFlags: + autoEnablePREfastWithNewRuleset: false # PREfast produces 0 actionable findings; auto-enable injects /analyze into every C++ TU, generating ~2656 SARIF files that Guardian uploads for ~19 min per native build sdl: credscan: suppressionsFile: $(Build.SourcesDirectory)\.ado\config\CredScanSuppressions.json spotBugs: enabled: false # We don't have any java, but random packages in node_modules do + prefast: + enabled: false stages: - stage: RNWPublish jobs: - - job: RnwPublishPrep - displayName: React-Native-Windows Publish Prep + # Set version variables + - job: SetVersionVars + displayName: Set Version Variables pool: ${{ parameters.AgentPool.Medium }} - timeoutInMinutes: 120 - cancelTimeoutInMinutes: 5 + timeoutInMinutes: 15 steps: - - template: .ado/templates/checkout-full.yml@self + - template: .ado/templates/checkout-shallow.yml@self + + - template: .ado/templates/set-version-vars.yml@self parameters: - persistCredentials: false + buildEnvironment: Continuous - - powershell: gci env:/BUILD_* - displayName: Show build information + # We new npmPack.js in Release pipeline to detect already published NPM packages and avoid publishing them again + - script: copy ".ado\scripts\npmPack.js" "$(Build.StagingDirectory)\versionEnvVars\npmPack.js" + displayName: Include npmPack.js in VersionEnvVars artifact - - template: .ado/templates/prepare-js-env.yml@self + templateContext: + outputs: + - output: pipelineArtifact + displayName: 'Publish version variables' + targetPath: $(Build.StagingDirectory)/versionEnvVars + artifactName: VersionEnvVars - - template: .ado/templates/run-compliance-prebuild.yml@self - - - script: if not exist %USERPROFILE%\AppData\Roaming\npm (mkdir %USERPROFILE%\AppData\Roaming\npm) - displayName: Fix missing npm config - - - pwsh: | - npx beachball check --verbose 2>&1 | Tee-Object -Variable beachballOutput - $beachballErrors = $beachballOutput | Where-Object { $_ -match "ERROR: *"} - $beachballErrors | ForEach { Write-Host "##vso[task.logissue type=error]$_" } - if ( $beachballErrors.Count -gt 0) { throw "Beachball check found $($beachballErrors.Count) errors." } - displayName: Beachball Check - condition: ${{ parameters.performBeachballCheck }} - - - job: RnwNpmPublish - displayName: React-Native-Windows Npm Pack - dependsOn: RnwPublishPrep - pool: - name: Azure-Pipelines-1ESPT-ExDShared - image: windows-latest - os: windows - timeoutInMinutes: 120 + # Create NPM packages + - job: RnwNpmPack + displayName: Create NPM packages + pool: ${{ parameters.AgentPool.Medium }} + timeoutInMinutes: 60 cancelTimeoutInMinutes: 5 steps: + - template: .ado/templates/checkout-shallow.yml@self + - template: .ado/templates/prepare-js-env.yml@self parameters: agentImage: HostedImage @@ -168,21 +156,6 @@ extends: - script: dir /s "$(Pipeline.Workspace)\published-packages" displayName: Show created npm packages - - template: .ado/templates/set-version-vars.yml@self - parameters: - buildEnvironment: Continuous - - - script: echo NpmDistTag is $(NpmDistTag) - displayName: Show NPM dist tag - - - script: copy ".ado\scripts\npmPack.js" "$(Build.StagingDirectory)\versionEnvVars\npmPack.js" - displayName: Include npmPack.js in VersionEnvVars artifact - - - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 - displayName: 📒 Generate Manifest Npm - inputs: - BuildDropPath: $(System.DefaultWorkingDirectory) - templateContext: outputs: - output: pipelineArtifact @@ -190,23 +163,23 @@ extends: condition: succeededOrFailed() targetPath: $(Pipeline.Workspace)/published-packages artifactName: NpmPackedTarballs - - output: pipelineArtifact - displayName: "📒 Publish Manifest Npm" - artifactName: SBom-$(System.JobAttempt) - targetPath: $(System.DefaultWorkingDirectory)/_manifest - sbomEnabled: false # This output is in fact an SBOM itself - - output: pipelineArtifact - displayName: 'Publish version variables' - targetPath: $(Build.StagingDirectory)/versionEnvVars - artifactName: VersionEnvVars + # Run linting + - template: .ado/jobs/linting.yml@self + parameters: + buildEnvironment: Continuous + AgentPool: ${{ parameters.AgentPool }} + + # Create and sign Destop DLLs - ${{ each matrix in parameters.desktopBuildMatrix }}: - job: RnwNativeBuildDesktop${{ matrix.Name }} displayName: Build Desktop ${{ matrix.Name }} - dependsOn: RnwNpmPublish + dependsOn: SetVersionVars pool: ${{ parameters.AgentPool.Large }} timeoutInMinutes: 360 # CodeQL requires 3x usual build timeout steps: + - template: .ado/templates/checkout-shallow.yml@self + - template: .ado/templates/prepare-js-env.yml@self - template: .ado/templates/prepare-build-env.yml@self @@ -220,10 +193,11 @@ extends: - template: .ado/templates/msbuild-sln.yml@self parameters: solutionDir: vnext - solutionName: ReactWindows-Desktop.sln + solutionName: ReactWindows-Desktop.Publish.slnf buildPlatform: ${{ matrix.BuildPlatform }} buildConfiguration: ${{ matrix.BuildConfiguration }} oneESMode: true ## Files are only copied to staging, not published + msbuildArguments: /p:ForceImportAfterCppTargets=$(Build.SourcesDirectory)\vnext\PropertySheets\CIBuildOptimizations.props - template: .ado/templates/publish-build-artifacts.yml@self parameters: @@ -232,14 +206,20 @@ extends: buildPlatform: ${{ matrix.BuildPlatform }} buildConfiguration: ${{ matrix.BuildConfiguration }} contents: | - React.Windows.Desktop\** - React.Windows.Desktop.DLL\** - React.Windows.Desktop.Test.DLL\** + React.Windows.Desktop\Microsoft.ReactNative.winmd + React.Windows.Desktop.DLL\react-native-win32.* - - template: .ado/templates/component-governance.yml@self + - template: .ado/templates/esrp-codesign-binaries.yml@self + parameters: + displayName: 'CodeSign Desktop Binaries' + folderPath: $(Build.StagingDirectory)/NuGet/Desktop/${{ matrix.BuildPlatform }}/${{ matrix.BuildConfiguration }} + pattern: | + **/react-native-win32.dll templateContext: sdl: + prefast: + enabled: false binskim: analyzeTargetGlob: '$(Build.SourcesDirectory)\vnext\target\${{ matrix.BuildPlatform }}\${{ matrix.BuildConfiguration }}\React.Windows.Desktop.DLL\react-native-win32.dll' outputs: @@ -258,13 +238,16 @@ extends: artifactName: Desktop.${{matrix.buildPlatform}}.${{matrix.buildConfiguration}} targetPath: $(Build.StagingDirectory)/NuGet/Desktop/${{matrix.buildPlatform}}/${{matrix.buildConfiguration}} + # Create and sign Universal DLLs - ${{ each matrix in parameters.universalBuildMatrix }}: - job: RnwNativeBuildUniversal${{ matrix.Name }} displayName: Build Universal ${{ matrix.Name }} - dependsOn: RnwNpmPublish + dependsOn: SetVersionVars pool: ${{ parameters.AgentPool.Large }} timeoutInMinutes: 360 # CodeQL requires 3x usual build timeout steps: + - template: .ado/templates/checkout-shallow.yml@self + - template: .ado/templates/prepare-js-env.yml@self - template: .ado/templates/prepare-build-env.yml@self @@ -285,6 +268,7 @@ extends: buildPlatform: ${{ matrix.BuildPlatform }} buildConfiguration: ${{ matrix.BuildConfiguration }} oneESMode: true ## Files are only copied to staging, not published + msbuildArguments: /p:ForceImportAfterCppTargets=$(Build.SourcesDirectory)\vnext\PropertySheets\CIBuildOptimizations.props - task: PowerShell@2 displayName: Make AnyCPU Reference Assemblies @@ -307,10 +291,22 @@ extends: Microsoft.ReactNative.Managed.CodeGen\** Microsoft.ReactNative.CsWinRT\** - - template: .ado/templates/component-governance.yml@self + - template: .ado/templates/esrp-codesign-binaries.yml@self + parameters: + displayName: 'CodeSign Microsoft.ReactNative Binaries' + ${{ if eq(matrix.UseFabric, true) }}: + folderPath: $(Build.StagingDirectory)/NuGet/ReactWindowsFabric/${{ matrix.BuildPlatform }}/${{ matrix.BuildConfiguration }} + ${{ else }}: + folderPath: $(Build.StagingDirectory)/NuGet/ReactWindows/${{ matrix.BuildPlatform }}/${{ matrix.BuildConfiguration }} + pattern: | + **/Microsoft.ReactNative.dll + **/Microsoft.ReactNative.winmd + **/Microsoft.ReactNative.Projection.dll templateContext: sdl: + prefast: + enabled: false binskim: analyzeTargetGlob: '$(Build.SourcesDirectory)\vnext\target\${{ matrix.BuildPlatform }}\${{ matrix.BuildConfiguration }}\Microsoft.ReactNative\Microsoft.ReactNative.dll' outputs: @@ -334,16 +330,18 @@ extends: artifactName: ReactWindows.${{ matrix.BuildPlatform }}.${{ matrix.BuildConfiguration }} targetPath: $(Build.StagingDirectory)/NuGet/ReactWindows/${{ matrix.BuildPlatform }}/${{ matrix.BuildConfiguration }} + # Create Nuget packages - job: RNWNuget + displayName: Pack NuGet dependsOn: - - RnwNpmPublish + - RnwNpmPack + - Linting - ${{ each matrix in parameters.desktopBuildMatrix }}: - RnwNativeBuildDesktop${{ matrix.Name }} - ${{ each matrix in parameters.universalBuildMatrix }}: - RnwNativeBuildUniversal${{ matrix.Name }} - displayName: Sign Binaries and Publish NuGet pool: ${{ parameters.AgentPool.Medium }} - timeoutInMinutes: 120 # Protect against the long CodeSign task + timeoutInMinutes: 60 # Protect against the long CodeSign task steps: - template: .ado/templates/checkout-shallow.yml@self @@ -352,7 +350,7 @@ extends: - template: .ado/templates/apply-published-version-vars.yml@self - # The commit tag in the nuspec requires that we use at least nuget 5.8 (because things break with nuget versions before and Vs 16.8 or later) + # The commit tag in the nuspec requires that we use at least nuget 5.8 (because things break with nuget versions before and VS 16.8 or later) - task: NuGetToolInstaller@1 inputs: versionSpec: ">=5.8.0" @@ -367,8 +365,6 @@ extends: packMicrosoftReactNativeCxx: true packMicrosoftReactNativeManaged: true packMicrosoftReactNativeManagedCodeGen: true - ${{ if or(eq(variables['EnableCodesign'], 'true'), endsWith(variables['Build.SourceBranchName'], '-stable')) }}: # Sign if EnableCodeSign or on *-stable release builds - signMicrosoft: true slices: - platform: x64 configuration: Release @@ -383,8 +379,6 @@ extends: publishCommitId: $(publishCommitId) npmVersion: $(npmVersion) packDesktop: true - ${{ if or(eq(variables['EnableCodesign'], 'true'), endsWith(variables['Build.SourceBranchName'], '-stable')) }}: # Sign if EnableCodeSign or on *-stable release builds - signMicrosoft: true slices: - platform: x64 configuration: Release @@ -399,25 +393,11 @@ extends: - platform: ARM64EC configuration: Debug - # Symbol Publishing for Work Item 59264834 - MSRC Compliance - # continueOnError: Duplicate symbols are expected when the pipeline - # is re-run for the same version. The symbols already exist on the - # server, so it is safe to continue. - - task: PublishSymbols@2 - displayName: 'Publish Symbols to Microsoft Symbol Server' - continueOnError: true - condition: and(succeeded(), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI')) - inputs: - UseNetCoreClientTool: true - ConnectedServiceName: Office-React-Native-Windows-Bot - SymbolsFolder: '$(System.DefaultWorkingDirectory)\NugetRoot' - SearchPattern: '**/*.pdb' - SymbolServerType: 'TeamServices' - SymbolsProduct: 'ReactNativeWindows' - SymbolsVersion: '$(Build.BuildNumber)' - SymbolsArtifactName: 'ReactNativeWindows-Symbols-$(Build.BuildId)' - DetailedLog: true - TreatNotIndexedAsWarning: false + - template: .ado/templates/esrp-codesign-nuget.yml@self + parameters: + displayName: 'CodeSign all NuGet packages' + folderPath: $(System.DefaultWorkingDirectory)/NugetRootFinal + pattern: '**/*.nupkg' templateContext: sdl: diff --git a/.ado/release.yml b/.ado/release.yml index d8a20a99e4c..4bd8ffe7f58 100644 --- a/.ado/release.yml +++ b/.ado/release.yml @@ -3,7 +3,10 @@ # It releases npm packages to npmjs.com and NuGet packages to the public # ms/react-native and ms/react-native-public ADO feeds and to nuget.org. # -# The triggers are overridden by the ADO pipeline UI definition. +# The pipeline completion trigger is defined below in the pipeline resource. +# Do NOT add a build completion trigger in the ADO UI — UI triggers override +# YAML triggers and cause the pipeline to always run against the default branch +# with incorrect metadata (wrong commit message and branch). # name: RNW NuGet Release $(Date:yyyyMMdd).$(Rev:r) @@ -16,7 +19,15 @@ resources: - pipeline: 'Publish' project: 'ReactNative' source: 'Publish' - trigger: none + trigger: + branches: + include: + - main + - '0.74-stable' + - '0.81-stable' + - '0.82-stable' + - '0.83-stable' + - '0.84-stable' repositories: - repository: 1ESPipelineTemplates type: git @@ -30,14 +41,110 @@ extends: name: Azure-Pipelines-1ESPT-ExDShared image: windows-latest os: windows - customBuildTags: - - ES365AIMigrationTooling-Release stages: + # + # Gate stage — runs unconditionally for every trigger. + # It determines whether the Release stage should proceed and sets a + # descriptive build number so the pipeline history is easy to scan. + # + - stage: Gate + displayName: Evaluate release + jobs: + - job: Evaluate + displayName: Check if release should proceed + steps: + - checkout: none + + - script: | + echo == Build Variables == + echo Build.Reason: $(Build.Reason) + echo Build.SourceBranch: $(Build.SourceBranch) + echo Build.SourceVersion: $(Build.SourceVersion) + echo Build.SourceVersionMessage: $(Build.SourceVersionMessage) + echo Build.BuildNumber: $(Build.BuildNumber) + echo Build.BuildId: $(Build.BuildId) + echo Build.DefinitionName: $(Build.DefinitionName) + echo Build.Repository.Name: $(Build.Repository.Name) + echo System.TeamProject: $(System.TeamProject) + echo. + echo == Pipeline Resource: Publish == + echo Publish.runName: $(resources.pipeline.Publish.runName) + echo Publish.runID: $(resources.pipeline.Publish.runID) + echo Publish.sourceBranch: $(resources.pipeline.Publish.sourceBranch) + echo Publish.sourceCommit: $(resources.pipeline.Publish.sourceCommit) + echo Publish.pipelineID: $(resources.pipeline.Publish.pipelineID) + echo Publish.requestedFor: $(resources.pipeline.Publish.requestedFor) + echo Publish.requestedForID: $(resources.pipeline.Publish.requestedForID) + displayName: Log all pipeline variables + + - powershell: | + $buildReason = $env:BUILD_REASON + # Use only the first line of the commit message + $sourceMessage = ($env:SOURCE_MESSAGE -split "`n")[0].Trim() + $publishRunName = $env:PUBLISH_RUN_NAME + $sourceBranch = $env:SOURCE_BRANCH -replace '^refs/heads/', '' + + # Extract the datestamp (e.g. "20260319.4") from the original build number + # which has the format "RNW NuGet Release 20260319.4" + $originalBuildNumber = $env:BUILD_BUILDNUMBER + $dateStamp = if ($originalBuildNumber -match '(\d{8}\.\d+)$') { $Matches[1] } else { "" } + + $shouldRelease = $false + $buildNumber = "" + + if ($buildReason -eq "Manual") { + $shouldRelease = $true + if ($publishRunName) { + $buildNumber = "$publishRunName ($sourceBranch) - $dateStamp" + } else { + $buildNumber = "Release ($sourceBranch) - $dateStamp" + } + } + elseif ($sourceMessage.StartsWith("RELEASE:")) { + $shouldRelease = $true + $buildNumber = "$publishRunName ($sourceBranch) - $dateStamp" + } + else { + $shouldRelease = $false + # Truncate commit message for readability + $shortMsg = $sourceMessage + if ($shortMsg.Length -gt 60) { + $shortMsg = $shortMsg.Substring(0, 57) + "..." + } + $buildNumber = "Skipped - $shortMsg ($sourceBranch) - $dateStamp" + } + + # Sanitize: ADO build numbers cannot contain " / : < > \ | ? @ * + # and cannot end with '.' + $buildNumber = $buildNumber -replace '["/:<>\\|?@*]', '_' + $buildNumber = $buildNumber.TrimEnd('.') + + Write-Host "shouldRelease: $shouldRelease" + Write-Host "buildNumber: $buildNumber" + + Write-Host "##vso[build.updatebuildnumber]$buildNumber" + Write-Host "##vso[task.setvariable variable=shouldRelease;isOutput=true]$shouldRelease" + name: gate + displayName: Determine release eligibility and set build number + env: + BUILD_REASON: $(Build.Reason) + BUILD_BUILDNUMBER: $(Build.BuildNumber) + SOURCE_MESSAGE: $(Build.SourceVersionMessage) + PUBLISH_RUN_NAME: $(resources.pipeline.Publish.runName) + SOURCE_BRANCH: $(resources.pipeline.Publish.sourceBranch) + + - script: echo Proceeding with release + displayName: RELEASING - proceeding to publish + condition: eq(variables['gate.shouldRelease'], 'True') + + - script: echo Skipping release + displayName: SKIPPED - not a RELEASE commit + condition: eq(variables['gate.shouldRelease'], 'False') + - stage: Release displayName: Publish artifacts - # Allow manual runs unconditionally; for build-completion triggers, - # only proceed if the commit message starts with 'RELEASE:'. - condition: or(eq(variables['Build.Reason'], 'Manual'), startsWith(variables['Build.SourceVersionMessage'], 'RELEASE:')) + dependsOn: Gate + condition: eq(dependencies.Gate.outputs['Evaluate.gate.shouldRelease'], 'True') jobs: - job: PushNpm displayName: npmjs.com - Publish npm packages @@ -73,7 +180,7 @@ extends: Write-Host "Found $tgzCount .tgz files" Write-Host "##vso[task.setvariable variable=HasPackagesToPublish]$($tgzCount -gt 0)" displayName: Check if there are packages to publish - - task: 'SFP.release-tasks.custom-build-release-task.EsrpRelease@10' + - task: 'EsrpRelease@11' displayName: 'ESRP Release to npmjs.com' condition: and(succeeded(), ne(variables['NpmDistTag'], ''), eq(variables['HasPackagesToPublish'], 'true')) inputs: @@ -158,3 +265,62 @@ extends: - script: nuget.exe push .\Microsoft.ReactNative.*.nupkg -Source https://api.nuget.org/v3/index.json -SkipDuplicate -NoSymbol -NonInteractive -Verbosity Detailed displayName: NuGet push (nuget.org) workingDirectory: $(Pipeline.Workspace)/ReactWindows-final-nuget + + - job: PublishSymbols + displayName: Publish PDB Symbols to Symbol Server + timeoutInMinutes: 30 + templateContext: + type: releaseJob + isProduction: true + inputs: + - input: pipelineArtifact + pipeline: 'Publish' + artifactName: 'ReactWindows-final-nuget' + targetPath: '$(Pipeline.Workspace)/ReactWindows-final-nuget' + steps: + - powershell: | + # Extract PDB files from all NuGet packages (.nupkg are ZIP archives) + $nugetDir = "$(Pipeline.Workspace)/ReactWindows-final-nuget" + $symbolsDir = "$(Pipeline.Workspace)/symbols" + New-Item -ItemType Directory -Path $symbolsDir -Force | Out-Null + + $nupkgs = Get-ChildItem "$nugetDir/*.nupkg" + Write-Host "Found $($nupkgs.Count) NuGet packages" + + foreach ($nupkg in $nupkgs) { + Write-Host "Extracting PDBs from: $($nupkg.Name)" + $extractDir = "$symbolsDir/$($nupkg.BaseName)" + # Rename to .zip for Expand-Archive compatibility + $zipPath = "$nugetDir/$($nupkg.BaseName).zip" + Copy-Item $nupkg.FullName $zipPath + Expand-Archive -Path $zipPath -DestinationPath $extractDir -Force + Remove-Item $zipPath + } + + # Show extracted PDBs + $pdbs = Get-ChildItem "$symbolsDir" -Recurse -Filter "*.pdb" + Write-Host "`nFound $($pdbs.Count) PDB files:" + foreach ($pdb in $pdbs) { + Write-Host " $($pdb.FullName) ($([math]::Round($pdb.Length / 1MB, 2)) MB)" + } + + if ($pdbs.Count -eq 0) { + Write-Host "##vso[task.logissue type=warning]No PDB files found in NuGet packages" + } + displayName: Extract PDBs from NuGet packages + + - task: PublishSymbols@2 + displayName: 'Publish Symbols to Microsoft Symbol Server' + continueOnError: true + inputs: + UseNetCoreClientTool: true + ConnectedServiceName: Office-React-Native-Windows-Bot + SymbolsFolder: '$(Pipeline.Workspace)/symbols' + SearchPattern: '**/*.pdb' + SymbolServerType: 'TeamServices' + IndexSources: false # SourceLink is already embedded in PDBs at compile time + SymbolsProduct: 'ReactNativeWindows' + SymbolsVersion: '$(Build.BuildNumber)' + SymbolsArtifactName: 'ReactNativeWindows-Symbols-$(Build.BuildId)' + DetailedLog: true + TreatNotIndexedAsWarning: false diff --git a/.ado/templates/checkout-shallow.yml b/.ado/templates/checkout-shallow.yml index 21460b9c88d..20c685f9395 100644 --- a/.ado/templates/checkout-shallow.yml +++ b/.ado/templates/checkout-shallow.yml @@ -2,7 +2,7 @@ # without full history. steps: - checkout: self - fetchDepth: 10 # Buffer to avoid race condition with AZP jobs started against merge branch + fetchDepth: 1 clean: false submodules: false lfs: false diff --git a/.ado/templates/esrp-codesign-binaries.yml b/.ado/templates/esrp-codesign-binaries.yml new file mode 100644 index 00000000000..9c8c03adcf5 --- /dev/null +++ b/.ado/templates/esrp-codesign-binaries.yml @@ -0,0 +1,45 @@ +parameters: + - name: displayName + type: string + - name: folderPath + type: string + - name: pattern + type: string + +steps: + - task: EsrpCodeSigning@6 + displayName: ${{ parameters.displayName }} + inputs: + ConnectedServiceName: 'ESRP-CodeSigning-OGX-JSHost-RNW' + AppRegistrationClientId: '0a35e01f-eadf-420a-a2bf-def002ba898d' + AppRegistrationTenantId: 'cdc5aeea-15c5-4db6-b079-fcadd2505dc2' + AuthAKVName: 'OGX-JSHost-KV' + AuthCertName: 'OGX-JSHost-Auth4' + AuthSignCertName: 'OGX-JSHost-Sign3' + FolderPath: ${{ parameters.folderPath }} + Pattern: ${{ parameters.pattern }} + UseMinimatch: true + signConfigType: inlineSignParams + inlineOperation: | + [ + { + "KeyCode" : "CP-230012", + "OperationCode" : "SigntoolSign", + "Parameters" : { + "OpusName" : "Microsoft", + "OpusInfo" : "http://www.microsoft.com", + "FileDigest" : "/fd \"SHA256\"", + "PageHash" : "/PH", + "TimeStamp" : "/tr \"http://rfc3161.gtm.corp.microsoft.com/TSS/HttpTspServer\" /td sha256" + }, + "ToolName" : "sign", + "ToolVersion" : "1.0" + }, + { + "KeyCode" : "CP-230012", + "OperationCode" : "SigntoolVerify", + "Parameters" : {}, + "ToolName" : "sign", + "ToolVersion" : "1.0" + } + ] diff --git a/.ado/templates/esrp-codesign-nuget.yml b/.ado/templates/esrp-codesign-nuget.yml new file mode 100644 index 00000000000..3666061449f --- /dev/null +++ b/.ado/templates/esrp-codesign-nuget.yml @@ -0,0 +1,39 @@ +parameters: + - name: displayName + type: string + - name: folderPath + type: string + - name: pattern + type: string + +steps: + - task: EsrpCodeSigning@6 + displayName: ${{ parameters.displayName }} + inputs: + ConnectedServiceName: 'ESRP-CodeSigning-OGX-JSHost-RNW' + AppRegistrationClientId: '0a35e01f-eadf-420a-a2bf-def002ba898d' + AppRegistrationTenantId: 'cdc5aeea-15c5-4db6-b079-fcadd2505dc2' + AuthAKVName: 'OGX-JSHost-KV' + AuthCertName: 'OGX-JSHost-Auth4' + AuthSignCertName: 'OGX-JSHost-Sign3' + FolderPath: ${{ parameters.folderPath }} + Pattern: ${{ parameters.pattern }} + UseMinimatch: true + signConfigType: inlineSignParams + inlineOperation: | + [ + { + "KeyCode" : "CP-401405", + "OperationCode" : "NuGetSign", + "Parameters" : {}, + "ToolName" : "sign", + "ToolVersion" : "1.0" + }, + { + "KeyCode" : "CP-401405", + "OperationCode" : "NuGetVerify", + "Parameters" : {}, + "ToolName" : "sign", + "ToolVersion" : "1.0" + } + ] diff --git a/.ado/templates/prep-and-pack-nuget.yml b/.ado/templates/prep-and-pack-nuget.yml index 95628d46e89..9addeb85594 100644 --- a/.ado/templates/prep-and-pack-nuget.yml +++ b/.ado/templates/prep-and-pack-nuget.yml @@ -35,9 +35,6 @@ parameters: type: boolean default: false - - name: signMicrosoft - type: boolean - default: false steps: - pwsh: | @@ -102,8 +99,6 @@ steps: outputPackage: Microsoft.ReactNative slices: $(releaseSlices) packageVersion: ${{parameters.npmVersion}} - codesignBinaries: ${{ parameters.signMicrosoft }} - codesignNuget: ${{ parameters.signMicrosoft }} buildProperties: CommitId=${{parameters.publishCommitId}};nugetroot=${{parameters.nugetroot}};baseconfiguration=Release;baseplatform=$(releaseBasePlatform) @@ -113,7 +108,6 @@ steps: outputPackage: Microsoft.ReactNative.Cxx packageVersion: ${{parameters.npmVersion}} buildProperties: CommitId=${{parameters.publishCommitId}};nugetroot=${{parameters.nugetroot}};baseconfiguration=$(baseConfiguration);baseplatform=$(basePlatform) - codesignNuget: ${{ parameters.signMicrosoft }} - ${{ if eq(parameters.packMicrosoftReactNativeManaged, true) }}: - ${{ if containsValue(parameters.slices.*.configuration, 'Release') }}: @@ -122,8 +116,6 @@ steps: outputPackage: Microsoft.ReactNative.Managed slices: $(releaseSlices) packageVersion: ${{parameters.npmVersion}} - codesignBinaries: ${{ parameters.signMicrosoft }} - codesignNuget: ${{ parameters.signMicrosoft }} buildProperties: CommitId=${{parameters.publishCommitId}};nugetroot=${{parameters.nugetroot}};baseconfiguration=Release;baseplatform=$(releaseBasePlatform) - ${{ if eq(parameters.packMicrosoftReactNativeManagedCodeGen, true) }}: @@ -132,5 +124,3 @@ steps: outputPackage: Microsoft.ReactNative.Managed.CodeGen packageVersion: ${{parameters.npmVersion}} buildProperties: CommitId=${{parameters.publishCommitId}};nugetroot=${{parameters.nugetroot}};baseconfiguration=$(baseConfiguration);baseplatform=$(basePlatform) - codesignBinaries: ${{ parameters.signMicrosoft }} - codesignNuget: ${{ parameters.signMicrosoft }} diff --git a/.ado/templates/prep-and-pack-single.yml b/.ado/templates/prep-and-pack-single.yml index e07757bdbfd..cdc7d7f4081 100644 --- a/.ado/templates/prep-and-pack-single.yml +++ b/.ado/templates/prep-and-pack-single.yml @@ -2,7 +2,7 @@ parameters: # Required: Name to publish the NuGet Package As - name: outputPackage type: string - + # Required: NPM-matching version - name: packageVersion type: string @@ -12,33 +12,17 @@ parameters: type: string default: '' - # Optional: Pattern of binaries within the artifact to sign as part of this - # NuGet package. Defaults to .dll, .winmd, .exe matching the nuspec name - - name: binariesToSign - type: string - default: '' - # Optional: Excludes platform-specific files from the NuSpec of they are not # included in slices - name: slices type: string default: '' - # Optional: Properties to pass to nuspec + # Optional: Properties to pass to nuspec - name: buildProperties type: string default: '' - # Optional: Whether to sign binaries - - name: codesignBinaries - type: boolean - default: false - - # Optional: Whether to sign the NuGet packag - - name: codesignNuget - type: boolean - default: false - steps: - powershell: gci $(System.DefaultWorkingDirectory)/NugetRoot @@ -54,50 +38,8 @@ steps: displayName: '${{ parameters.outputPackage }} - Strip slices from nuspec' workingDirectory: $(System.DefaultWorkingDirectory)/NugetRoot - - ${{ if eq(parameters.codesignBinaries, true) }}: - - task: SFP.build-tasks.custom-build-task-1.EsrpCodeSigning@5 - displayName: '${{ parameters.outputPackage }} CodeSign Binaries' - inputs: - ConnectedServiceName: 'ESRP-CodeSigning-OGX-JSHost-RNW' - AppRegistrationClientId: '0a35e01f-eadf-420a-a2bf-def002ba898d' - AppRegistrationTenantId: 'cdc5aeea-15c5-4db6-b079-fcadd2505dc2' - AuthAKVName: 'OGX-JSHost-KV' - AuthCertName: 'OGX-JSHost-Auth4' - AuthSignCertName: 'OGX-JSHost-Sign3' - FolderPath: $(System.DefaultWorkingDirectory)/NugetRoot - # Recursively finds files matching these patterns: - ${{ if ne(parameters.binariesToSign, '') }}: - Pattern: ${{ parameters.binariesToSign }} - ${{ else }}: - Pattern: | - **/${{ coalesce(parameters.nuspec, parameters.outputPackage) }}.dll - **/${{ coalesce(parameters.nuspec, parameters.outputPackage) }}.winmd - **/${{ coalesce(parameters.nuspec, parameters.outputPackage) }}.exe - UseMinimatch: true - signConfigType: inlineSignParams - inlineOperation: | - [ - { - "KeyCode" : "CP-230012", - "OperationCode" : "SigntoolSign", - "Parameters" : { - "OpusName" : "Microsoft", - "OpusInfo" : "http://www.microsoft.com", - "FileDigest" : "/fd \"SHA256\"", - "PageHash" : "/PH", - "TimeStamp" : "/tr \"http://rfc3161.gtm.corp.microsoft.com/TSS/HttpTspServer\" /td sha256" - }, - "ToolName" : "sign", - "ToolVersion" : "1.0" - }, - { - "KeyCode" : "CP-230012", - "OperationCode" : "SigntoolVerify", - "Parameters" : {}, - "ToolName" : "sign", - "ToolVersion" : "1.0" - } - ] + # Binary signing is done in build jobs (ESRP CodeSign before artifact upload) + # NuGet signing is done in batch in publish.yml (single ESRP call for all .nupkg) # NuGetCommand@2 workaround: https://developercommunity.visualstudio.com/content/problem/288534/vsts-yaml-build-failure-the-task-name-nugetcommand.html - task: 333b11bd-d341-40d9-afcf-b32d5ce6f23b@2 @@ -109,39 +51,6 @@ steps: packDestination: $(System.DefaultWorkingDirectory)/NugetRootFinal buildProperties: version=${{ parameters.packageVersion }};id=${{ parameters.outputPackage }};${{ parameters.buildProperties }} - - ${{ if eq(parameters.codesignNuget, true) }}: - - task: SFP.build-tasks.custom-build-task-1.EsrpCodeSigning@5 - displayName: '${{ parameters.outputPackage }} CodeSign NuGet' - inputs: - ConnectedServiceName: 'ESRP-CodeSigning-OGX-JSHost-RNW' - AppRegistrationClientId: '0a35e01f-eadf-420a-a2bf-def002ba898d' - AppRegistrationTenantId: 'cdc5aeea-15c5-4db6-b079-fcadd2505dc2' - AuthAKVName: 'OGX-JSHost-KV' - AuthCertName: 'OGX-JSHost-Auth4' - AuthSignCertName: 'OGX-JSHost-Sign3' - FolderPath: $(System.DefaultWorkingDirectory)/NugetRootFinal - Pattern: | - **/${{ parameters.outputPackage }}.${{ parameters.packageVersion }}.nupkg - UseMinimatch: true - signConfigType: inlineSignParams - inlineOperation: | - [ - { - "KeyCode" : "CP-401405", - "OperationCode" : "NuGetSign", - "Parameters" : {}, - "ToolName" : "sign", - "ToolVersion" : "1.0" - }, - { - "KeyCode" : "CP-401405", - "OperationCode" : "NuGetVerify", - "Parameters" : {}, - "ToolName" : "sign", - "ToolVersion" : "1.0" - } - ] - - powershell: gci $(System.DefaultWorkingDirectory)/NugetRootFinal displayName: List files in NugetRootFinal diff --git a/.gitignore b/.gitignore index 94a413d154c..8724fe25a55 100644 --- a/.gitignore +++ b/.gitignore @@ -196,3 +196,4 @@ nul .store*/* /npm-pkgs +/.claude diff --git a/.unbroken_exclusions b/.unbroken_exclusions index a07ede1bd82..ef9e36b50d6 100644 --- a/.unbroken_exclusions +++ b/.unbroken_exclusions @@ -2,6 +2,9 @@ URL not found https://docs.github.com/pull-requests/collaborating-with-pull-requ URL not found https://docs.github.com/pull-requests/collaborating-with-pull-requests/working-with-forks/about-forks while parsing CONTRIBUTING.md (HTTP 403) URL not found https://docs.github.com/get-started/quickstart while parsing CONTRIBUTING.md (HTTP 403) File not found edge:/inspect while parsing packages/playground/README_composition.md +URL not found https://www.npmjs.com/org/rnw-scripts while parsing packages/README.md (HTTP 403) +URL not found https://aka.ms/watson while parsing docs/sdl-gs-crash-monitoring.md (HTTP 401) +URL not found https://www.npmjs.com/package/mustache while parsing docs/react-native-windows-init.md (HTTP 403) !**/node_modules !vnext/packages !vnext/ReactCopies diff --git a/README.md b/README.md index e7a1e680bd1..3779c99e1de 100644 --- a/README.md +++ b/README.md @@ -58,16 +58,12 @@ Search the [existing issues](https://github.com/microsoft/react-native-windows/i ## Documentation React Native has [great documentation](https://reactnative.dev/docs/getting-started). React Native for Windows adds its own separate [Windows and macOS documentation](https://microsoft.github.io/react-native-windows/) for desktop platform information like API docs and blog updates. -### Security Documentation -- **[Security Configuration Guide](https://github.com/microsoft/react-native-windows/blob/main/docs/security-configuration.md)** - Comprehensive guide for SDL-compliant security configurations -- **[Security Best Practices](https://github.com/microsoft/react-native-windows/blob/main/docs/security-best-practices.md)** - Secure coding patterns and security API usage - ### Examples - Using the CLI in the [Getting Started](https://microsoft.github.io/react-native-windows/docs/getting-started) guide will set you up with a sample React Native for Windows app that you can begin editing right away. - Check the [samples repo](https://github.com/microsoft/react-native-windows-samples) for more standalone samples. - The [React Native Gallery](https://github.com/microsoft/react-native-gallery) app demonstrates various components in an interactive way. - Check out the [React Native Developer Blog](https://devblogs.microsoft.com/react-native/) to see examples from past conference talks, blog posts, and more. -- For more sample code browse the [RNTester folder](https://github.com/microsoft/react-native-windows/tree/main/packages/e2e-test-app/windows/RNTesterApp) in the GitHub web UI. +- For more sample code browse the [RNTester folder](https://github.com/microsoft/react-native-windows/tree/0.81-stable/packages/e2e-test-app/windows/RNTesterApp) in the GitHub web UI. ## 📢 Contributing See [Contributing guidelines](https://github.com/microsoft/react-native-windows/blob/main/CONTRIBUTING.md) for how to setup your fork of the repo and start a PR to contribute to React Native for Windows. diff --git a/change/@react-native-windows-codegen-d501d375-47e5-4d3a-9cbc-4e82c50b8aad.json b/change/@react-native-windows-codegen-d501d375-47e5-4d3a-9cbc-4e82c50b8aad.json new file mode 100644 index 00000000000..d487391891c --- /dev/null +++ b/change/@react-native-windows-codegen-d501d375-47e5-4d3a-9cbc-4e82c50b8aad.json @@ -0,0 +1,7 @@ +{ + "type": "patch", + "comment": "Speed up the publish pipeline (#15785)", + "packageName": "@react-native-windows/codegen", + "email": "vmorozov@microsoft.com", + "dependentChangeType": "patch" +} diff --git a/change/react-native-windows-959c3f60-0f33-4ac8-a081-dc6452e2d455.json b/change/react-native-windows-959c3f60-0f33-4ac8-a081-dc6452e2d455.json new file mode 100644 index 00000000000..9b547c58d34 --- /dev/null +++ b/change/react-native-windows-959c3f60-0f33-4ac8-a081-dc6452e2d455.json @@ -0,0 +1,7 @@ +{ + "type": "prerelease", + "comment": "Speed up the publish pipeline", + "packageName": "react-native-windows", + "email": "vmorozov@microsoft.com", + "dependentChangeType": "patch" +} diff --git a/docs/breakingchanges-0.63.md b/docs/breakingchanges-0.63.md deleted file mode 100644 index 5effc36d24b..00000000000 --- a/docs/breakingchanges-0.63.md +++ /dev/null @@ -1,92 +0,0 @@ - -# Breaking changes for 0.63 - -## Managed C# projects -In 0.63 we have deprecated the Microsoft.ReactNative.SharedManaged project in favor of a proper library reference. If you only have cpp projects, no action is needed. If you have a C# app or C# native module, to update your project please perform the following actions: - -### At least one C# project - -1. Update your `.sln` file in the following ways: - 1. Replace the shared project with the regular project: - ```diff - - Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Microsoft.ReactNative.SharedManaged", "..\..\..\vnext\Microsoft.ReactNative.SharedManaged\Microsoft.ReactNative.SharedManaged.shproj", "{67A1076F-7790-4203-86EA-4402CCB5E782}" - + Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.ReactNative.Managed", "..\node_modules\react-native-windows\Microsoft.ReactNative.Managed\Microsoft.ReactNative.Managed.csproj", "{F2824844-CE15-4242-9420-308923CD76C3}" - ``` - 1. Remove the shared project section of the old project: - ```diff - GlobalSection(SharedMSBuildProjectFiles) = preSolution - - ..\..\..\vnext\Microsoft.ReactNative.SharedManaged\Microsoft.ReactNative. SharedManaged.projitems*{67a1076f-7790-4203-86ea-4402ccb5e782}*SharedItemsImports = 13 - ``` - 1. Insert the configuration section for the new project - ```diff - GlobalSection(ProjectConfigurationPlatforms) = postSolution - + {F2824844-CE15-4242-9420-308923CD76C3}.Debug|ARM.ActiveCfg = Debug|ARM - + {F2824844-CE15-4242-9420-308923CD76C3}.Debug|ARM.Build.0 = Debug|ARM - + {F2824844-CE15-4242-9420-308923CD76C3}.Debug|ARM64.ActiveCfg = Debug|ARM64 - + {F2824844-CE15-4242-9420-308923CD76C3}.Debug|ARM64.Build.0 = Debug|ARM64 - + {F2824844-CE15-4242-9420-308923CD76C3}.Debug|x64.ActiveCfg = Debug|x64 - + {F2824844-CE15-4242-9420-308923CD76C3}.Debug|x64.Build.0 = Debug|x64 - + {F2824844-CE15-4242-9420-308923CD76C3}.Debug|x86.ActiveCfg = Debug|x86 - + {F2824844-CE15-4242-9420-308923CD76C3}.Debug|x86.Build.0 = Debug|x86 - + {F2824844-CE15-4242-9420-308923CD76C3}.Release|ARM.ActiveCfg = Release|ARM - + {F2824844-CE15-4242-9420-308923CD76C3}.Release|ARM.Build.0 = Release|ARM - + {F2824844-CE15-4242-9420-308923CD76C3}.Release|ARM64.ActiveCfg = Release|ARM64 - + {F2824844-CE15-4242-9420-308923CD76C3}.Release|ARM64.Build.0 = Release|ARM64 - + {F2824844-CE15-4242-9420-308923CD76C3}.Release|x64.ActiveCfg = Release|x64 - + {F2824844-CE15-4242-9420-308923CD76C3}.Release|x64.Build.0 = Release|x64 - + {F2824844-CE15-4242-9420-308923CD76C3}.Release|x86.ActiveCfg = Release|x86 - + {F2824844-CE15-4242-9420-308923CD76C3}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - ``` - 1. Update the folder structure in the solution - ```diff - GlobalSection(NestedProjects) = preSolution - - {FCA38F3C-7C73-4C47-BE4E-32F77FA8538D} = {5EA20F54-880A-49F3-99FA-4B3FE54E8AB1} - + {F2824844-CE15-4242-9420-308923CD76C3} = {5EA20F54-880A-49F3-99FA-4B3FE54E8AB1} - EndGlobalSection - ``` -1. Open file `App.xaml.cs` - and ensure that you add a call to register the types in this through Reflection and remove the comment that the main provider handles modules in this project - ```diff - - PackageProviders.Add(new Microsoft.ReactNative.Managed.ReactPackageProvider()); // Includes any modules in this project - + PackageProviders.Add(new Microsoft.ReactNative.Managed.ReactPackageProvider()); - + PackageProviders.Add(new ReflectionReactPackageProvider()); - ``` - - > note: this will change when codegen becomes default -1. Update your App `.csproj` file in the following way (Only if you created the project before 0.62) - 1. Check if has an import for `Microsoft.ReactNative.SharedManaged` - 1. Add the following to the top of your `.csproj` - ```diff - - - + - + $([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), 'node_modules\react-native-windows\package.json'))\node_modules\react-native-windows\ - + - + - ``` - 1. Add the following to the bottom of your `.csproj` file: - ```diff - + - - ``` - 1. Remove references to `Microsoft.ReactNative` and Xaml: - ```diff - - - - {f7d32bd0-2749-483e-9a0d-1635ef7e3136} - - Microsoft.ReactNative - - - - - - 2.3.191129002 - - - ``` - 1. Remove references to `Microsoft.ReactNative.SharedManaged` - ```diff - - - ``` - 1. Remove imports for bundeling - ```diff - - - - - ``` - diff --git a/docs/managedCodeGen.md b/docs/managedCodeGen.md index 2f33659fbc9..52023ba6611 100644 --- a/docs/managedCodeGen.md +++ b/docs/managedCodeGen.md @@ -27,7 +27,7 @@ When building the apps that are checked in to our repo for testing, we have to r ## Turning on/off Currently the feature is behind an MSBuild property `$(ReactNativeCodeGenEnabled)`. -The default at the moment is false, it is only turned on for a single project for now which is the [SampleLibraryCS.csproj](https://github.com/microsoft/react-native-windows/blob/main/packages/sample-apps/windows/SampleLibraryCS/SampleLibraryCS.csproj) project, to prove it is stable. We will slowly enable it for all projects in the repo and then make it the default. +The default at the moment is false, it is only turned on for a single project for now to prove it is stable. We will slowly enable it for all projects in the repo and then make it the default. ## MSBuild/NuGet Complications MSBuild and NuGet spent a long time fighting me in mixing a NetCoreApp3.1 executable and WinRT apps in the same solution and the same build. ProjectReferences cannot be used so I had to use the `` task directly in the targets and it was tricky making it build from both the customer apps as well as our main build solution and unittest (Microsoft.ReactNative.sln). In the end there are a few hacks in place to make this work. diff --git a/docs/security-best-practices.md b/docs/security-best-practices.md deleted file mode 100644 index ec50238d3ad..00000000000 --- a/docs/security-best-practices.md +++ /dev/null @@ -1,503 +0,0 @@ -# Security Best Practices for React Native Windows - -This document outlines security best practices for developing applications with React Native Windows, focusing on secure coding patterns, API usage, and common security pitfalls to avoid. - -## Table of Contents - -- [Secure Development Practices](#secure-development-practices) -- [Native Module Security](#native-module-security) -- [WebView Security](#webview-security) -- [Data Protection](#data-protection) -- [Network Security](#network-security) -- [Common Security Pitfalls](#common-security-pitfalls) - -## Secure Development Practices - -### Input Validation - -Always validate inputs in native modules and JavaScript code: - -```cpp -// Native module input validation example -REACT_METHOD(ProcessUserInput) -void ProcessUserInput(std::string userInput) noexcept { - // Validate input length - if (userInput.length() > MAX_INPUT_LENGTH) { - // Log security event and reject - return; - } - - // Sanitize input - std::string sanitized = SanitizeInput(userInput); - - // Process sanitized input - ProcessSafeInput(sanitized); -} -``` - -```javascript -// JavaScript input validation -function validateUserInput(input) { - if (typeof input !== 'string' || input.length > 1000) { - throw new Error('Invalid input'); - } - - // Remove potentially dangerous characters - return input.replace(/[<>\"'&]/g, ''); -} -``` - -### Memory Management - -Use RAII and smart pointers in native code: - -```cpp -#include - -class SecureNativeModule { -public: - void ProcessData(const std::vector& data) { - // Use smart pointers for automatic cleanup - auto buffer = std::make_unique(data.size()); - - // Process data safely - std::copy(data.begin(), data.end(), buffer.get()); - - // Automatic cleanup when scope exits - } -}; -``` - -### Error Handling - -Implement secure error handling that doesn't leak sensitive information: - -```cpp -REACT_METHOD(SecureOperation) -void SecureOperation(std::string input, ReactPromise promise) noexcept { - try { - auto result = PerformSecureOperation(input); - promise.Resolve(result); - } - catch (const SecurityException& e) { - // Log detailed error internally - LogSecurityEvent(e.what()); - - // Return generic error to client - promise.Reject("Operation failed"); - } - catch (const std::exception& e) { - // Log error and return generic message - LogError(e.what()); - promise.Reject("An error occurred"); - } -} -``` - -## Native Module Security - -### Windows Security API Integration - -Use Windows security APIs through native modules: - -```cpp -#include -#include - -using namespace winrt::Windows::Security::Cryptography; -using namespace winrt::Windows::Storage::Streams; - -REACT_METHOD(GenerateSecureRandom) -void GenerateSecureRandom(int length, ReactPromise promise) noexcept { - try { - // Use Windows cryptographically secure random generation - auto buffer = CryptographicBuffer::GenerateRandom(length); - auto base64 = CryptographicBuffer::EncodeToBase64String(buffer); - - promise.Resolve(winrt::to_string(base64)); - } - catch (...) { - promise.Reject("Failed to generate random data"); - } -} -``` - -### Credential Management - -Implement secure credential handling: - -```cpp -#include - -using namespace winrt::Windows::Security::Credentials; - -REACT_METHOD(StoreCredential) -void StoreCredential(std::string resource, std::string userName, - std::string password, ReactPromise promise) noexcept { - try { - PasswordVault vault; - PasswordCredential credential( - winrt::to_hstring(resource), - winrt::to_hstring(userName), - winrt::to_hstring(password) - ); - - vault.Add(credential); - promise.Resolve(true); - } - catch (...) { - promise.Reject("Failed to store credential"); - } -} -``` - -## WebView Security - -### Secure WebView Configuration - -Configure WebView2 with appropriate security settings: - -```cpp -// WebView2 security configuration -auto webviewOptions = WebView2::CoreWebView2CreationProperties(); -webviewOptions.put_AdditionalBrowserArguments( - L"--disable-web-security=false " - L"--enable-features=msWebView2BrowserHitTesting " - L"--force-effective-connection-type=4g" -); - -// Configure content security -webview.NavigationStarting([](auto&&, auto&& args) { - auto uri = args.Uri(); - - // Validate allowed origins - if (!IsAllowedOrigin(uri)) { - args.Cancel(true); - } -}); -``` - -### Content Security Policy - -Implement Content Security Policy for web content: - -```html - - -``` - -### Origin Validation - -Validate message origins in WebView communication: - -```javascript -// JavaScript side - validate message origin -window.addEventListener('message', (event) => { - // Validate origin - if (event.origin !== 'https://trusted-domain.com') { - return; - } - - // Process trusted message - handleTrustedMessage(event.data); -}); -``` - -```cpp -// Native side - validate WebView messages -webview.WebMessageReceived([](auto&&, auto&& args) { - auto message = args.TryGetWebMessageAsString(); - - // Validate message format and content - if (!IsValidMessage(message)) { - return; - } - - ProcessValidMessage(message); -}); -``` - -## Data Protection - -### Encryption - -Use Windows encryption APIs for sensitive data: - -```cpp -#include - -using namespace winrt::Windows::Security::Cryptography::Core; - -REACT_METHOD(EncryptData) -void EncryptData(std::string plaintext, ReactPromise promise) noexcept { - try { - // Use AES encryption - auto algorithm = SymmetricKeyAlgorithmProvider::OpenAlgorithm( - SymmetricAlgorithmNames::AesGcm()); - - auto key = algorithm.GenerateKey(256 / 8); // 256-bit key - - auto plaintextBuffer = CryptographicBuffer::ConvertStringToBinary( - winrt::to_hstring(plaintext), BinaryStringEncoding::Utf8); - - auto encryptedBuffer = CryptographicEngine::Encrypt( - key, plaintextBuffer, nullptr); - - auto base64 = CryptographicBuffer::EncodeToBase64String(encryptedBuffer); - promise.Resolve(winrt::to_string(base64)); - } - catch (...) { - promise.Reject("Encryption failed"); - } -} -``` - -### Secure Storage - -Implement secure local storage: - -```javascript -import {NativeModules} from 'react-native'; -const {SecureStorage} = NativeModules; - -class SecureDataManager { - static async storeSecureData(key, data) { - try { - // Encrypt data before storage - const encrypted = await SecureStorage.encrypt(JSON.stringify(data)); - await SecureStorage.store(key, encrypted); - } catch (error) { - console.error('Failed to store secure data:', error); - throw error; - } - } - - static async retrieveSecureData(key) { - try { - const encrypted = await SecureStorage.retrieve(key); - if (!encrypted) return null; - - const decrypted = await SecureStorage.decrypt(encrypted); - return JSON.parse(decrypted); - } catch (error) { - console.error('Failed to retrieve secure data:', error); - throw error; - } - } -} -``` - -## Network Security - -### TLS Configuration - -Ensure proper TLS configuration for network requests: - -```javascript -// Use HTTPS for all network requests -const API_BASE_URL = 'https://api.example.com'; - -class SecureNetworking { - static async makeSecureRequest(endpoint, options = {}) { - const url = `${API_BASE_URL}${endpoint}`; - - const secureOptions = { - ...options, - // Ensure HTTPS - method: options.method || 'GET', - headers: { - 'Content-Type': 'application/json', - ...options.headers, - }, - }; - - // Add request validation - if (!url.startsWith('https://')) { - throw new Error('Only HTTPS requests are allowed'); - } - - try { - const response = await fetch(url, secureOptions); - - if (!response.ok) { - throw new Error(`HTTP ${response.status}: ${response.statusText}`); - } - - return await response.json(); - } catch (error) { - console.error('Network request failed:', error); - throw error; - } - } -} -``` - -### Certificate Pinning - -Implement certificate pinning for critical connections: - -```cpp -// Certificate pinning in native module -REACT_METHOD(MakePinnedRequest) -void MakePinnedRequest(std::string url, ReactPromise promise) noexcept { - try { - // Validate certificate against pinned certificate - if (!ValidateCertificatePinning(url)) { - promise.Reject("Certificate pinning validation failed"); - return; - } - - // Make secure request - auto result = MakeSecureHttpRequest(url); - promise.Resolve(result); - } - catch (...) { - promise.Reject("Request failed"); - } -} -``` - -## Common Security Pitfalls - -### Avoid These Patterns - -#### ❌ Insecure Random Number Generation - -```javascript -// Don't use Math.random() for security-sensitive operations -const insecureToken = Math.random().toString(36); -``` - -#### ✅ Use Cryptographically Secure Random - -```javascript -import {NativeModules} from 'react-native'; -const {WindowsSecurity} = NativeModules; - -const secureToken = await WindowsSecurity.generateSecureRandom(32); -``` - -#### ❌ Storing Sensitive Data in Plain Text - -```javascript -// Don't store sensitive data unencrypted -AsyncStorage.setItem('password', plainTextPassword); -``` - -#### ✅ Use Secure Storage - -```javascript -// Use encrypted storage for sensitive data -await SecureDataManager.storeSecureData('credentials', { - username, - password -}); -``` - -#### ❌ Insufficient Input Validation - -```cpp -// Don't trust user input -void ProcessInput(std::string input) { - // Direct usage without validation - DANGEROUS - ExecuteCommand(input); -} -``` - -#### ✅ Comprehensive Input Validation - -```cpp -// Validate and sanitize all inputs -void ProcessInput(std::string input) { - if (!IsValidInput(input)) { - throw SecurityException("Invalid input"); - } - - auto sanitized = SanitizeInput(input); - ExecuteCommand(sanitized); -} -``` - -### Security Testing - -#### Unit Tests for Security Functions - -```cpp -// Test security functions -TEST_CLASS(SecurityTests) { -public: - TEST_METHOD(TestInputValidation) { - // Test with valid input - ASSERT_TRUE(IsValidInput("normal_input")); - - // Test with malicious input - ASSERT_FALSE(IsValidInput("")); - ASSERT_FALSE(IsValidInput("'; DROP TABLE users; --")); - } - - TEST_METHOD(TestEncryption) { - std::string plaintext = "sensitive data"; - auto encrypted = EncryptData(plaintext); - auto decrypted = DecryptData(encrypted); - - ASSERT_EQ(plaintext, decrypted); - ASSERT_NE(plaintext, encrypted); - } -}; -``` - -### Security Monitoring - -#### Logging Security Events - -```cpp -class SecurityLogger { -public: - static void LogSecurityEvent(const std::string& event, - const std::string& details) { - // Log to Windows Event Log - auto eventLog = winrt::Windows::ApplicationModel::Core::CoreApplication::MainView() - .CoreWindow().Dispatcher(); - - // Log security events for monitoring - OutputDebugStringA(("SECURITY: " + event + " - " + details).c_str()); - } -}; -``` - -## Security Checklist - -### Development Phase - -- [ ] Input validation implemented for all user inputs -- [ ] Memory management uses RAII and smart pointers -- [ ] Error handling doesn't leak sensitive information -- [ ] Cryptographically secure random number generation -- [ ] Sensitive data encrypted before storage - -### Testing Phase - -- [ ] Security unit tests implemented -- [ ] Input validation tests with malicious inputs -- [ ] Encryption/decryption functionality tested -- [ ] Certificate validation tested -- [ ] WebView security configuration validated - -### Deployment Phase - -- [ ] HTTPS enforced for all network communications -- [ ] Certificate pinning implemented for critical services -- [ ] Content Security Policy configured for WebViews -- [ ] Sensitive information removed from production builds -- [ ] Security logging and monitoring enabled - ---- - -**Document Version**: 1.0 -**Last Updated**: October 14, 2025 -**Related**: [Security Configuration Guide](security-configuration.md) diff --git a/docs/security-configuration.md b/docs/security-configuration.md deleted file mode 100644 index 152baf02dd5..00000000000 --- a/docs/security-configuration.md +++ /dev/null @@ -1,360 +0,0 @@ -# Security Configuration Guide - -This document provides comprehensive security configuration guidance for React Native Windows development, covering build-time security settings, runtime configurations, and security best practices for SDL compliance. - -## Table of Contents - -- [Build Security Configuration](#build-security-configuration) -- [Runtime Security Configuration](#runtime-security-configuration) -- [Security Features and APIs](#security-features-and-apis) -- [Development Security Best Practices](#development-security-best-practices) -- [Security Testing](#security-testing) -- [SDL Compliance](#sdl-compliance) - -## Build Security Configuration - -### MSBuild Security Settings - -React Native Windows incorporates comprehensive security configurations through MSBuild property sheets in `vnext/PropertySheets/`. - -#### Core Security Flags - -The `React.Cpp.props` file enables essential security mitigations: - -```xml - - - - Guard - - - Spectre - - - ProgramDatabase - - - false - - -``` - -#### SDL Compiler Warnings - -The `Warnings.props` file enforces SDL-compliant warning levels: - -```xml - - - - true - - - Level4 - - - /permissive- %(AdditionalOptions) - - -``` - -#### SDL Mandatory Warnings - -React Native Windows enables SDL mandatory warnings (configured in `PropertySheets/Warnings.props`): - -- **C4287**: Unsigned/negative constant mismatch -- **C4365**: Signed/unsigned mismatch -- **C4388**: Signed/unsigned mismatch in comparison -- **C4545**: Expression before comma evaluates to function missing argument list -- **C4546**: Function call before comma missing argument list -- **C4547**: Operator before comma has no effect -- **C4549**: Operator before comma has no effect - -### Security Build Configuration - -#### Directory.Build.props Security Settings - -The root `Directory.Build.props` includes security-focused build configurations: - -- **Symbol Generation**: Enables PDB generation for security analysis -- **Platform Toolset**: Enforces modern, secure compiler versions -- **NuGet Security**: Secure package restore with lock files - -#### Azure DevOps Security Pipeline - -The `.ado/publish.yml` pipeline incorporates: - -1. **Symbol Publishing**: PublishSymbols@2 task for MSRC security response -2. **Security Scanning**: Integrated vulnerability detection -3. **Build Validation**: Security policy enforcement - -## Runtime Security Configuration - -### Platform Security Integration - -React Native Windows leverages Windows platform security: - -#### TLS and Network Security - -- **Platform TLS Enforcement**: Inherits Windows system TLS policies -- **WebView2 Security**: Automatic HTTPS enforcement and certificate validation -- **Secure Network Defaults**: Framework provides secure networking configurations - -#### Certificate Validation - -Certificate validation is handled automatically by the Windows platform: - -```javascript -// Certificate validation works automatically through Windows networking stack -// WebView2 enforces HTTPS and proper certificate validation -// No custom TLS bypass mechanisms are provided -``` - -### WebView Security - -React Native Windows uses WebView2 with comprehensive security controls: - -#### Sandboxing and Isolation - -- **Process Isolation**: WebView2 runs in separate security context -- **Origin Restrictions**: Prevents unauthorized cross-origin access -- **Content Security Policy**: Enforces security boundaries - -#### Security Configuration Example - -```cpp -// WebView2 security settings in Microsoft.ReactNative -webviewEnvironmentOptions.put_AdditionalBrowserArguments( - L"--disable-web-security=false --enable-features=msWebView2BrowserHitTesting" -); -``` - -## Security Features and APIs - -### Windows Security API Integration - -React Native Windows provides secure access to Windows security APIs through native modules: - -#### Cryptography APIs - -```javascript -// Access to Windows.Security.Cryptography through native bridge -import {NativeModules} from 'react-native'; - -// Example: Secure random number generation -const {WindowsSecurity} = NativeModules; -const randomBytes = await WindowsSecurity.generateRandom(32); - -// Example: Hash computation using platform APIs -const hash = await WindowsSecurity.computeHash('SHA256', data); -``` - -#### Credential Management - -```javascript -// Integration with Windows.Security.Credentials -const {WindowsCredentials} = NativeModules; - -// Secure credential storage -await WindowsCredentials.storeCredential({ - resource: 'MyApp', - userName: 'user@example.com', - password: 'securePassword' -}); -``` - -### Code Signature Verification - -React Native Windows implements signature verification for downloaded dependencies in `vnext/Scripts/rnw-dependencies.ps1`: - -```powershell -# Verify digital signature of downloaded files -$signature = Get-AuthenticodeSignature -FilePath $downloadedFile -if ($signature.Status -ne "Valid") { - throw "Invalid signature: File signature verification failed" -} - -# Ensure Microsoft signed content -if ($signature.SignerCertificate.Subject -notlike "*Microsoft*") { - throw "Invalid publisher: File must be signed by Microsoft" -} -``` - -## Development Security Best Practices - -### Secure Coding Guidelines - -#### Input Validation - -- **Validate All Inputs**: Implement comprehensive input validation in native modules -- **Sanitize Data**: Properly escape and sanitize user inputs before processing -- **Bounds Checking**: Ensure array and buffer bounds are validated - -#### Memory Safety - -- **RAII Patterns**: Use Resource Acquisition Is Initialization -- **Smart Pointers**: Prefer `std::unique_ptr` and `std::shared_ptr` over raw pointers -- **Buffer Overflow Protection**: Enabled through `/GS` compiler flag - -#### Error Handling - -- **Secure Error Messages**: Avoid exposing sensitive information in error messages -- **Exception Safety**: Implement proper exception handling with RAII -- **Security Logging**: Ensure logs don't contain sensitive data - -### Dependencies Security - -#### Package Management - -- **Vulnerability Scanning**: Automated scanning in CI/CD pipeline -- **Regular Updates**: Keep dependencies updated to latest secure versions -- **Lock Files**: Use package lock files for reproducible, secure builds - -#### Native Dependencies - -- **Code Signature Verification**: All native dependencies verified during download -- **Trusted Sources**: Download only from official Microsoft and trusted sources -- **Integrity Validation**: Verify checksums and digital signatures - -## Security Testing - -### Static Analysis - -Security testing is integrated into the build process: - -#### Compiler-Based Analysis - -- **Warning as Errors**: All security warnings treated as build failures -- **Static Analysis**: Integrated `/analyze` compiler flag for security analysis -- **Code Analysis**: PREfast security rule enforcement - -#### CI/CD Integration - -```yaml -# Example from .ado/publish.yml -- task: MSBuild@1 - inputs: - solution: 'vnext/Microsoft.ReactNative.sln' - msbuildArguments: '/p:RunCodeAnalysis=true /p:TreatWarningsAsErrors=true' -``` - -### Dynamic Testing - -#### Security Testing Framework - -- **Unit Tests**: Security-focused unit testing -- **Integration Tests**: Security boundary validation -- **Penetration Testing**: Regular security assessments - -## SDL Compliance - -React Native Windows maintains compliance with Microsoft Security Development Lifecycle requirements: - -### SDL Requirements Status - -#### ✅ Compiler Requirements (Policy: Microsoft.Security.CE.10019) - -- **Azure DevOps CI/CD**: Security-enabled build pipelines -- **MSBuild Security Flags**: Control Flow Guard, Spectre mitigation enabled -- **Symbol Publishing**: Integrated for Microsoft Security Response Center support -- **Static Analysis**: Security analysis integrated in build process - -#### ✅ TLS Implementation - -- **Platform TLS Enforcement**: Windows system-level TLS policies -- **WebView2 Security**: Automatic HTTPS and certificate validation -- **No Custom TLS Bypass**: Framework uses secure platform defaults - -#### ✅ Secret & Storage Management - -- **Windows.Security.Cryptography**: Platform cryptography API access -- **PasswordVault Integration**: Secure credential storage through Windows APIs -- **Enterprise Credential Support**: Windows enterprise credential integration - -#### ✅ Web Content Security - -- **WebView2 Sandboxing**: Proper content isolation and security boundaries -- **Content Security Policy**: Security policy enforcement -- **Origin Restrictions**: Prevents unauthorized cross-origin access - -#### ✅ Code Signature Verification (Policy: Microsoft.Security.CE.10121) - -- **Download Verification**: All downloads verified with digital signatures -- **Microsoft Publisher Validation**: Ensures content is Microsoft-signed -- **Integrity Checking**: Cryptographic integrity validation - -### Compliance Documentation - -Security compliance is documented through: - -1. **Evidence Collection**: Comprehensive security implementation documentation -2. **Risk Assessment**: Regular security risk evaluations -3. **Compliance Verification**: Systematic SDL requirement validation -4. **Security Attestation**: Formal security approval processes - -### Security Review Process - -#### Code Review Requirements - -1. **Security-Focused Reviews**: All security-sensitive code changes require security review -2. **Architecture Reviews**: Major changes undergo security architecture review -3. **Threat Modeling**: New features require threat modeling analysis -4. **Security Sign-off**: Security team approval for security-critical changes - -## Security Configuration Checklist - -### Build Configuration - -- [ ] Control Flow Guard enabled in `React.Cpp.props` -- [ ] Spectre mitigation enabled in `React.Cpp.props` -- [ ] Warnings as errors configured in `Warnings.props` -- [ ] SDL mandatory warnings enabled -- [ ] Symbol generation enabled for security analysis - -### Runtime Configuration - -- [ ] Platform TLS enforcement verified -- [ ] WebView2 security settings validated -- [ ] Certificate validation working properly -- [ ] Secure credential storage configured - -### Development Process - -- [ ] Security code reviews implemented -- [ ] Static analysis tools integrated in CI/CD -- [ ] Vulnerability scanning automated -- [ ] Security testing in build pipeline - -### Dependencies - -- [ ] Package vulnerability scanning enabled -- [ ] Code signature verification implemented in `rnw-dependencies.ps1` -- [ ] Trusted source validation configured -- [ ] Regular security updates scheduled - -## Additional Resources - -### Security Documentation - -- [Microsoft Security Development Lifecycle](https://www.microsoft.com/securityengineering/sdl) -- [Windows Security APIs](https://docs.microsoft.com/en-us/uwp/api/windows.security) -- [WebView2 Security Guide](https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/security) - -### React Native Windows Security Implementation - -- **MSBuild Configuration**: See `vnext/PropertySheets/` for security build settings -- **Security APIs**: See `vnext/Microsoft.ReactNative/Modules/` for Windows security API usage -- **CI/CD Security**: See `.ado/` directory for security pipeline configurations -- **Dependency Security**: See `vnext/Scripts/rnw-dependencies.ps1` for signature verification - -### Support and Contacts - -- **Security Issues**: Report security vulnerabilities to Microsoft Security Response Center (MSRC) -- **SDL Compliance**: Contact React Native Windows security team for compliance questions -- **Architecture Reviews**: Engage security architects for design reviews - ---- - -**Document Version**: 1.0 -**Last Updated**: October 14, 2025 -**SDL Compliance**: Microsoft.Security.CE.10119, Microsoft.Security.CE.10019, Microsoft.Security.CE.10121 diff --git a/docs/security-process.md b/docs/security-process.md deleted file mode 100644 index 1fb7c120598..00000000000 --- a/docs/security-process.md +++ /dev/null @@ -1,375 +0,0 @@ -# Security Review Process - -This document outlines the security review process for React Native Windows development, including security milestones, review procedures, and compliance verification. - -## Overview - -React Native Windows follows Microsoft Security Development Lifecycle (SDL) requirements for continuous security assurance. This process ensures all code changes undergo appropriate security review and validation. - -## Security Review Requirements - -### Code Review Security Gates - -All code changes must pass security review gates based on change classification: - -#### 1. Standard Code Changes - -- **Security Impact Assessment**: Automated security impact analysis -- **Peer Review**: Security-aware code review by team members -- **Static Analysis**: Automated security scanning in CI/CD pipeline -- **Approval Required**: Standard approval from code reviewers - -#### 2. Security-Sensitive Changes - -Changes that require enhanced security review: - -- Native module modifications accessing Windows security APIs -- WebView security configuration changes -- Cryptographic implementation changes -- Network security configuration modifications -- Build system security changes - -**Enhanced Review Process:** - -- **Security Architecture Review**: Security team review for design changes -- **Threat Modeling**: Analysis of security implications -- **Security Testing**: Additional security-focused testing requirements -- **Security Approval**: Explicit security team sign-off required - -#### 3. Critical Security Changes - -Changes with high security impact: - -- Authentication/authorization system changes -- Core security API modifications -- Security policy implementations -- Compliance-related changes - -**Critical Review Process:** - -- **Security Design Review**: Formal security architecture review -- **Comprehensive Threat Modeling**: Full threat analysis and mitigation planning -- **Security Testing**: Comprehensive security testing including penetration testing -- **Security Lead Approval**: Security lead approval required -- **Documentation**: Updated security documentation and compliance evidence - -### Security Milestone Requirements - -Security milestones are integrated into the development lifecycle: - -#### Design Phase - -- [ ] **Threat Model Created**: Comprehensive threat modeling for new features -- [ ] **Security Requirements Defined**: Clear security requirements documented -- [ ] **Security Architecture Review**: Security team review of design -- [ ] **Privacy Impact Assessment**: Privacy implications analyzed - -#### Implementation Phase - -- [ ] **Secure Coding Standards**: SDL coding standards followed -- [ ] **Security API Usage**: Proper use of Windows security APIs -- [ ] **Input Validation**: Comprehensive input validation implemented -- [ ] **Error Handling**: Secure error handling patterns implemented - -#### Testing Phase - -- [ ] **Security Unit Tests**: Security-focused unit tests implemented -- [ ] **Static Analysis Clean**: No security warnings in static analysis -- [ ] **Dynamic Security Testing**: Security testing passed -- [ ] **Vulnerability Assessment**: Security vulnerability scanning completed - -#### Release Phase - -- [ ] **Security Documentation**: Security documentation updated -- [ ] **Compliance Verification**: SDL compliance requirements verified -- [ ] **Security Sign-off**: Security team approval obtained -- [ ] **Incident Response Plan**: Security incident response procedures validated - -## Security Testing Requirements - -### Automated Security Testing - -Integrated security testing in CI/CD pipeline: - -#### Static Analysis - -```yaml -# Security static analysis in Azure DevOps pipeline -- task: MSBuild@1 - displayName: 'Build with Security Analysis' - inputs: - solution: 'vnext/Microsoft.ReactNative.sln' - msbuildArguments: > - /p:RunCodeAnalysis=true - /p:TreatWarningsAsErrors=true - /p:EnableSDLRecommendedRules=true -``` - -#### Security Scanning - -```yaml -# Vulnerability scanning -- task: ComponentGovernanceComponentDetection@0 - displayName: 'Component Detection' - inputs: - scanType: 'Register' - verbosity: 'Verbose' - alertWarningLevel: 'High' -``` - -### Manual Security Testing - -#### Security Test Cases - -1. **Input Validation Testing** - - Malicious input injection testing - - Boundary condition testing - - Format string vulnerability testing - -2. **Authentication Testing** - - Credential storage security testing - - Authentication bypass testing - - Session management testing - -3. **WebView Security Testing** - - Cross-site scripting (XSS) testing - - Content Security Policy validation - - Origin validation testing - -4. **Cryptography Testing** - - Encryption/decryption validation - - Key management testing - - Random number generation testing - -### Security Testing Documentation - -Security testing results must be documented: - -```markdown -## Security Test Report - -### Test Summary -- **Test Date**: [Date] -- **Test Scope**: [Scope] -- **Tester**: [Name] -- **Test Environment**: [Environment] - -### Test Results -- **Input Validation**: ✅ PASS -- **Authentication**: ✅ PASS -- **WebView Security**: ✅ PASS -- **Cryptography**: ✅ PASS - -### Issues Identified -- None - -### Security Approval -Approved by: [Security Team Member] -Date: [Date] -``` - -## Compliance Verification - -### SDL Compliance Checklist - -Regular verification of SDL compliance requirements: - -#### Build Security Compliance - -- [ ] **Control Flow Guard**: Enabled in build configuration -- [ ] **Spectre Mitigation**: Enabled for all native code -- [ ] **SDL Warnings**: All SDL mandatory warnings enabled as errors -- [ ] **Static Analysis**: Security analysis integrated in build process -- [ ] **Symbol Publishing**: Debug symbols published for security response - -#### Runtime Security Compliance - -- [ ] **TLS Enforcement**: Platform TLS enforcement validated -- [ ] **Certificate Validation**: Proper certificate validation implemented -- [ ] **Secure Storage**: Encrypted storage for sensitive data -- [ ] **WebView Security**: Secure WebView configuration validated - -#### Development Process Compliance - -- [ ] **Security Training**: Team security training completed -- [ ] **Security Reviews**: Security review process followed -- [ ] **Vulnerability Management**: Vulnerability response process established -- [ ] **Incident Response**: Security incident response procedures documented - -### Compliance Attestation Process - -Regular SDL compliance attestation: - -#### Quarterly Compliance Review - -1. **Evidence Collection**: Gather compliance evidence -2. **Gap Analysis**: Identify compliance gaps -3. **Remediation Planning**: Plan remediation for any gaps -4. **Attestation**: Formal compliance attestation - -#### Annual Security Assessment - -1. **Comprehensive Review**: Full security posture assessment -2. **Threat Model Update**: Update threat models -3. **Security Architecture Review**: Review security architecture -4. **Compliance Certification**: Annual compliance certification - -## Security Incident Response - -### Incident Classification - -Security incidents are classified by severity: - -#### Critical (P0) - -- Active exploitation of security vulnerability -- Data breach or exposure of sensitive information -- Complete system compromise - -**Response Time**: 2 hours -**Response Team**: Security lead, engineering lead, product manager - -#### High (P1) - -- Security vulnerability with high impact -- Potential for data exposure -- Security control bypass - -**Response Time**: 24 hours -**Response Team**: Security team member, engineering team - -#### Medium (P2) - -- Security vulnerability with medium impact -- Security policy violation -- Configuration issue with security implications - -**Response Time**: 72 hours -**Response Team**: Engineering team with security consultation - -#### Low (P3) - -- Minor security issue -- Security documentation gap -- Low-impact configuration issue - -**Response Time**: 1 week -**Response Team**: Engineering team - -### Incident Response Process - -1. **Detection and Reporting** - - Security monitoring systems - - Internal reporting - - External vulnerability reports - -2. **Initial Response** - - Incident classification - - Initial containment - - Stakeholder notification - -3. **Investigation** - - Root cause analysis - - Impact assessment - - Evidence collection - -4. **Remediation** - - Fix development - - Testing and validation - - Deployment coordination - -5. **Recovery** - - System restoration - - Monitoring enhancement - - Documentation update - -6. **Post-Incident Review** - - Lessons learned analysis - - Process improvement - - Prevention measures - -## Security Documentation Requirements - -### Security Documentation Updates - -Security documentation must be updated for: - -#### New Features - -- Security design documentation -- Threat model updates -- Security testing documentation -- User security guidance - -#### Security Changes - -- Security configuration updates -- API security documentation -- Security best practices updates -- Compliance documentation updates - -### Documentation Review Process - -1. **Technical Review**: Technical accuracy validation -2. **Security Review**: Security team review -3. **Compliance Review**: Compliance requirement validation -4. **Approval**: Final approval and publication - -## Security Training Requirements - -### Required Training - -All team members must complete: - -#### Initial Security Training - -- SDL fundamentals training -- Secure coding training -- Threat modeling training -- Security testing training - -#### Annual Refresher Training - -- Security update training -- New threat awareness training -- Compliance update training -- Incident response training - -### Role-Specific Training - -#### Developers - -- Secure coding practices -- Security API usage -- Vulnerability prevention -- Security testing techniques - -#### Security Team - -- Advanced threat modeling -- Security architecture -- Incident response -- Compliance management - -## Tools and Resources - -### Security Tools - -- **Static Analysis**: Visual Studio Code Analysis, PREfast -- **Dynamic Analysis**: Application Verifier, Dr. Memory -- **Vulnerability Scanning**: Component Governance, WhiteSource -- **Security Testing**: OWASP ZAP, Burp Suite - -### Documentation Resources - -- [Microsoft Security Development Lifecycle](https://www.microsoft.com/securityengineering/sdl) -- [SDL Process Guidance](https://www.microsoft.com/securityengineering/sdl/practices) -- [OWASP Security Testing Guide](https://owasp.org/www-project-web-security-testing-guide/) -- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework) - ---- - -**Document Version**: 1.0 -**Last Updated**: October 14, 2025 -**Process Owner**: React Native Windows Security Team -**Related Documents**: [Security Configuration Guide](security-configuration.md), [Security Best Practices](security-best-practices.md) diff --git a/docs/testing-createRnwApp.md b/docs/testing-createRnwApp.md deleted file mode 100644 index a6466ee14c3..00000000000 --- a/docs/testing-createRnwApp.md +++ /dev/null @@ -1,145 +0,0 @@ -# React Native Windows creaternwapp Testing Guide - -This document provides a comprehensive testing guide for validating React Native Windows creaternwapp functionality with both new architecture (Fabric) and old architecture (Paper/UWP). - -## Prerequisites - -1. Windows development environment with Visual Studio -2. Node.js and yarn installed -3. React Native Windows development dependencies -4. RNW_ROOT environment variable set (if using local development) - -## Test Scenarios - -The testing covers both stable and preview versions of React Native Windows: - -- **Stable Version**: Tests the latest stable release from npm -- **Preview Version**: Tests the latest preview release from npm - -### New Architecture (Fabric) Testing - -#### Debug Mode -```bash -# Step 1: Create new app with Fabric architecture -# For stable version: -creaternwapp.cmd /rnw latest TestAppFabricStable -# For preview version: -creaternwapp.cmd /rnw preview TestAppFabricPreview - -# Step 2: Navigate to app directory -cd TestAppFabric* - -# Step 3: Start Metro bundler -yarn start - -# Step 4: In a new terminal, build and run in debug mode -cd TestAppFabric* -yarn windows -``` - -#### Release Mode -```bash -# Using the same app created above, build in release mode -cd TestAppFabric* -yarn windows --release -``` - -### Old Architecture (Paper/UWP) Testing - -#### Debug Mode -```bash -# Step 1: Create new app with UWP/Paper architecture -# For stable version: -creaternwapp.cmd /rnw latest /t old/uwp-cpp-app TestAppPaperStable -# For preview version: -creaternwapp.cmd /rnw preview /t old/uwp-cpp-app TestAppPaperPreview - -# Step 2: Navigate to app directory -cd TestAppPaper* - -# Step 3: Start Metro bundler -yarn start - -# Step 4: In a new terminal, build and run in debug mode -cd TestAppPaper* -yarn windows -``` - -#### Release Mode -```bash -# Using the same app created above, build in release mode -cd TestAppPaper* -yarn windows --release -``` - -## Validation Checklist - -### App Creation Validation -- [ ] App directory is created successfully -- [ ] package.json contains correct react-native-windows version -- [ ] windows directory is created with project files -- [ ] Solution (.sln) and project files are present -- [ ] Dependencies are installed correctly - -### Build Validation -- [ ] Debug build completes without errors -- [ ] Release build completes without errors -- [ ] App launches successfully -- [ ] No critical warnings in build output -- [ ] Bundle creation works (yarn start) - -### Architecture-Specific Validation - -#### Fabric (New Architecture) -- [ ] Uses modern Fabric renderer -- [ ] Supports new architecture features -- [ ] Compatible with latest React Native patterns - -#### Paper/UWP (Old Architecture) -- [ ] Uses legacy Paper renderer -- [ ] UWP-specific features work correctly -- [ ] Compatible with existing UWP applications - -## Expected Outcomes - -1. **Successful App Creation**: Both architectures should create functional React Native Windows apps for both stable and preview versions -2. **Version Consistency**: All apps should use the correct react-native-windows version (stable or preview as requested) -3. **Build Success**: Both debug and release builds should complete successfully -4. **Runtime Functionality**: Apps should launch and display the default React Native screen - -## Troubleshooting - -### Common Issues -- **Build Failures**: Check Visual Studio components and Windows SDK versions -- **Version Conflicts**: Ensure clean environment and correct package versions -- **Network Issues**: May need to configure npm/yarn registries -- **Version Mismatch**: Verify npm registry has the expected stable/preview versions available - -### Debugging Steps -1. Check creaternwapp.cmd output for errors -2. Verify package.json dependencies -3. Review build logs for specific error messages -4. Ensure all prerequisites are met -5. Verify npm registry connectivity and version availability - -## Automation Notes - -This testing can be automated in CI/CD environments using: -- Windows-based build agents -- Verdaccio for package registry testing -- MSBuild for compilation validation -- Automated deployment testing -- Npm registry queries to verify version availability - -The automated tests now include: -- **Stable Version Tests**: Automatically fetch and test the latest stable version from npm -- **Preview Version Tests**: Automatically fetch and test the latest preview version from npm -- **Version Validation**: Verify that the fetched versions exist and have correct dependencies - -## Documentation - -For additional information, see: -- React Native Windows documentation -- creaternwapp.cmd script source -- Template documentation in vnext/templates/ -- NPM package versions and tags for react-native-windows \ No newline at end of file diff --git a/packages/@react-native-windows/codegen/Document.md b/packages/@react-native-windows/codegen/Document.md index 527efe2fc0b..060b9577024 100644 --- a/packages/@react-native-windows/codegen/Document.md +++ b/packages/@react-native-windows/codegen/Document.md @@ -56,7 +56,7 @@ export default TurboModuleRegistry.getEnforcing('SampleTurboModule'); Checkout the following example: - Flow definition: [NativeDialogManagerWindows.js](https://github.com/microsoft/react-native-windows/blob/main/vnext/src-win/Libraries/NativeModules/specs/NativeDialogManagerWindows.js) -- Generated spec file: [NativeDialogManagerWindowsSpec.g.h](https://github.com/microsoft/react-native-windows/blob/main/vnext/codegen/NativeDialogManagerWindowsSpec.g.h) +- Generated spec file: [NativeDialogManagerWindowsSpec.g.h](https://github.com/microsoft/react-native-windows/blob/0.81-stable/vnext/codegen/NativeDialogManagerWindowsSpec.g.h) - Implementation: [AlertModule.h](https://github.com/microsoft/react-native-windows/blob/main/vnext/Microsoft.ReactNative/Modules/AlertModule.h) A TurboModule implemetation starts with: diff --git a/vnext/Microsoft.ReactNative.NewArch.Publish.slnf b/vnext/Microsoft.ReactNative.NewArch.Publish.slnf new file mode 100644 index 00000000000..39839fab846 --- /dev/null +++ b/vnext/Microsoft.ReactNative.NewArch.Publish.slnf @@ -0,0 +1,13 @@ +{ + "solution": { + "path": "Microsoft.ReactNative.NewArch.sln", + "projects": [ + "Common\\Common.vcxproj", + "Folly\\Folly.vcxproj", + "fmt\\fmt.vcxproj", + "Microsoft.ReactNative\\Microsoft.ReactNative.vcxproj", + "Microsoft.ReactNative.CsWinRT\\Microsoft.ReactNative.CsWinRT.csproj", + "ReactCommon\\ReactCommon.vcxproj" + ] + } +} diff --git a/vnext/PropertySheets/CIBuildOptimizations.props b/vnext/PropertySheets/CIBuildOptimizations.props new file mode 100644 index 00000000000..61d0244f890 --- /dev/null +++ b/vnext/PropertySheets/CIBuildOptimizations.props @@ -0,0 +1,29 @@ + + + + + false + false + false + + + + false + false + %(AdditionalOptions) /MP + + + diff --git a/vnext/ReactWindows-Desktop.Publish.slnf b/vnext/ReactWindows-Desktop.Publish.slnf new file mode 100644 index 00000000000..0261a90d017 --- /dev/null +++ b/vnext/ReactWindows-Desktop.Publish.slnf @@ -0,0 +1,14 @@ +{ + "solution": { + "path": "ReactWindows-Desktop.sln", + "projects": [ + "Common\\Common.vcxproj", + "Desktop\\React.Windows.Desktop.vcxproj", + "Desktop.DLL\\React.Windows.Desktop.DLL.vcxproj", + "Folly\\Folly.vcxproj", + "FollyWin32\\FollyWin32.vcxproj", + "ReactCommon\\ReactCommon.vcxproj", + "fmt\\fmt.vcxproj" + ] + } +} diff --git a/vnext/Scripts/OfficeReact.Win32.nuspec b/vnext/Scripts/OfficeReact.Win32.nuspec index 1c3126d1346..9ea60a4f687 100644 --- a/vnext/Scripts/OfficeReact.Win32.nuspec +++ b/vnext/Scripts/OfficeReact.Win32.nuspec @@ -28,11 +28,6 @@ - - - - - @@ -62,12 +57,6 @@ - - - - - -