@evomap/evolver-adapter-public 2.0.37 → 2.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/credentialStore.d.ts +2 -1
- package/dist/auth/credentialStore.js +46 -358
- package/dist/auth/windowsPowerShell.d.ts +2 -3
- package/dist/auth/windowsPowerShell.js +2 -91
- package/dist/hubCapability.d.ts +3 -1
- package/dist/hubCapability.js +51 -36
- package/dist/hubFetch.d.ts +2 -0
- package/dist/hubFetch.js +23 -20
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/recipeExecution.d.ts +4 -0
- package/dist/recipeExecution.js +100 -0
- package/dist/wireMap.js +2 -0
- package/package.json +3 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { linkSync, renameSync } from 'node:fs';
|
|
2
|
-
import
|
|
2
|
+
import { hub } from '@evomap/evolver-core';
|
|
3
3
|
export interface CredentialStoreOptions {
|
|
4
4
|
/**
|
|
5
5
|
* Test seam for the Windows policy; defaults to the current platform.
|
|
@@ -86,6 +86,7 @@ export declare class CredentialStore {
|
|
|
86
86
|
private unlinkIfSameFile;
|
|
87
87
|
private secureWindowsDirectory;
|
|
88
88
|
private secureWindowsFile;
|
|
89
|
+
private assertWindowsFileIdentity;
|
|
89
90
|
private clearDarwinAcl;
|
|
90
91
|
private assertSafeDarwinAncestor;
|
|
91
92
|
private assertTrustedDarwinFile;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto';
|
|
2
2
|
import { execFileSync } from 'node:child_process';
|
|
3
3
|
import { constants, closeSync, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
4
|
-
import { basename, dirname, resolve
|
|
5
|
-
import {
|
|
4
|
+
import { basename, dirname, resolve } from 'node:path';
|
|
5
|
+
import { hub, util } from '@evomap/evolver-core';
|
|
6
|
+
import { windowsAclFailureDetail } from './windowsPowerShell.js';
|
|
6
7
|
const DIRECTORY_MODE = 0o700;
|
|
7
8
|
const FILE_MODE = 0o600;
|
|
8
9
|
export class CredentialStoreError extends Error {
|
|
@@ -29,7 +30,7 @@ export class CredentialStore {
|
|
|
29
30
|
this.path = resolve(path);
|
|
30
31
|
this.platform = options.platform ?? process.platform;
|
|
31
32
|
this.windowsAclOps = this.platform === 'win32'
|
|
32
|
-
? (options.windowsAclOps ??
|
|
33
|
+
? (options.windowsAclOps ?? createWindowsCredentialAclOps())
|
|
33
34
|
: undefined;
|
|
34
35
|
this.darwinAclReader = options.darwinAclReader ?? readDarwinAcl;
|
|
35
36
|
this.windowsParentStateReader = options.windowsParentStateReader ?? parentSecurityStates;
|
|
@@ -170,9 +171,9 @@ export class CredentialStore {
|
|
|
170
171
|
}
|
|
171
172
|
return false;
|
|
172
173
|
}
|
|
173
|
-
this.verifySavedFile(temporaryIdentity);
|
|
174
174
|
if (!replaceExisting)
|
|
175
175
|
this.unlinkIfSameFile(temporaryPath, temporaryIdentity);
|
|
176
|
+
this.verifySavedFile(temporaryIdentity);
|
|
176
177
|
temporaryIdentity = null;
|
|
177
178
|
this.syncDirectory(directory);
|
|
178
179
|
return true;
|
|
@@ -330,12 +331,15 @@ export class CredentialStore {
|
|
|
330
331
|
}
|
|
331
332
|
}
|
|
332
333
|
openCredentialFile() {
|
|
333
|
-
const
|
|
334
|
-
if (!
|
|
334
|
+
const entry = safeLstat(this.path);
|
|
335
|
+
if (!entry)
|
|
335
336
|
return null;
|
|
336
|
-
if (
|
|
337
|
+
if (entry.isSymbolicLink() || !entry.isFile()) {
|
|
337
338
|
throw new CredentialStoreError('credential entry is a symlink or not a regular file');
|
|
338
339
|
}
|
|
340
|
+
const before = credentialFileStat(this.path);
|
|
341
|
+
if (before.nlink !== 1n)
|
|
342
|
+
throw new CredentialStoreError('credential entry has multiple hardlinks');
|
|
339
343
|
let fd;
|
|
340
344
|
try {
|
|
341
345
|
fd = openSync(this.path, constants.O_RDONLY | optionalConstant('O_NOFOLLOW') | optionalConstant('O_NONBLOCK'));
|
|
@@ -349,8 +353,9 @@ export class CredentialStore {
|
|
|
349
353
|
}
|
|
350
354
|
try {
|
|
351
355
|
const opened = bigFstat(fd);
|
|
352
|
-
const after =
|
|
356
|
+
const after = credentialFileStat(this.path);
|
|
353
357
|
if (!opened.isFile() || after.isSymbolicLink() || !after.isFile() ||
|
|
358
|
+
opened.nlink !== 1n || after.nlink !== 1n ||
|
|
354
359
|
!sameIdentity(before, opened) || !sameIdentity(opened, after)) {
|
|
355
360
|
throw new CredentialStoreError('credential entry changed during validation');
|
|
356
361
|
}
|
|
@@ -398,13 +403,7 @@ export class CredentialStore {
|
|
|
398
403
|
catch (cause) {
|
|
399
404
|
throw windowsCredentialStoreError('Windows credential file ACL is not trusted', cause);
|
|
400
405
|
}
|
|
401
|
-
|
|
402
|
-
const fdStat = bigFstat(fd);
|
|
403
|
-
if (pathStat.isSymbolicLink() || !pathStat.isFile() || !fdStat.isFile() ||
|
|
404
|
-
!sameIdentity(pathStat, identity) || !sameIdentity(fdStat, identity)) {
|
|
405
|
-
throw new CredentialStoreError('credential file changed during read-only ACL validation');
|
|
406
|
-
}
|
|
407
|
-
return fdStat;
|
|
406
|
+
return this.assertWindowsFileIdentity(this.path, fd, identity);
|
|
408
407
|
}
|
|
409
408
|
if (stat.uid !== BigInt(currentUid())) {
|
|
410
409
|
throw new CredentialStoreError('credential file is not owned by the current user');
|
|
@@ -493,7 +492,9 @@ export class CredentialStore {
|
|
|
493
492
|
}
|
|
494
493
|
unlinkIfSameFile(path, identity) {
|
|
495
494
|
const stat = safeLstat(path);
|
|
496
|
-
if (!stat || stat.isSymbolicLink() || !stat.isFile()
|
|
495
|
+
if (!stat || stat.isSymbolicLink() || !stat.isFile())
|
|
496
|
+
return;
|
|
497
|
+
if (!sameIdentity(credentialFileStat(path), identity))
|
|
497
498
|
return;
|
|
498
499
|
unlinkSync(path);
|
|
499
500
|
}
|
|
@@ -538,6 +539,7 @@ export class CredentialStore {
|
|
|
538
539
|
catch (cause) {
|
|
539
540
|
throw windowsCredentialStoreError('Windows credential file ACL is not trusted', cause);
|
|
540
541
|
}
|
|
542
|
+
this.assertWindowsFileIdentity(path, fd, identity);
|
|
541
543
|
if (isCredentialPath && this.securedCredentialState &&
|
|
542
544
|
sameSecurityState(this.securedCredentialState, before))
|
|
543
545
|
return;
|
|
@@ -547,14 +549,19 @@ export class CredentialStore {
|
|
|
547
549
|
catch (cause) {
|
|
548
550
|
throw windowsCredentialStoreError('Windows file ACL could not be secured', cause);
|
|
549
551
|
}
|
|
550
|
-
const
|
|
552
|
+
const fdStat = this.assertWindowsFileIdentity(path, fd, identity);
|
|
553
|
+
if (isCredentialPath)
|
|
554
|
+
this.securedCredentialState = securityStateOf(fdStat);
|
|
555
|
+
}
|
|
556
|
+
assertWindowsFileIdentity(path, fd, identity) {
|
|
557
|
+
const pathStat = credentialFileStat(path);
|
|
551
558
|
const fdStat = bigFstat(fd);
|
|
552
559
|
if (pathStat.isSymbolicLink() || !pathStat.isFile() || !fdStat.isFile() ||
|
|
560
|
+
pathStat.nlink !== 1n || fdStat.nlink !== 1n ||
|
|
553
561
|
!sameIdentity(pathStat, identity) || !sameIdentity(fdStat, identity)) {
|
|
554
|
-
throw new CredentialStoreError('credential file changed
|
|
562
|
+
throw new CredentialStoreError('credential file changed during Windows ACL validation');
|
|
555
563
|
}
|
|
556
|
-
|
|
557
|
-
this.securedCredentialState = securityStateOf(fdStat);
|
|
564
|
+
return fdStat;
|
|
558
565
|
}
|
|
559
566
|
clearDarwinAcl(fd, identity, kind) {
|
|
560
567
|
if (this.platform !== 'darwin')
|
|
@@ -700,347 +707,17 @@ export class CredentialStore {
|
|
|
700
707
|
return this.platform !== 'win32';
|
|
701
708
|
}
|
|
702
709
|
}
|
|
703
|
-
function
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
}
|
|
707
|
-
const WINDOWS_ACL_SCRIPT = String.raw `
|
|
708
|
-
$ErrorActionPreference = 'Stop'
|
|
709
|
-
# Progress records can be serialized as CLIXML onto redirected stderr and
|
|
710
|
-
# obscure the actual failure. Suppress them so stderr carries only real errors.
|
|
711
|
-
$ProgressPreference = 'SilentlyContinue'
|
|
712
|
-
|
|
713
|
-
function ConvertTo-OneLineAclDiagnostic([object]$Value) {
|
|
714
|
-
if ($null -eq $Value) { return '' }
|
|
715
|
-
return ([string]$Value -replace '[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+', ' ').Trim()
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
function Throw-CredentialAclFailure(
|
|
719
|
-
[string]$Reason,
|
|
720
|
-
[string]$Path = '',
|
|
721
|
-
[string]$Sid = '',
|
|
722
|
-
[object]$Rights = $null,
|
|
723
|
-
[string]$Principal = ''
|
|
724
|
-
) {
|
|
725
|
-
$parts = @($Reason)
|
|
726
|
-
$safePath = ConvertTo-OneLineAclDiagnostic $Path
|
|
727
|
-
$safeSid = ConvertTo-OneLineAclDiagnostic $Sid
|
|
728
|
-
$safeRights = ConvertTo-OneLineAclDiagnostic $Rights
|
|
729
|
-
$safePrincipal = ConvertTo-OneLineAclDiagnostic $Principal
|
|
730
|
-
if (-not [string]::IsNullOrWhiteSpace($safePath)) { $parts += ('path=' + $safePath) }
|
|
731
|
-
if (-not [string]::IsNullOrWhiteSpace($safeSid)) { $parts += ('sid=' + $safeSid) }
|
|
732
|
-
if (-not [string]::IsNullOrWhiteSpace($safePrincipal)) { $parts += ('principal=' + $safePrincipal) }
|
|
733
|
-
if (-not [string]::IsNullOrWhiteSpace($safeRights)) { $parts += ('rights=' + $safeRights) }
|
|
734
|
-
throw ($parts -join '; ')
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
# Windows PowerShell can serialize ordinary error-stream writes as CLIXML when
|
|
738
|
-
# stderr is redirected. Write the terminating exception directly to native stderr so
|
|
739
|
-
# Node receives the actionable message rather than only a serialized record.
|
|
740
|
-
trap {
|
|
741
|
-
$message = ConvertTo-OneLineAclDiagnostic $_.Exception.Message
|
|
742
|
-
if ([string]::IsNullOrWhiteSpace($message)) { $message = 'Credential ACL check failed' }
|
|
743
|
-
[Console]::Error.WriteLine($message)
|
|
744
|
-
exit 1
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
$Target = [Environment]::GetEnvironmentVariable('EVOMAP_CREDENTIAL_ACL_TARGET', 'Process')
|
|
748
|
-
$Kind = [Environment]::GetEnvironmentVariable('EVOMAP_CREDENTIAL_ACL_KIND', 'Process')
|
|
749
|
-
if ([string]::IsNullOrEmpty($Target) -or
|
|
750
|
-
($Kind -ne 'assert-parent' -and $Kind -ne 'assert-create-parent' -and
|
|
751
|
-
$Kind -ne 'assert-file' -and $Kind -ne 'directory' -and $Kind -ne 'file')) {
|
|
752
|
-
throw 'Invalid credential ACL input'
|
|
753
|
-
}
|
|
754
|
-
$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
755
|
-
$trustedSids = @(
|
|
756
|
-
$sid.Value,
|
|
757
|
-
'S-1-5-18',
|
|
758
|
-
'S-1-5-32-544',
|
|
759
|
-
'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'
|
|
760
|
-
)
|
|
761
|
-
$dangerousRights = [System.Security.AccessControl.FileSystemRights](
|
|
762
|
-
[System.Security.AccessControl.FileSystemRights]::Delete -bor
|
|
763
|
-
[System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor
|
|
764
|
-
[System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor
|
|
765
|
-
[System.Security.AccessControl.FileSystemRights]::TakeOwnership
|
|
766
|
-
)
|
|
767
|
-
$dangerousFileRights = [System.Security.AccessControl.FileSystemRights](
|
|
768
|
-
[System.Security.AccessControl.FileSystemRights]::WriteData -bor
|
|
769
|
-
[System.Security.AccessControl.FileSystemRights]::AppendData -bor
|
|
770
|
-
[System.Security.AccessControl.FileSystemRights]::WriteAttributes -bor
|
|
771
|
-
[System.Security.AccessControl.FileSystemRights]::WriteExtendedAttributes -bor
|
|
772
|
-
[System.Security.AccessControl.FileSystemRights]::Delete -bor
|
|
773
|
-
[System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor
|
|
774
|
-
[System.Security.AccessControl.FileSystemRights]::TakeOwnership
|
|
775
|
-
)
|
|
776
|
-
|
|
777
|
-
function Assert-TrustedParent([string]$ParentPath, [bool]$StrictCreate) {
|
|
778
|
-
$full = [System.IO.Path]::GetFullPath($ParentPath)
|
|
779
|
-
$root = [System.IO.Path]::GetPathRoot($full)
|
|
780
|
-
if ([string]::IsNullOrEmpty($root) -or $root -notmatch '^[A-Za-z]:\\$') {
|
|
781
|
-
Throw-CredentialAclFailure -Reason 'Credential parent must be on a local drive' -Path $full
|
|
782
|
-
}
|
|
783
|
-
if ([System.IO.DriveInfo]::new($root).DriveType -ne [System.IO.DriveType]::Fixed) {
|
|
784
|
-
Throw-CredentialAclFailure -Reason 'Credential parent must be on a fixed local drive' -Path $full
|
|
785
|
-
}
|
|
786
|
-
$current = $root
|
|
787
|
-
$relative = $full.Substring($root.Length)
|
|
788
|
-
$segments = $relative.Split(
|
|
789
|
-
[char[]]@([System.IO.Path]::DirectorySeparatorChar, [System.IO.Path]::AltDirectorySeparatorChar),
|
|
790
|
-
[System.StringSplitOptions]::RemoveEmptyEntries
|
|
791
|
-
)
|
|
792
|
-
$paths = @($root)
|
|
793
|
-
foreach ($segment in $segments) {
|
|
794
|
-
$current = [System.IO.Path]::Combine($current, $segment)
|
|
795
|
-
$paths += $current
|
|
796
|
-
}
|
|
797
|
-
$trimSeparators = [char[]]@(
|
|
798
|
-
[System.IO.Path]::DirectorySeparatorChar,
|
|
799
|
-
[System.IO.Path]::AltDirectorySeparatorChar
|
|
800
|
-
)
|
|
801
|
-
$finalParent = $full.TrimEnd($trimSeparators)
|
|
802
|
-
foreach ($current in $paths) {
|
|
803
|
-
$isCreateParent = $StrictCreate -and [string]::Equals(
|
|
804
|
-
$current.TrimEnd($trimSeparators),
|
|
805
|
-
$finalParent,
|
|
806
|
-
[System.StringComparison]::OrdinalIgnoreCase
|
|
807
|
-
)
|
|
808
|
-
$attributes = [System.IO.File]::GetAttributes($current)
|
|
809
|
-
if ((($attributes -band [System.IO.FileAttributes]::Directory) -eq 0) -or
|
|
810
|
-
(($attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0)) {
|
|
811
|
-
Throw-CredentialAclFailure -Reason 'Credential parent contains a reparse point or non-directory' -Path $current
|
|
812
|
-
}
|
|
813
|
-
$parentAcl = [System.IO.Directory]::GetAccessControl($current)
|
|
814
|
-
$ownerSid = $parentAcl.GetOwner([System.Security.Principal.SecurityIdentifier])
|
|
815
|
-
if ($trustedSids -notcontains $ownerSid.Value) {
|
|
816
|
-
Throw-CredentialAclFailure -Reason 'Credential parent has an untrusted owner' -Path $current -Sid $ownerSid.Value
|
|
817
|
-
}
|
|
818
|
-
$parentRules = @($parentAcl.GetAccessRules(
|
|
819
|
-
$true,
|
|
820
|
-
$true,
|
|
821
|
-
[System.Security.Principal.SecurityIdentifier]
|
|
822
|
-
))
|
|
823
|
-
foreach ($parentRule in $parentRules) {
|
|
824
|
-
if ($parentRule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) {
|
|
825
|
-
continue
|
|
826
|
-
}
|
|
827
|
-
$rights = $parentRule.FileSystemRights
|
|
828
|
-
$inheritOnly = (($parentRule.PropagationFlags -band
|
|
829
|
-
[System.Security.AccessControl.PropagationFlags]::InheritOnly) -ne 0)
|
|
830
|
-
$containerInherit = (($parentRule.InheritanceFlags -band
|
|
831
|
-
[System.Security.AccessControl.InheritanceFlags]::ContainerInherit) -ne 0)
|
|
832
|
-
$objectInherit = (($parentRule.InheritanceFlags -band
|
|
833
|
-
[System.Security.AccessControl.InheritanceFlags]::ObjectInherit) -ne 0)
|
|
834
|
-
$hasGranularDanger = (($rights -band $dangerousRights) -ne 0)
|
|
835
|
-
$hasCreateDanger = (($rights -band (
|
|
836
|
-
[System.Security.AccessControl.FileSystemRights]::CreateDirectories -bor
|
|
837
|
-
[System.Security.AccessControl.FileSystemRights]::CreateFiles
|
|
838
|
-
)) -ne 0)
|
|
839
|
-
$hasCompositeDanger =
|
|
840
|
-
(($rights -band [System.Security.AccessControl.FileSystemRights]::Write) -eq
|
|
841
|
-
[System.Security.AccessControl.FileSystemRights]::Write) -or
|
|
842
|
-
(($rights -band [System.Security.AccessControl.FileSystemRights]::Modify) -eq
|
|
843
|
-
[System.Security.AccessControl.FileSystemRights]::Modify) -or
|
|
844
|
-
(($rights -band [System.Security.AccessControl.FileSystemRights]::FullControl) -eq
|
|
845
|
-
[System.Security.AccessControl.FileSystemRights]::FullControl)
|
|
846
|
-
if ($inheritOnly) {
|
|
847
|
-
$dangerousGrant = $isCreateParent -and ($containerInherit -or $objectInherit) -and
|
|
848
|
-
($hasGranularDanger -or $hasCreateDanger -or $hasCompositeDanger)
|
|
849
|
-
} else {
|
|
850
|
-
$dangerousGrant = $hasGranularDanger -or ($isCreateParent -and $hasCreateDanger)
|
|
851
|
-
}
|
|
852
|
-
if (-not $dangerousGrant) { continue }
|
|
853
|
-
$parentRuleSid = $parentRule.IdentityReference
|
|
854
|
-
if (-not ($parentRuleSid -is [System.Security.Principal.SecurityIdentifier])) {
|
|
855
|
-
Throw-CredentialAclFailure -Reason 'Credential parent contains an unresolvable write principal' -Path $current -Principal $parentRule.IdentityReference.Value -Rights $rights
|
|
856
|
-
}
|
|
857
|
-
if ($trustedSids -notcontains $parentRuleSid.Value) {
|
|
858
|
-
Throw-CredentialAclFailure -Reason 'Credential parent grants write access to an untrusted principal' -Path $current -Sid $parentRuleSid.Value -Rights $rights
|
|
859
|
-
}
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
function Assert-TrustedFile([string]$FilePath) {
|
|
865
|
-
$attributes = [System.IO.File]::GetAttributes($FilePath)
|
|
866
|
-
if ((($attributes -band [System.IO.FileAttributes]::Directory) -ne 0) -or
|
|
867
|
-
(($attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0)) {
|
|
868
|
-
Throw-CredentialAclFailure -Reason 'Credential file is a reparse point or not a regular file' -Path $FilePath
|
|
869
|
-
}
|
|
870
|
-
$fileAcl = [System.IO.File]::GetAccessControl($FilePath)
|
|
871
|
-
$ownerSid = $fileAcl.GetOwner([System.Security.Principal.SecurityIdentifier])
|
|
872
|
-
if ($trustedSids -notcontains $ownerSid.Value) {
|
|
873
|
-
Throw-CredentialAclFailure -Reason 'Credential file has an untrusted owner' -Path $FilePath -Sid $ownerSid.Value
|
|
874
|
-
}
|
|
875
|
-
$fileRules = @($fileAcl.GetAccessRules(
|
|
876
|
-
$true,
|
|
877
|
-
$true,
|
|
878
|
-
[System.Security.Principal.SecurityIdentifier]
|
|
879
|
-
))
|
|
880
|
-
foreach ($fileRule in $fileRules) {
|
|
881
|
-
if ($fileRule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) {
|
|
882
|
-
continue
|
|
883
|
-
}
|
|
884
|
-
$rights = $fileRule.FileSystemRights
|
|
885
|
-
$hasGranularDanger = (($rights -band $dangerousFileRights) -ne 0)
|
|
886
|
-
$hasCompositeDanger =
|
|
887
|
-
(($rights -band [System.Security.AccessControl.FileSystemRights]::Write) -eq
|
|
888
|
-
[System.Security.AccessControl.FileSystemRights]::Write) -or
|
|
889
|
-
(($rights -band [System.Security.AccessControl.FileSystemRights]::Modify) -eq
|
|
890
|
-
[System.Security.AccessControl.FileSystemRights]::Modify) -or
|
|
891
|
-
(($rights -band [System.Security.AccessControl.FileSystemRights]::FullControl) -eq
|
|
892
|
-
[System.Security.AccessControl.FileSystemRights]::FullControl)
|
|
893
|
-
if (-not ($hasGranularDanger -or $hasCompositeDanger)) { continue }
|
|
894
|
-
$fileRuleSid = $fileRule.IdentityReference
|
|
895
|
-
if (-not ($fileRuleSid -is [System.Security.Principal.SecurityIdentifier])) {
|
|
896
|
-
Throw-CredentialAclFailure -Reason 'Credential file contains an unresolvable write principal' -Path $FilePath -Principal $fileRule.IdentityReference.Value -Rights $rights
|
|
897
|
-
}
|
|
898
|
-
if ($trustedSids -notcontains $fileRuleSid.Value) {
|
|
899
|
-
Throw-CredentialAclFailure -Reason 'Credential file grants write access to an untrusted principal' -Path $FilePath -Sid $fileRuleSid.Value -Rights $rights
|
|
710
|
+
function createWindowsCredentialAclOps() {
|
|
711
|
+
try {
|
|
712
|
+
return new hub.PowerShellWindowsAclOps();
|
|
900
713
|
}
|
|
901
|
-
|
|
902
|
-
}
|
|
903
|
-
|
|
904
|
-
function Test-CanonicalCredentialAcl(
|
|
905
|
-
[System.Security.AccessControl.FileSystemSecurity]$CandidateAcl,
|
|
906
|
-
[System.Security.Principal.SecurityIdentifier]$ExpectedOwner,
|
|
907
|
-
[System.Security.AccessControl.InheritanceFlags]$ExpectedInheritance
|
|
908
|
-
) {
|
|
909
|
-
try {
|
|
910
|
-
$candidateRules = @($CandidateAcl.GetAccessRules(
|
|
911
|
-
$true,
|
|
912
|
-
$true,
|
|
913
|
-
[System.Security.Principal.SecurityIdentifier]
|
|
914
|
-
))
|
|
915
|
-
if (-not $CandidateAcl.AreAccessRulesProtected -or $candidateRules.Count -ne 1) {
|
|
916
|
-
return $false
|
|
714
|
+
catch (cause) {
|
|
715
|
+
throw new CredentialStoreError(cause instanceof Error ? cause.message : 'Windows ACL policy is unavailable', { cause });
|
|
917
716
|
}
|
|
918
|
-
$candidateOwner = $CandidateAcl.GetOwner([System.Security.Principal.SecurityIdentifier])
|
|
919
|
-
$candidateRule = $candidateRules[0]
|
|
920
|
-
$candidateRuleSid = $candidateRule.IdentityReference
|
|
921
|
-
return (
|
|
922
|
-
$candidateOwner.Value -eq $ExpectedOwner.Value -and
|
|
923
|
-
$candidateRuleSid.Value -eq $ExpectedOwner.Value -and
|
|
924
|
-
$candidateRule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and
|
|
925
|
-
$candidateRule.FileSystemRights -eq [System.Security.AccessControl.FileSystemRights]::FullControl -and
|
|
926
|
-
$candidateRule.InheritanceFlags -eq $ExpectedInheritance -and
|
|
927
|
-
$candidateRule.PropagationFlags -eq [System.Security.AccessControl.PropagationFlags]::None -and
|
|
928
|
-
-not $candidateRule.IsInherited
|
|
929
|
-
)
|
|
930
|
-
} catch {
|
|
931
|
-
return $false
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
if ($Kind -eq 'assert-parent' -or $Kind -eq 'assert-create-parent') {
|
|
936
|
-
# Existing entries only require protection against replacement. Immediately
|
|
937
|
-
# before mkdir, also reject principals that could atomically squat the name.
|
|
938
|
-
Assert-TrustedParent $Target ($Kind -eq 'assert-create-parent')
|
|
939
|
-
exit 0
|
|
940
717
|
}
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
# and before trusting file content. Do not migrate unsafe grants in place.
|
|
945
|
-
Assert-TrustedFile $Target
|
|
946
|
-
exit 0
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
$expectedInheritance = if ($Kind -eq 'directory') {
|
|
950
|
-
[System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
|
|
951
|
-
} else {
|
|
952
|
-
[System.Security.AccessControl.InheritanceFlags]::None
|
|
953
|
-
}
|
|
954
|
-
$acl = if ($Kind -eq 'directory') {
|
|
955
|
-
[System.IO.Directory]::GetAccessControl($Target)
|
|
956
|
-
} else {
|
|
957
|
-
[System.IO.File]::GetAccessControl($Target)
|
|
958
|
-
}
|
|
959
|
-
if (Test-CanonicalCredentialAcl $acl $sid $expectedInheritance) {
|
|
960
|
-
exit 0
|
|
961
|
-
}
|
|
962
|
-
$acl.SetOwner($sid)
|
|
963
|
-
$acl.SetAccessRuleProtection($true, $false)
|
|
964
|
-
foreach ($rule in @($acl.GetAccessRules(
|
|
965
|
-
$true,
|
|
966
|
-
$true,
|
|
967
|
-
[System.Security.Principal.SecurityIdentifier]
|
|
968
|
-
))) { [void]$acl.RemoveAccessRuleSpecific($rule) }
|
|
969
|
-
$access = [System.Security.AccessControl.FileSystemAccessRule]::new(
|
|
970
|
-
$sid,
|
|
971
|
-
[System.Security.AccessControl.FileSystemRights]::FullControl,
|
|
972
|
-
$expectedInheritance,
|
|
973
|
-
[System.Security.AccessControl.PropagationFlags]::None,
|
|
974
|
-
[System.Security.AccessControl.AccessControlType]::Allow
|
|
975
|
-
)
|
|
976
|
-
[void]$acl.AddAccessRule($access)
|
|
977
|
-
if ($Kind -eq 'directory') {
|
|
978
|
-
[System.IO.Directory]::SetAccessControl($Target, $acl)
|
|
979
|
-
$verified = [System.IO.Directory]::GetAccessControl($Target)
|
|
980
|
-
} else {
|
|
981
|
-
[System.IO.File]::SetAccessControl($Target, $acl)
|
|
982
|
-
$verified = [System.IO.File]::GetAccessControl($Target)
|
|
983
|
-
}
|
|
984
|
-
if (-not (Test-CanonicalCredentialAcl $verified $sid $expectedInheritance)) {
|
|
985
|
-
Throw-CredentialAclFailure -Reason 'Credential ACL verification failed' -Path $Target -Sid $sid.Value
|
|
986
|
-
}
|
|
987
|
-
`;
|
|
988
|
-
class PowerShellWindowsAclOps {
|
|
989
|
-
executable;
|
|
990
|
-
systemRoot;
|
|
991
|
-
constructor() {
|
|
992
|
-
const systemRoot = process.env['SystemRoot'];
|
|
993
|
-
if (!systemRoot || !win32.isAbsolute(systemRoot)) {
|
|
994
|
-
throw new CredentialStoreError('Windows SystemRoot is unavailable or invalid');
|
|
995
|
-
}
|
|
996
|
-
this.systemRoot = systemRoot;
|
|
997
|
-
this.executable = win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
998
|
-
}
|
|
999
|
-
secureDirectory(path) {
|
|
1000
|
-
this.run(path, 'directory');
|
|
1001
|
-
}
|
|
1002
|
-
secureFile(path) {
|
|
1003
|
-
this.run(path, 'file');
|
|
1004
|
-
}
|
|
1005
|
-
assertTrustedParent(path, strictCreate) {
|
|
1006
|
-
this.run(path, strictCreate ? 'assert-create-parent' : 'assert-parent');
|
|
1007
|
-
}
|
|
1008
|
-
assertTrustedFile(path) {
|
|
1009
|
-
this.run(path, 'assert-file');
|
|
1010
|
-
}
|
|
1011
|
-
run(path, kind) {
|
|
1012
|
-
try {
|
|
1013
|
-
execFileSync(this.executable, [
|
|
1014
|
-
'-NoLogo',
|
|
1015
|
-
'-NoProfile',
|
|
1016
|
-
'-NonInteractive',
|
|
1017
|
-
'-ExecutionPolicy', 'Bypass',
|
|
1018
|
-
// Keep the trusted constant script out of stdin: Windows PowerShell 5.1
|
|
1019
|
-
// can wait indefinitely for redirected stdin on hosted runners.
|
|
1020
|
-
'-Command', POWERSHELL_ENV_SCRIPT_COMMAND,
|
|
1021
|
-
], {
|
|
1022
|
-
encoding: 'utf8',
|
|
1023
|
-
env: {
|
|
1024
|
-
SystemRoot: this.systemRoot,
|
|
1025
|
-
EVOMAP_CREDENTIAL_ACL_TARGET: path,
|
|
1026
|
-
EVOMAP_CREDENTIAL_ACL_KIND: kind,
|
|
1027
|
-
EVOMAP_CREDENTIAL_ACL_SCRIPT: WINDOWS_ACL_SCRIPT,
|
|
1028
|
-
},
|
|
1029
|
-
shell: false,
|
|
1030
|
-
// Capture both streams rather than discarding them: the script's own
|
|
1031
|
-
// message names which path level and which SID failed, and without it
|
|
1032
|
-
// every rejection is indistinguishable from "PowerShell is missing".
|
|
1033
|
-
// The script prints nothing on success, so this stays quiet normally.
|
|
1034
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1035
|
-
timeout: 15_000,
|
|
1036
|
-
windowsHide: true,
|
|
1037
|
-
});
|
|
1038
|
-
}
|
|
1039
|
-
catch (cause) {
|
|
1040
|
-
const detail = windowsAclFailureDetail(cause);
|
|
1041
|
-
throw new Error(detail ? `${kind} check failed: ${detail}` : `${kind} check failed`, { cause });
|
|
1042
|
-
}
|
|
1043
|
-
}
|
|
718
|
+
function windowsCredentialStoreError(message, cause) {
|
|
719
|
+
const detail = cause instanceof Error ? windowsAclFailureDetail(cause) : '';
|
|
720
|
+
return new CredentialStoreError(detail ? `${message} (${detail})` : message, { cause });
|
|
1044
721
|
}
|
|
1045
722
|
function readDarwinAcl(path) {
|
|
1046
723
|
return execFileSync('/bin/ls', ['-lde', path], {
|
|
@@ -1067,6 +744,17 @@ function currentUid() {
|
|
|
1067
744
|
function optionalConstant(name) {
|
|
1068
745
|
return constants[name] ?? 0;
|
|
1069
746
|
}
|
|
747
|
+
function credentialFileStat(path) {
|
|
748
|
+
try {
|
|
749
|
+
return util.statRegularFileIdentity(path);
|
|
750
|
+
}
|
|
751
|
+
catch (cause) {
|
|
752
|
+
if (cause instanceof util.UnsafeLockPathError) {
|
|
753
|
+
throw new CredentialStoreError(`credential file identity changed: ${cause.reason}`, { cause });
|
|
754
|
+
}
|
|
755
|
+
throw cause;
|
|
756
|
+
}
|
|
757
|
+
}
|
|
1070
758
|
function bigLstat(path) {
|
|
1071
759
|
return lstatSync(path, { bigint: true });
|
|
1072
760
|
}
|
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
export declare
|
|
3
|
-
export declare function stripPowerShellClixml(text: string): string;
|
|
1
|
+
import { hub } from '@evomap/evolver-core';
|
|
2
|
+
export declare const POWERSHELL_ENV_SCRIPT_COMMAND: string, windowsAclFailureDetail: typeof hub.windowsAclFailureDetail, stripPowerShellClixml: typeof hub.stripPowerShellClixml;
|
|
@@ -1,91 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
export
|
|
3
|
-
const error = cause;
|
|
4
|
-
const parts = [];
|
|
5
|
-
if (typeof error?.code === 'string' && error.code) {
|
|
6
|
-
parts.push('code ' + normalizePowerShellDiagnostic(error.code));
|
|
7
|
-
}
|
|
8
|
-
if (typeof error?.status === 'number')
|
|
9
|
-
parts.push('exit ' + error.status);
|
|
10
|
-
if (typeof error?.signal === 'string' && error.signal) {
|
|
11
|
-
parts.push('signal ' + normalizePowerShellDiagnostic(error.signal));
|
|
12
|
-
}
|
|
13
|
-
const [stderr, stdout] = [error?.stderr, error?.stdout]
|
|
14
|
-
.map((stream) => (typeof stream === 'string'
|
|
15
|
-
? stream
|
|
16
|
-
: Buffer.isBuffer(stream) ? stream.toString('utf8') : ''))
|
|
17
|
-
.map(stripPowerShellClixml);
|
|
18
|
-
const streams = stderr ? [stderr] : stdout ? [stdout] : [];
|
|
19
|
-
if (streams.length > 0) {
|
|
20
|
-
parts.push(streams.join(' | '));
|
|
21
|
-
}
|
|
22
|
-
else {
|
|
23
|
-
const message = typeof error?.message === 'string' ? error.message : '';
|
|
24
|
-
const detail = stripPowerShellClixml(message.replace(/-EncodedCommand\s+\S+/g, '-EncodedCommand <omitted>'));
|
|
25
|
-
if (detail)
|
|
26
|
-
parts.push(detail);
|
|
27
|
-
}
|
|
28
|
-
return boundPowerShellDiagnostic(parts.join('; '));
|
|
29
|
-
}
|
|
30
|
-
export function stripPowerShellClixml(text) {
|
|
31
|
-
if (/#<\s*CLIXML\b/i.test(text)) {
|
|
32
|
-
const errorRecords = [];
|
|
33
|
-
const serializedErrors = /<S\b(?=[^>]*\bS=\x22Error\x22)[^>]*>([\s\S]*?)<\/S>/gi;
|
|
34
|
-
for (const match of text.matchAll(serializedErrors)) {
|
|
35
|
-
const record = decodePowerShellClixmlText(match[1] ?? '');
|
|
36
|
-
const hasLocationBoilerplate = /(?:^|\s)At line:\d+ char:\d+/i.test(record);
|
|
37
|
-
const decoded = normalizePowerShellDiagnostic(stripPowerShellLocationBoilerplate(record));
|
|
38
|
-
if (decoded)
|
|
39
|
-
errorRecords.push(decoded);
|
|
40
|
-
if (hasLocationBoilerplate)
|
|
41
|
-
break;
|
|
42
|
-
}
|
|
43
|
-
if (errorRecords.length > 0)
|
|
44
|
-
return [...new Set(errorRecords)].join(' | ');
|
|
45
|
-
}
|
|
46
|
-
return normalizePowerShellDiagnostic(stripPowerShellLocationBoilerplate(text)
|
|
47
|
-
.replace(/<Objs\b[\s\S]*?<\/Objs>/g, ' ')
|
|
48
|
-
.replace(/<Objs\b[^\n]*/g, ' ')
|
|
49
|
-
.replace(/#<\s*CLIXML\b/gi, ' '));
|
|
50
|
-
}
|
|
51
|
-
function stripPowerShellLocationBoilerplate(text) {
|
|
52
|
-
return text.replace(/(?:^|\s)At line:\d+ char:\d+[\s\S]*$/i, ' ');
|
|
53
|
-
}
|
|
54
|
-
function decodePowerShellClixmlText(text) {
|
|
55
|
-
return text
|
|
56
|
-
.replace(/_x([0-9a-f]{4})_/gi, (_match, hex) => String.fromCharCode(Number.parseInt(hex, 16)))
|
|
57
|
-
.replace(/&#x([0-9a-f]+);/gi, (match, value) => decodeXmlCodePoint(match, value, 16))
|
|
58
|
-
.replace(/&#([0-9]+);/g, (match, value) => decodeXmlCodePoint(match, value, 10))
|
|
59
|
-
.replace(/</g, '<')
|
|
60
|
-
.replace(/>/g, '>')
|
|
61
|
-
.replace(/"/g, String.fromCharCode(34))
|
|
62
|
-
.replace(/'/g, String.fromCharCode(39))
|
|
63
|
-
.replace(/&/g, '&');
|
|
64
|
-
}
|
|
65
|
-
function decodeXmlCodePoint(match, value, radix) {
|
|
66
|
-
const codePoint = Number.parseInt(value, radix);
|
|
67
|
-
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff ||
|
|
68
|
-
(codePoint >= 0xd800 && codePoint <= 0xdfff)) {
|
|
69
|
-
return match;
|
|
70
|
-
}
|
|
71
|
-
return String.fromCodePoint(codePoint);
|
|
72
|
-
}
|
|
73
|
-
const POWERSHELL_DIAGNOSTIC_FORMAT_CHARACTER = /^\p{Cf}$/u;
|
|
74
|
-
function normalizePowerShellDiagnostic(text) {
|
|
75
|
-
const sanitized = [];
|
|
76
|
-
for (const character of text) {
|
|
77
|
-
const codePoint = character.codePointAt(0) ?? 0;
|
|
78
|
-
const isControl = codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
|
|
79
|
-
const isFormat = POWERSHELL_DIAGNOSTIC_FORMAT_CHARACTER.test(character);
|
|
80
|
-
sanitized.push(isControl || isFormat || codePoint === 0x2028 || codePoint === 0x2029 ? ' ' : character);
|
|
81
|
-
}
|
|
82
|
-
return sanitized.join('').replace(/\s+/g, ' ').trim();
|
|
83
|
-
}
|
|
84
|
-
function boundPowerShellDiagnostic(text) {
|
|
85
|
-
const limit = 300;
|
|
86
|
-
if (text.length <= limit)
|
|
87
|
-
return text;
|
|
88
|
-
const headLength = Math.ceil((limit - 3) / 2);
|
|
89
|
-
const tailLength = limit - 3 - headLength;
|
|
90
|
-
return text.slice(0, headLength) + '...' + text.slice(-tailLength);
|
|
91
|
-
}
|
|
1
|
+
import { hub } from '@evomap/evolver-core';
|
|
2
|
+
export const { POWERSHELL_ENV_SCRIPT_COMMAND, windowsAclFailureDetail, stripPowerShellClixml } = hub;
|
package/dist/hubCapability.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { reference, type hub } from '@evomap/evolver-core';
|
|
2
|
-
import { type FetchLike } from './hubFetch.js';
|
|
2
|
+
import { type FetchLike, type HubDeadlineScheduler } from './hubFetch.js';
|
|
3
3
|
import { type AntiAbuseTelemetryOptions } from './antiAbuseTelemetry.js';
|
|
4
4
|
export declare const INBOUND_LIMIT = 100;
|
|
5
5
|
export declare const OUTBOUND_MAX_BATCH = 50;
|
|
@@ -74,6 +74,8 @@ export interface PublicHubOptions {
|
|
|
74
74
|
auth: hub.AuthProvider;
|
|
75
75
|
fetchFn: FetchLike;
|
|
76
76
|
senderId: () => string | undefined;
|
|
77
|
+
authTimeoutMs?: number;
|
|
78
|
+
deadlineScheduler?: HubDeadlineScheduler;
|
|
77
79
|
/** task.subscribe 轮询节奏(默认 10s). */
|
|
78
80
|
subscribePollMs?: number;
|
|
79
81
|
/** Public Hub anti-abuse heartbeat metadata. Defaults to env-controlled heartbeat mode. */
|
package/dist/hubCapability.js
CHANGED
|
@@ -6,6 +6,7 @@ import { inboundToAgentEvent, agentEventToOutbound, publishRespToReceipt, search
|
|
|
6
6
|
import { antiAbuseTelemetryMode, buildHeartbeatAntiAbuseTelemetry, } from './antiAbuseTelemetry.js';
|
|
7
7
|
import { getWorkspaceKeychainMode } from './auth/workspaceKeychain.js';
|
|
8
8
|
import { agentDirectoryFailure, parsePublicAgentPage, parsePublicAgentProfile, paginatePublicAgentPage, mergePublicAgentPages, publicAgentSearchQuery, publicTaskDiscoveryQuery, PUBLIC_TASK_DISCOVERY_MAX_CANDIDATES, unsupportedPublicAvailability, unsupportedPublicSort, withDirectoryTimeout, } from './agentDirectory.js';
|
|
9
|
+
import { createRecipeExecution } from './recipeExecution.js';
|
|
9
10
|
import { assetMatchesId, stripHubDeliveryMetadataForIntegrity } from './hubReuse.js';
|
|
10
11
|
export const INBOUND_LIMIT = 100;
|
|
11
12
|
export const OUTBOUND_MAX_BATCH = 50;
|
|
@@ -114,6 +115,7 @@ export class PublicHubCapability {
|
|
|
114
115
|
this.opts = opts;
|
|
115
116
|
this.auth = opts.auth;
|
|
116
117
|
this.http = new HubFetch({ baseUrl: opts.baseUrl, auth: opts.auth, fetchFn: opts.fetchFn, senderId: opts.senderId });
|
|
118
|
+
this.recipes.execution = createRecipeExecution(opts);
|
|
117
119
|
}
|
|
118
120
|
evolverVersionForWire(explicitVersion) {
|
|
119
121
|
const antiAbuse = this.opts.antiAbuse;
|
|
@@ -138,7 +140,7 @@ export class PublicHubCapability {
|
|
|
138
140
|
const evolverVersion = this.evolverVersionForWire(opts.evolverVersion);
|
|
139
141
|
const body = await this.http.call('POST', '/a2a/hello', gepEnvelope('hello', {
|
|
140
142
|
rotate_secret: opts.rotate,
|
|
141
|
-
capabilities: { supported_types: ['publish', 'fetch', 'mailbox', 'questions'] },
|
|
143
|
+
capabilities: { supported_types: ['publish', 'fetch', 'mailbox', 'questions'], recipe_execution: { version: 1, modes: ['caller'] } },
|
|
142
144
|
agent_name: '@evomap/evolver-proxy',
|
|
143
145
|
status: 'active',
|
|
144
146
|
timestamp: new Date().toISOString(),
|
|
@@ -172,6 +174,8 @@ export class PublicHubCapability {
|
|
|
172
174
|
...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
|
|
173
175
|
};
|
|
174
176
|
}
|
|
177
|
+
if (isNodeMergedResponse(body, payload))
|
|
178
|
+
return helloResultFromBody(200, body);
|
|
175
179
|
if (payload['error'])
|
|
176
180
|
return { ok: false, error: String(payload['error']), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}), ...(rateLimitUntilMs !== undefined ? { rateLimitUntilMs } : {}) };
|
|
177
181
|
const nodeId = stringField(payload, 'your_node_id')
|
|
@@ -203,8 +207,12 @@ export class PublicHubCapability {
|
|
|
203
207
|
};
|
|
204
208
|
}
|
|
205
209
|
catch (err) {
|
|
206
|
-
if (err instanceof AuthError)
|
|
207
|
-
|
|
210
|
+
if (err instanceof AuthError) {
|
|
211
|
+
const result = helloResultFromBody(err.status, asRecord(err.body) ?? {});
|
|
212
|
+
return result.error === 'node_merged'
|
|
213
|
+
? result
|
|
214
|
+
: { ok: false, authError: true, error: `hub auth error ${err.status}`, httpStatus: err.status };
|
|
215
|
+
}
|
|
208
216
|
if (err instanceof HubClientError)
|
|
209
217
|
return helloResultFromBody(err.status, asRecord(err.body) ?? {});
|
|
210
218
|
if (isHubUnreachableError(err))
|
|
@@ -229,8 +237,12 @@ export class PublicHubCapability {
|
|
|
229
237
|
return heartbeatResultFromBody(200, body);
|
|
230
238
|
}
|
|
231
239
|
catch (err) {
|
|
232
|
-
if (err instanceof AuthError)
|
|
233
|
-
|
|
240
|
+
if (err instanceof AuthError) {
|
|
241
|
+
const result = heartbeatResultFromBody(err.status, asRecord(err.body) ?? {});
|
|
242
|
+
return result.error === 'node_merged'
|
|
243
|
+
? result
|
|
244
|
+
: { ok: false, authError: true, error: `hub auth error ${err.status}` };
|
|
245
|
+
}
|
|
234
246
|
if (err instanceof HubClientError)
|
|
235
247
|
return heartbeatResultFromBody(err.status, asRecord(err.body) ?? {});
|
|
236
248
|
if (isHubUnreachableError(err))
|
|
@@ -702,22 +714,11 @@ export class PublicHubCapability {
|
|
|
702
714
|
return recipeSearchReceiptFromBody(body);
|
|
703
715
|
}
|
|
704
716
|
async expressRecipe(recipeId, request = {}) {
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
const
|
|
709
|
-
|
|
710
|
-
...(sender ? { node_id: sender } : {}),
|
|
711
|
-
input_payload: request.inputPayload ?? {},
|
|
712
|
-
});
|
|
713
|
-
const payload = recipePayload(body);
|
|
714
|
-
const organismId = recipeOrganismIdFromPayload(payload);
|
|
715
|
-
const receipt = recipeReceiptFromBody(body);
|
|
716
|
-
return {
|
|
717
|
-
...receipt,
|
|
718
|
-
recipeId: receipt.recipeId ?? recipeId,
|
|
719
|
-
...(organismId ? { organismId } : {}),
|
|
720
|
-
};
|
|
717
|
+
const input = hubNs.parseRecipeExecutionInput('express', { ...request, recipeId });
|
|
718
|
+
if (isHubDryRunEnabled())
|
|
719
|
+
throw new Error('recipe_execution_disabled_in_dry_run');
|
|
720
|
+
const receipt = await hubNs.requireRecipeExecution(this.recipes.execution).invoke('express', input);
|
|
721
|
+
return { recipeId, organismId: receipt.organism.id, status: receipt.status, raw: receipt };
|
|
721
722
|
}
|
|
722
723
|
task = {
|
|
723
724
|
claim: async (taskId) => {
|
|
@@ -940,15 +941,6 @@ function isRecipeLikeRecord(value) {
|
|
|
940
941
|
?? stringField(value, 'recipe_id')
|
|
941
942
|
?? stringField(value, 'recipeId'));
|
|
942
943
|
}
|
|
943
|
-
function recipeOrganismIdFromPayload(payload) {
|
|
944
|
-
const flatId = stringField(payload, 'organism_id') ?? stringField(payload, 'organismId');
|
|
945
|
-
if (flatId)
|
|
946
|
-
return flatId;
|
|
947
|
-
const organism = asRecord(payload['organism']);
|
|
948
|
-
return organism
|
|
949
|
-
? stringField(organism, 'id') ?? stringField(organism, 'organism_id') ?? stringField(organism, 'organismId')
|
|
950
|
-
: undefined;
|
|
951
|
-
}
|
|
952
944
|
function recipeSearchQuery(request) {
|
|
953
945
|
return {
|
|
954
946
|
...(request.q ? { q: request.q } : {}),
|
|
@@ -1568,9 +1560,12 @@ function helloResultFromBody(httpStatus, body) {
|
|
|
1568
1560
|
const payload = asRecord(body['payload']) ?? body;
|
|
1569
1561
|
const retryAfterMs = numberField(payload, 'retry_after_ms') ?? numberField(payload, 'retryAfterMs');
|
|
1570
1562
|
const rateLimitUntilMs = numberField(payload, 'rate_limit_until_ms') ?? numberField(payload, 'rateLimitUntilMs');
|
|
1571
|
-
const
|
|
1572
|
-
const
|
|
1573
|
-
const
|
|
1563
|
+
const nodeMerged = isNodeMergedResponse(body, payload);
|
|
1564
|
+
const status = nodeMerged ? 'node_merged' : stringField(payload, 'status');
|
|
1565
|
+
const error = nodeMerged
|
|
1566
|
+
? 'node_merged'
|
|
1567
|
+
: stringField(payload, 'error') ?? stringField(payload, 'reason') ?? (httpStatus >= 400 ? `http_${httpStatus}` : undefined);
|
|
1568
|
+
const details = nodeMerged ? undefined : payload['details'] ?? body['details'];
|
|
1574
1569
|
const authError = httpStatus === 401 || httpStatus === 403 || status === 'auth_failed' || status === 'invalid_secret';
|
|
1575
1570
|
return {
|
|
1576
1571
|
ok: false,
|
|
@@ -1591,9 +1586,13 @@ function hubUnreachableRetryAfterMs(err) {
|
|
|
1591
1586
|
function heartbeatResultFromBody(httpStatus, body) {
|
|
1592
1587
|
const payload = asRecord(body['payload']) ?? body;
|
|
1593
1588
|
const retryAfterMs = numberField(payload, 'retry_after_ms') ?? numberField(payload, 'retryAfterMs');
|
|
1594
|
-
const
|
|
1595
|
-
const
|
|
1596
|
-
const
|
|
1589
|
+
const nodeMerged = isNodeMergedResponse(body, payload);
|
|
1590
|
+
const status = nodeMerged ? 'node_merged' : stringField(payload, 'status');
|
|
1591
|
+
const error = nodeMerged
|
|
1592
|
+
? 'node_merged'
|
|
1593
|
+
: stringField(payload, 'error') ?? (httpStatus >= 400 ? `http_${httpStatus}` : undefined);
|
|
1594
|
+
const details = nodeMerged ? undefined : payload['details'] ?? body['details'];
|
|
1595
|
+
const authError = httpStatus === 401 || httpStatus === 403;
|
|
1597
1596
|
const ack = asRecord(payload['last_update_ack']);
|
|
1598
1597
|
const forceUpdate = forceUpdateFromRecord(asRecord(payload['force_update']));
|
|
1599
1598
|
const rawCapabilityGaps = payload['capability_gaps'] ?? payload['capabilityGaps'];
|
|
@@ -1607,6 +1606,7 @@ function heartbeatResultFromBody(httpStatus, body) {
|
|
|
1607
1606
|
&& !error;
|
|
1608
1607
|
return {
|
|
1609
1608
|
ok,
|
|
1609
|
+
...(authError ? { authError: true } : {}),
|
|
1610
1610
|
...(httpStatus >= 400 ? { httpStatus } : {}),
|
|
1611
1611
|
...(error ? { error } : {}),
|
|
1612
1612
|
...(details !== undefined ? { details } : {}),
|
|
@@ -1620,6 +1620,21 @@ function heartbeatResultFromBody(httpStatus, body) {
|
|
|
1620
1620
|
...(capabilityGaps !== undefined ? { capabilityGaps } : {}),
|
|
1621
1621
|
};
|
|
1622
1622
|
}
|
|
1623
|
+
function isNodeMergedResponse(body, payload) {
|
|
1624
|
+
return [
|
|
1625
|
+
payload['error'],
|
|
1626
|
+
payload['reason'],
|
|
1627
|
+
payload['status'],
|
|
1628
|
+
body['error'],
|
|
1629
|
+
body['reason'],
|
|
1630
|
+
body['status'],
|
|
1631
|
+
].some((value) => {
|
|
1632
|
+
if (typeof value !== 'string')
|
|
1633
|
+
return false;
|
|
1634
|
+
const code = value.trim();
|
|
1635
|
+
return code === 'node_merged' || code.startsWith('node_merged:');
|
|
1636
|
+
});
|
|
1637
|
+
}
|
|
1623
1638
|
function forceUpdateFromRecord(value) {
|
|
1624
1639
|
if (!value)
|
|
1625
1640
|
return undefined;
|
package/dist/hubFetch.d.ts
CHANGED
|
@@ -34,6 +34,7 @@ export interface HubOperationTimeouts {
|
|
|
34
34
|
helloMs: number;
|
|
35
35
|
}
|
|
36
36
|
export type HubOperation = 'general' | 'search' | 'heartbeat' | 'poll' | 'hello';
|
|
37
|
+
export declare const HUB_AUTH_TIMEOUT_MS = 20000;
|
|
37
38
|
export interface HubDeadlineScheduler {
|
|
38
39
|
set(callback: () => void, delayMs: number): unknown;
|
|
39
40
|
clear(handle: unknown): void;
|
|
@@ -90,6 +91,7 @@ export interface HubFetchDeps {
|
|
|
90
91
|
* 401/403→AuthError(reauth), 4xx→HubClientError(终态), 5xx→重试.
|
|
91
92
|
* 非 JSON Hub 响应(WAF/HTML/captive portal/gateway text)→HubUnreachableError, 不触发 auth recovery.
|
|
92
93
|
*/
|
|
94
|
+
export declare function authenticateHubRequest(deps: Pick<HubFetchDeps, 'auth' | 'authTimeoutMs' | 'deadlineScheduler'>, method: string, path: string, bodyObj?: Record<string, unknown>): Promise<hub.SignedRequest>;
|
|
93
95
|
export declare class HubFetch {
|
|
94
96
|
private readonly deps;
|
|
95
97
|
private readonly operationTimeouts;
|
package/dist/hubFetch.js
CHANGED
|
@@ -17,7 +17,7 @@ const HUB_OPERATION_TIMEOUT_KEYS = {
|
|
|
17
17
|
poll: 'pollMs',
|
|
18
18
|
hello: 'helloMs',
|
|
19
19
|
};
|
|
20
|
-
const
|
|
20
|
+
export const HUB_AUTH_TIMEOUT_MS = 20_000;
|
|
21
21
|
const DEFAULT_DEADLINE_SCHEDULER = {
|
|
22
22
|
set(callback, delayMs) {
|
|
23
23
|
const timer = setTimeout(callback, delayMs);
|
|
@@ -139,6 +139,27 @@ function mergeRequestHeaders(requestHeaders, signedHeaders) {
|
|
|
139
139
|
* 401/403→AuthError(reauth), 4xx→HubClientError(终态), 5xx→重试.
|
|
140
140
|
* 非 JSON Hub 响应(WAF/HTML/captive portal/gateway text)→HubUnreachableError, 不触发 auth recovery.
|
|
141
141
|
*/
|
|
142
|
+
export async function authenticateHubRequest(deps, method, path, bodyObj) {
|
|
143
|
+
const operation = hubOperationForRequest(path, bodyObj);
|
|
144
|
+
const draft = bodyObj !== undefined ? JSON.stringify(bodyObj) : '';
|
|
145
|
+
const authDeadline = createHubDeadline(deps.deadlineScheduler ?? DEFAULT_DEADLINE_SCHEDULER, method, path, operation, deps.authTimeoutMs ?? HUB_AUTH_TIMEOUT_MS);
|
|
146
|
+
try {
|
|
147
|
+
return await awaitWithAbort(deps.auth.authenticate({ method, path, ...(draft ? { body: draft } : {}), signal: authDeadline.signal }), authDeadline.signal);
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
if (isAuthTransportTimeout(error)) {
|
|
151
|
+
throw new HubUnreachableError('hub authentication timed out', {
|
|
152
|
+
context: `${method} ${path}`,
|
|
153
|
+
retryAfterMs: HUB_UNREACHABLE_BACKOFF_BASE_MS,
|
|
154
|
+
operation,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
authDeadline.dispose();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
142
163
|
export class HubFetch {
|
|
143
164
|
deps;
|
|
144
165
|
operationTimeouts;
|
|
@@ -150,25 +171,7 @@ export class HubFetch {
|
|
|
150
171
|
}
|
|
151
172
|
async call(method, path, bodyObj, query, requestHeaders) {
|
|
152
173
|
const operation = hubOperationForRequest(path, bodyObj);
|
|
153
|
-
const
|
|
154
|
-
const authDeadline = createHubDeadline(this.deadlineScheduler, method, path, operation, this.deps.authTimeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS);
|
|
155
|
-
let signed;
|
|
156
|
-
try {
|
|
157
|
-
signed = await awaitWithAbort(this.deps.auth.authenticate({ method, path, ...(draft ? { body: draft } : {}), signal: authDeadline.signal }), authDeadline.signal);
|
|
158
|
-
}
|
|
159
|
-
catch (error) {
|
|
160
|
-
if (isAuthTransportTimeout(error)) {
|
|
161
|
-
throw new HubUnreachableError('hub authentication timed out', {
|
|
162
|
-
context: `${method} ${path}`,
|
|
163
|
-
retryAfterMs: HUB_UNREACHABLE_BACKOFF_BASE_MS,
|
|
164
|
-
operation,
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
throw error;
|
|
168
|
-
}
|
|
169
|
-
finally {
|
|
170
|
-
authDeadline.dispose();
|
|
171
|
-
}
|
|
174
|
+
const signed = await authenticateHubRequest({ auth: this.deps.auth, authTimeoutMs: this.deps.authTimeoutMs, deadlineScheduler: this.deadlineScheduler }, method, path, bodyObj);
|
|
172
175
|
const timeoutMs = this.operationTimeouts[HUB_OPERATION_TIMEOUT_KEYS[operation]];
|
|
173
176
|
const deadline = createHubDeadline(this.deadlineScheduler, method, path, operation, timeoutMs);
|
|
174
177
|
try {
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { hub } from '@evomap/evolver-core';
|
|
2
|
+
import { type PublicHubOptions } from './hubCapability.js';
|
|
3
|
+
export declare function recipeHubError(error: unknown, operation: hub.RecipeExecutionOperation): hub.RecipeExecutionError;
|
|
4
|
+
export declare function createRecipeExecution(opts: PublicHubOptions): hub.RecipeExecutionCapability;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { hub } from '@evomap/evolver-core';
|
|
3
|
+
import { AuthError, HubClientError, HubFetch, HubUnreachableError, authenticateHubRequest } from './hubFetch.js';
|
|
4
|
+
import { isHubDryRunEnabled } from './hubCapability.js';
|
|
5
|
+
const correctableFinalizationCodes = new Set(['invalid_output_schema', 'invalid_final_output', 'invalid_execution_evidence', 'execution_evidence_required', 'execution_evidence_digest_mismatch', 'execution_artifacts_required', 'invalid_text_transform_output', 'execution_steps_incomplete']);
|
|
6
|
+
export function recipeHubError(error, operation) {
|
|
7
|
+
if (error instanceof hub.RecipeExecutionError)
|
|
8
|
+
return error;
|
|
9
|
+
if (error instanceof HubClientError || error instanceof AuthError) {
|
|
10
|
+
const body = error.body && typeof error.body === 'object' ? error.body : {};
|
|
11
|
+
const raw = body['code'] ?? body['error'];
|
|
12
|
+
const code = typeof raw === 'string' && /^[a-z][a-z0-9_]{0,127}$/.test(raw) ? raw : 'recipe_hub_request_failed';
|
|
13
|
+
const retryAfterMs = error instanceof HubClientError && Number.isFinite(error.retryAfterMs) && (error.retryAfterMs ?? -1) >= 0 ? error.retryAfterMs : undefined;
|
|
14
|
+
const rejected = operation === 'finalize' && (error.status === 400 || error.status === 409) && correctableFinalizationCodes.has(code);
|
|
15
|
+
return new hub.RecipeExecutionError(code, error.status, retryAfterMs, rejected ? 'rejected' : 'unknown');
|
|
16
|
+
}
|
|
17
|
+
if (error instanceof HubUnreachableError)
|
|
18
|
+
return new hub.RecipeExecutionError('recipe_hub_unreachable', 503, error.retryAfterMs);
|
|
19
|
+
return new hub.RecipeExecutionError('recipe_execution_failed', 502);
|
|
20
|
+
}
|
|
21
|
+
export function createRecipeExecution(opts) {
|
|
22
|
+
const baseUrl = opts.baseUrl.replace(/\/+$/, '');
|
|
23
|
+
const scope = () => {
|
|
24
|
+
const sender = opts.senderId();
|
|
25
|
+
if (!sender)
|
|
26
|
+
throw new hub.RecipeExecutionError('recipe_node_identity_required', 409);
|
|
27
|
+
return createHash('sha256').update(JSON.stringify([baseUrl, sender])).digest('hex');
|
|
28
|
+
};
|
|
29
|
+
const prepare = async (operation, input, expectedScope) => {
|
|
30
|
+
const parsed = hub.parseRecipeExecutionInput(operation, input);
|
|
31
|
+
if (isHubDryRunEnabled())
|
|
32
|
+
throw new hub.RecipeExecutionError('recipe_execution_disabled_in_dry_run', 409, undefined, 'rejected', 'not_sent');
|
|
33
|
+
const frozenScope = expectedScope ?? scope();
|
|
34
|
+
const sender = opts.senderId();
|
|
35
|
+
const assertIdentity = () => {
|
|
36
|
+
if (!sender || opts.senderId() !== sender || scope() !== frozenScope)
|
|
37
|
+
throw new hub.RecipeExecutionError('recipe_identity_scope_mismatch', 409, undefined, 'rejected', 'not_sent');
|
|
38
|
+
};
|
|
39
|
+
assertIdentity();
|
|
40
|
+
const target = encodeURIComponent(String(parsed['recipeId'] ?? parsed['organismId'] ?? parsed['taskId'] ?? ''));
|
|
41
|
+
const path = operation === 'express' ? `/a2a/recipe/${target}/express`
|
|
42
|
+
: operation === 'get' ? `/a2a/organism/${target}/private`
|
|
43
|
+
: operation === 'list' ? '/a2a/organism/mine'
|
|
44
|
+
: operation === 'task' ? `/a2a/recipe-execution/task/${target}`
|
|
45
|
+
: `/a2a/organism/${target}/${operation}`;
|
|
46
|
+
const names = { inputPayload: 'input_payload', requestKey: 'request_key', maxCredits: 'max_credits', executionMode: 'execution_mode', leaseId: 'lease_id', assetId: 'asset_id' };
|
|
47
|
+
const body = Object.fromEntries(Object.entries(parsed).filter(([key, value]) => !['recipeId', 'organismId', 'taskId'].includes(key) && value !== undefined).map(([key, value]) => [names[key] ?? key, value]));
|
|
48
|
+
const read = ['get', 'list', 'task'].includes(operation);
|
|
49
|
+
let signed;
|
|
50
|
+
let headers;
|
|
51
|
+
try {
|
|
52
|
+
signed = await authenticateHubRequest(opts, read ? 'GET' : 'POST', path, read ? undefined : body);
|
|
53
|
+
assertIdentity();
|
|
54
|
+
const fields = signed.bodyFields ?? {};
|
|
55
|
+
if (Object.keys(fields).some((key) => key !== 'node_secret'))
|
|
56
|
+
throw new hub.RecipeExecutionError('recipe_auth_body_fields_unsupported', 400, undefined, 'rejected', 'not_sent');
|
|
57
|
+
headers = { ...signed.headers };
|
|
58
|
+
if (fields['node_secret'] !== undefined) {
|
|
59
|
+
if (typeof fields['node_secret'] !== 'string' || !fields['node_secret'])
|
|
60
|
+
throw new hub.RecipeExecutionError('recipe_auth_invalid', 400, undefined, 'rejected', 'not_sent');
|
|
61
|
+
if (!Object.keys(headers).some((key) => key.toLowerCase() === 'authorization'))
|
|
62
|
+
headers['Authorization'] = `Bearer ${fields['node_secret']}`;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
throw recipeHubError(error, operation);
|
|
67
|
+
}
|
|
68
|
+
const auth = {
|
|
69
|
+
kind: opts.auth.kind,
|
|
70
|
+
login: () => opts.auth.login(), rotate: () => opts.auth.rotate(), revoke: (id) => opts.auth.revoke(id),
|
|
71
|
+
authenticate: async () => {
|
|
72
|
+
assertIdentity();
|
|
73
|
+
return { ...signed, headers, bodyFields: {} };
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
const http = new HubFetch({ ...opts, baseUrl, auth, senderId: () => sender, fetchFn: (url, init) => { assertIdentity(); return opts.fetchFn(url, init); } });
|
|
77
|
+
return {
|
|
78
|
+
invoke: async () => {
|
|
79
|
+
try {
|
|
80
|
+
const response = await http.call(read ? 'GET' : 'POST', path, read ? undefined : body, read ? body : undefined);
|
|
81
|
+
const validated = hub.recipeExecutionResponses[operation].safeParse(response);
|
|
82
|
+
if (!validated.success)
|
|
83
|
+
throw new hub.RecipeExecutionError(`recipe_${operation}_response_invalid`, 502);
|
|
84
|
+
return validated.data;
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
throw recipeHubError(error, operation);
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
protocolVersion: 1,
|
|
94
|
+
scope,
|
|
95
|
+
prepare,
|
|
96
|
+
async invoke(operation, input, expectedScope) {
|
|
97
|
+
return await (await prepare(operation, input, expectedScope)).invoke();
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
package/dist/wireMap.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@evomap/evolver-adapter-public",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.39",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -17,8 +17,8 @@
|
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
19
|
"@evomap/atp-sdk": "^0.1.0",
|
|
20
|
-
"@evomap/evolver-core": "2.0.
|
|
21
|
-
"undici": "^6.
|
|
20
|
+
"@evomap/evolver-core": "2.0.39",
|
|
21
|
+
"undici": "^6.28.0"
|
|
22
22
|
},
|
|
23
23
|
"optionalDependencies": {
|
|
24
24
|
"@napi-rs/keyring": "^1.1.6"
|