@yadsh/dsh-qa-integrations 0.10.5 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +7 -2
  2. package/compatibility.json +1 -1
  3. package/lib/broker/outcomes.js +92 -0
  4. package/lib/broker/outcomes.js.map +1 -0
  5. package/lib/broker/service-view.js +93 -0
  6. package/lib/broker/service-view.js.map +1 -0
  7. package/lib/broker.js +37 -209
  8. package/lib/broker.js.map +1 -1
  9. package/lib/client/index.js +7 -0
  10. package/lib/client/index.js.map +1 -1
  11. package/lib/client/integrations.js.map +1 -1
  12. package/lib/client/operator-card.js +27 -6
  13. package/lib/client/operator-card.js.map +1 -1
  14. package/lib/client/operator-controls.js +84 -13
  15. package/lib/client/operator-controls.js.map +1 -1
  16. package/lib/client/operator-sections/service-operation-policy.js +30 -0
  17. package/lib/client/operator-sections/service-operation-policy.js.map +1 -0
  18. package/lib/client/operator-sections/service-profiles.js +35 -27
  19. package/lib/client/operator-sections/service-profiles.js.map +1 -1
  20. package/lib/client/operator-sections/shared.js.map +1 -1
  21. package/lib/client/operator-service-reach.js +6 -2
  22. package/lib/client/operator-service-reach.js.map +1 -1
  23. package/lib/client/provider-card.js +3 -1
  24. package/lib/client/provider-card.js.map +1 -1
  25. package/lib/client.js +17362 -1892
  26. package/lib/client.js.map +1 -1
  27. package/lib/index.js +8 -0
  28. package/lib/index.js.map +1 -1
  29. package/lib/providers/bitrix24/index.js +11 -3
  30. package/lib/providers/bitrix24/index.js.map +1 -1
  31. package/lib/providers/confluence/index.js +11 -3
  32. package/lib/providers/confluence/index.js.map +1 -1
  33. package/lib/providers/gitlab/index.js +11 -3
  34. package/lib/providers/gitlab/index.js.map +1 -1
  35. package/lib/providers/jira/index.js +11 -3
  36. package/lib/providers/jira/index.js.map +1 -1
  37. package/lib/providers/shared/service-boundary.js +14 -15
  38. package/lib/providers/shared/service-boundary.js.map +1 -1
  39. package/lib/providers/teamcity/index.js +13 -3
  40. package/lib/providers/teamcity/index.js.map +1 -1
  41. package/lib/providers/testit/catalog.js +2 -0
  42. package/lib/providers/testit/catalog.js.map +1 -1
  43. package/lib/providers/testit/index.js +11 -3
  44. package/lib/providers/testit/index.js.map +1 -1
  45. package/lib/providers/weblate/index.js +11 -3
  46. package/lib/providers/weblate/index.js.map +1 -1
  47. package/lib/repository.js +2 -2
  48. package/lib/repository.js.map +1 -1
  49. package/lib/service-credentials/catalog.js +26 -0
  50. package/lib/service-credentials/catalog.js.map +1 -0
  51. package/lib/service-credentials/config.js +4 -9
  52. package/lib/service-credentials/config.js.map +1 -1
  53. package/lib/service-credentials/operation-policy.js +28 -0
  54. package/lib/service-credentials/operation-policy.js.map +1 -0
  55. package/lib/service-credentials/policy.js +14 -22
  56. package/lib/service-credentials/policy.js.map +1 -1
  57. package/lib/service-credentials/state.js +18 -16
  58. package/lib/service-credentials/state.js.map +1 -1
  59. package/lib/service-credentials/types.js.map +1 -1
  60. package/lib/typert.host.js +1235 -702
  61. package/lib/typert.remote-client.d.ts +57 -3
  62. package/lib/typert.remote-client.js +1213 -696
  63. package/lib/types/broker/outcomes.d.ts +35 -0
  64. package/lib/types/broker/service-view.d.ts +24 -0
  65. package/lib/types/broker.d.ts +1 -48
  66. package/lib/types/client/integrations.d.ts +6 -2
  67. package/lib/types/client/operator-card.d.ts +3 -1
  68. package/lib/types/client/operator-controls.d.ts +8 -0
  69. package/lib/types/client/operator-sections/service-operation-policy.d.ts +12 -0
  70. package/lib/types/client/operator-sections/shared.d.ts +2 -0
  71. package/lib/types/client/operator-service-reach.d.ts +4 -0
  72. package/lib/types/index.d.ts +3 -0
  73. package/lib/types/providers/bitrix24/index.d.ts +1 -1
  74. package/lib/types/providers/confluence/index.d.ts +1 -1
  75. package/lib/types/providers/contract.d.ts +3 -1
  76. package/lib/types/providers/gitlab/index.d.ts +1 -1
  77. package/lib/types/providers/jira/index.d.ts +1 -1
  78. package/lib/types/providers/shared/service-boundary.d.ts +8 -9
  79. package/lib/types/providers/teamcity/index.d.ts +1 -1
  80. package/lib/types/providers/testit/index.d.ts +1 -1
  81. package/lib/types/providers/weblate/index.d.ts +1 -1
  82. package/lib/types/repository.d.ts +1 -1
  83. package/lib/types/service-credentials/catalog.d.ts +4 -0
  84. package/lib/types/service-credentials/config.d.ts +2 -2
  85. package/lib/types/service-credentials/operation-policy.d.ts +15 -0
  86. package/lib/types/service-credentials/policy.d.ts +3 -1
  87. package/lib/types/service-credentials/state.d.ts +2 -1
  88. package/lib/types/service-credentials/types.d.ts +5 -3
  89. package/lib/types/types.d.ts +15 -0
  90. package/package.json +19 -19
package/README.md CHANGED
@@ -839,7 +839,8 @@ managedServiceCredentials:
839
839
  groups:
840
840
  - group/platform
841
841
  policy:
842
- gitlab.issues.read: deny # только сужение; "allow" отвергается при загрузке
842
+ gitlab.issues.read: deny # запрет раздела имеет приоритет над разрешением операции
843
+ jobs.log: allow # явно разрешить чтение логов в пределах resources
843
844
  - id: teamcity-readonly
844
845
  provider: teamcity
845
846
  instance: teamcity # сервер TeamCity один, id фиксирован
@@ -856,7 +857,11 @@ managedServiceCredentials:
856
857
 
857
858
  Новое подключение начинается на сервисном токене, когда профиль для выбранного инстанса есть и `defaultForNewConnections` включён (по умолчанию так): чекбокс «Использовать сервисный токен» в форме уже отмечен, поля токена нет вовсе, а кнопка называется «Подключить сервисный токен». Снятая галочка возвращает обычную форму с personal access token. У уже существующих подключений режим не меняется: он хранится в самом подключении, поэтому обновление стенда не переводит пользователя на общий аккаунт само. В подключённой карточке режим виден строкой «Сервисный аккаунт · управляется администратором», а рядом — «Изменить доступ» и «Использовать личный аккаунт».
858
859
 
859
- Сервисный режим — не «read-only вообще», а жёсткий потолок: только `read`, только обычная чувствительность и только операции, которые провайдер пометил service-safe намеренно. Запись, админ-действия, управление правами и токенами и произвольный REST недостижимы, даже если сервисный токен наверху это умеет: классификация операции — свойство каталога провайдера, а не прав токена. Чувствительные чтения остаются личными: через общий аккаунт не читаются лог CI-джоба GitLab (`ci.logs.read`), лог сборки TeamCity (`logs.read`) и текст артефакта (`artifacts.read`), тело вложения Test IT и Confluence, содержимое Диска Bitrix24, переписки и открытые линии Bitrix24, календарь занятости и справочник сотрудников с телефонами, а конфиденциальная задача GitLab не возвращается вовсе — прямое чтение отвечает `ResourceNotFound`, из выдачи и из поиска она выпадает, а поиск по комментариям (`scope: notes`) отказывается целиком: у комментария нет признака конфиденциальности, и проверить его родителя одним запросом нельзя. У Weblate, где нет операций уровня журналов, чувствительных чтений нет вовсе. Операция, которую провайдер не классифицировал, отклоняется по умолчанию: инструмент, добавленный обновлением провайдера, недостижим через общий аккаунт, пока кто-то не классифицирует его намеренно. Администраторская `policy` может только выключить: `allow` в профиле отвергается при загрузке, потому что оператор, написавший `allow`, считает, что расширил потолок. Отказ называет сработавшее правило: чувствительное чтение отвечает строкой с именем возможности (`teamcity.logs.read`) и с тем, что нужен личный аккаунт, — модель передаёт эту строку пользователю дословно, и из неё видно, что ограничение на стороне потолка сервиса, а не интеграции стенда. То же условие стоит в описании каждого инструмента, которому потолок отказывает как чтению, — и только там, где развёртывание вообще выдаёт сервисные креденшалы: на стенде без общего токена предупреждение о чужом потолке удерживало бы модель от чтения, которое её личный аккаунт отвечает. Подпись складывается из классификации операции в каталоге провайдера, поэтому модель знает её до вызова, а не только в отказе, и условие не может застрять у одного провайдера: `tests/tools/service-ceiling.test.ts` сверяет описания со всеми семью каталогами, беря имена инструментов по фактическому префиксу провайдера (у Bitrix24 это `bitrix_`, а не `bitrix24_`) и проверяя, что ни один каталог не сверяется с пустым множеством, а стенд без общего токена не несёт ни одной подписи. Второй замок — отказ самого провайдера — различает запись, личное чтение и чтение, закрытое классификацией, и отвечает тем же кодом, что и брокер на той же классификации (`tests/shared/service-boundary.test.ts`).
860
+ Политика сервисного профиля настраивается в админке, в разделе «Операции сервисного аккаунта». Для каждой операции можно выбрать «Разрешить», «Запретить» или вернуть поведение по умолчанию. Настройка общая для всех пользователей выбранного профиля и применяется к уже созданным подключениям. Без явного разрешения сохраняются прежние ограничения на чувствительное чтение. Например, `builds.log: allow` открывает лог сборки TeamCity, а `jobs.log: allow` — лог джоба GitLab; флаг соответствующего провайдера также должен быть включён.
861
+
862
+ `policy` принимает `allow` и `deny` для имени операции (`builds.log`), возможности (`logs.read`) или ключа с префиксом провайдера (`teamcity.logs.read`). Если подходят несколько правил, любой `deny` имеет приоритет. Выбор пользователя может дополнительно закрыть раздел, но не расширяет разрешение профиля. В карточке подключения отображается актуальное состояние, включая частичный доступ к разделам, в которых разрешены не все операции.
863
+
864
+ Разрешение чтения сохраняет границу `resources`, ограничения ответа, маскирование секретов, аудит и лимиты запросов. Провайдер сначала доказывает принадлежность ресурса разрешённому проекту или пространству, и только затем отдаёт содержимое. Операции, для которых принадлежность ресурса установить нельзя (например, глобальное вложение Test IT без связи с проектом), остаются доступными через личное подключение; админка объясняет это рядом с операцией. Запись, админ-действия, секретные данные, произвольный REST и неклассифицированные операции через сервисный аккаунт не разрешаются. Права сервисного токена на стороне внешней системы этого правила не меняют.
860
865
 
861
866
  Граница ресурсов нужна потому, что сервисный аккаунт видит больше, чем один пользователь. В сервисном режиме провайдер сверяет с allowlist каждый вызов: проект, названный по id или по пути, должен быть в списке или под перечисленной группой; сборка TeamCity, названная по id, сначала разрешается в свой проект; страница Confluence, названная по id, — в своё пространство; задача Jira и запись Test IT — в свой проект; компонент Weblate — в свой проект-слаг; вебхук Bitrix24 обязан отвечать на портале, названном в границе, — других идентификаторов у границы этого провайдера нет. Листинг, не называющий ресурс, отказывается, а не отвечает всей картиной, доступной общему аккаунту. Списки (`gitlab_projects_list`, `teamcity_projects`, `projects.list` Weblate, `projects.list` Test IT) собираются из allowlist, а не из того, что видит сервисный токен: ресурс, которого токен не видит, приходит в `unavailableResources`, а не исчезает молча, — это и есть ответ оператору, что граница и токен разошлись. Разворачивая группу GitLab, провайдер просит только её собственные проекты (`with_shared=false`) и дополнительно сверяет каждый вернувшийся проект с границей: чужой проект, расшаренный в группу, в выдачу не попадает. Пользователь может сузить список в карточке кнопкой «Изменить доступ», но не расширить: выбор вне администраторского списка отбрасывается и не сохраняется.
862
867
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "deepseekHarness": {
3
3
  "channel": "next",
4
- "range": ">=0.1.7-rc.2 <0.2.0",
4
+ "range": ">=0.1.7-rc.2 <0.3.0-0",
5
5
  "testedReleases": ["0.1.7-rc.2"],
6
6
  "requiredHostFeatures": ["tools", "qaSurface"],
7
7
  "requiredClientFeatures": [
@@ -0,0 +1,92 @@
1
+ import { IntegrationError } from "../errors.js";
2
+ /** What a probe verdict means for the stored binding, if anything. */
3
+ export function healthCode(health) {
4
+ switch (health?.status) {
5
+ case undefined:
6
+ case "healthy":
7
+ return undefined;
8
+ case "expired":
9
+ return "CredentialExpired";
10
+ case "revoked":
11
+ return "CredentialRevoked";
12
+ case "unsafe_scope":
13
+ return "ServiceCredentialUnsafeScope";
14
+ default:
15
+ return "ProviderUnavailable";
16
+ }
17
+ }
18
+ /** Only a refused credential says the binding itself needs repair. */
19
+ const REFUSED_CREDENTIAL_CODES = Object.freeze(["CredentialExpired", "CredentialRevoked", "InvalidCredential"]);
20
+ export function refusedCredentialCode(error) {
21
+ return error instanceof IntegrationError &&
22
+ REFUSED_CREDENTIAL_CODES.includes(error.code)
23
+ ? error.code
24
+ : undefined;
25
+ }
26
+ /** Codes that mean policy refused the operation, wherever it was decided. */
27
+ const DENIAL_CODES = Object.freeze([
28
+ "OperationDeniedByPolicy",
29
+ "OperationNotAllowedWithServiceCredential",
30
+ "SensitiveReadRequiresPersonalCredential",
31
+ "ServiceResourceNotAllowed",
32
+ "ServiceCredentialUnavailable",
33
+ "ServiceCredentialDisabled",
34
+ "ServiceCredentialInvalid",
35
+ "PersonalCredentialRequired",
36
+ ]);
37
+ export function isPolicyDenial(error) {
38
+ return error instanceof IntegrationError && DENIAL_CODES.includes(error.code);
39
+ }
40
+ /**
41
+ * A deadline report reads only the budget the transport actually spent.
42
+ * No upstream address, query, body or credential enters these log fields.
43
+ */
44
+ export function transportTimeoutFields(provider, operation, error, serviceProfileId) {
45
+ if (!(error instanceof IntegrationError) ||
46
+ error.code !== "UpstreamTimeout") {
47
+ return undefined;
48
+ }
49
+ const budget = error.budget;
50
+ return {
51
+ provider,
52
+ operation,
53
+ ...(budget === undefined
54
+ ? {}
55
+ : {
56
+ timeoutMs: budget.timeoutMs,
57
+ retries: budget.retries,
58
+ attempts: budget.attempts,
59
+ }),
60
+ ...(serviceProfileId === undefined
61
+ ? {}
62
+ : { serviceProfile: serviceProfileId }),
63
+ };
64
+ }
65
+ /**
66
+ * Describe the shape of the upstream refusal, never its content. A timeout
67
+ * has its own report; an admission refusal has no upstream diagnostics.
68
+ */
69
+ export function callFailureFields(provider, integration, operation, error, serviceProfileId) {
70
+ if (!(error instanceof IntegrationError))
71
+ return undefined;
72
+ if (error.code === "UpstreamTimeout" || error.diagnostics === undefined) {
73
+ return undefined;
74
+ }
75
+ const facts = error.diagnostics;
76
+ return {
77
+ provider,
78
+ operation,
79
+ reason: error.code,
80
+ integrationId: integration.id,
81
+ credentialSource: integration.credentialSource,
82
+ ...(facts.status === undefined ? {} : { status: facts.status }),
83
+ ...(facts.contentType === undefined
84
+ ? {}
85
+ : { contentType: facts.contentType }),
86
+ ...(facts.errorClass === undefined ? {} : { errorClass: facts.errorClass }),
87
+ ...(serviceProfileId === undefined
88
+ ? {}
89
+ : { serviceProfile: serviceProfileId }),
90
+ };
91
+ }
92
+ //# sourceMappingURL=outcomes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outcomes.js","sourceRoot":"","sources":["../../src/broker/outcomes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAA6B,MAAM,cAAc,CAAC;AAI3E,sEAAsE;AACtE,MAAM,UAAU,UAAU,CACxB,MAA2C;IAE3C,QAAQ,MAAM,EAAE,MAAM,EAAE,CAAC;QACvB,KAAK,SAAS,CAAC;QACf,KAAK,SAAS;YACZ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AAE,CAAC;QAC3E,GAAG,CAAC,gBAAgB,KAAK,SAAS;YAChC,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,cAAc,EAAE,gBAAgB,EAAE,CAAC;KAC1C,CAAC;AACJ,CAAC"}
@@ -0,0 +1,93 @@
1
+ /** Provider discovery exposes descriptive metadata, with no credential. */
2
+ export function providerSummary(provider) {
3
+ return {
4
+ id: provider.id,
5
+ displayName: provider.displayName,
6
+ enabled: true,
7
+ authModes: ["token"],
8
+ capabilities: provider.capabilities,
9
+ credentialHelp: provider.credentialHelp,
10
+ };
11
+ }
12
+ /**
13
+ * The live grant is the stored grant with withdrawn capabilities removed.
14
+ * Call admission, policy edits and operator views use the same intersection.
15
+ */
16
+ export function grantedCapabilities(integration, provider, profile) {
17
+ if (integration.credentialSource === "service")
18
+ return profile?.enabled === true
19
+ ? serviceCapabilities(provider, profile.policy)
20
+ : [];
21
+ return integration.capabilities.filter((capability) => provider.capabilities.includes(capability));
22
+ }
23
+ /** Capabilities the managed credential can reach through this provider. */
24
+ export function serviceCapabilities(provider, policy) {
25
+ if (provider.capabilityServiceState === undefined)
26
+ return [];
27
+ return provider.capabilities.filter((capability) => ["available", "partial"].includes(provider.capabilityServiceState?.(capability, policy) ?? "unavailable"));
28
+ }
29
+ /** Managed capability states as the operator can see them, without a secret. */
30
+ export function serviceCapabilityStates(provider, policy) {
31
+ if (provider.capabilityServiceState === undefined)
32
+ return null;
33
+ const capabilities = {};
34
+ for (const capability of provider.capabilities) {
35
+ capabilities[capability] =
36
+ provider.capabilityServiceState(capability, policy) ?? "unavailable";
37
+ }
38
+ return Object.freeze(capabilities);
39
+ }
40
+ /**
41
+ * The caller resolves the profile; this projection reads no registry or secret
42
+ * and changes no binding. A provider without service support displays no view.
43
+ */
44
+ export function serviceSummary(capabilities, profile, selection) {
45
+ if (capabilities === null)
46
+ return null;
47
+ return {
48
+ available: profile?.enabled === true,
49
+ label: profile?.label ?? null,
50
+ resources: profile?.resources ?? null,
51
+ selection,
52
+ capabilities,
53
+ };
54
+ }
55
+ /** A provider with no binding exposes metadata but grants no policy. */
56
+ export function disconnectedSummary(providerId, provider, service) {
57
+ return {
58
+ provider: providerId,
59
+ displayName: provider.displayName,
60
+ status: "not_connected",
61
+ portal: null,
62
+ externalAccountName: null,
63
+ credentialConfigured: false,
64
+ credentialUpdatedAt: null,
65
+ capabilities: provider.capabilities,
66
+ capabilityInfo: provider.capabilityInfo,
67
+ policy: [],
68
+ lastValidatedAt: null,
69
+ errorCode: null,
70
+ credentialSource: "personal",
71
+ service,
72
+ };
73
+ }
74
+ /** Display one captured binding with its live grant and stored policy. */
75
+ export function connectedSummary(providerId, provider, integration, granted, policy, secret, service) {
76
+ return {
77
+ provider: providerId,
78
+ displayName: provider.displayName,
79
+ status: integration.status,
80
+ portal: integration.externalTenantId,
81
+ externalAccountName: integration.displayName,
82
+ credentialConfigured: secret !== undefined,
83
+ credentialUpdatedAt: secret?.updatedAt ?? null,
84
+ capabilities: granted,
85
+ capabilityInfo: provider.capabilityInfo,
86
+ policy,
87
+ lastValidatedAt: integration.lastValidatedAt,
88
+ errorCode: integration.lastErrorCode,
89
+ credentialSource: integration.credentialSource,
90
+ service,
91
+ };
92
+ }
93
+ //# sourceMappingURL=service-view.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service-view.js","sourceRoot":"","sources":["../../src/broker/service-view.ts"],"names":[],"mappings":"AAgBA,2EAA2E;AAC3E,MAAM,UAAU,eAAe,CAC7B,QAA6B;IAE7B,OAAO;QACL,EAAE,EAAE,QAAQ,CAAC,EAAE;QACf,WAAW,EAAE,QAAQ,CAAC,WAAW;QACjC,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,CAAC,OAAO,CAAC;QACpB,YAAY,EAAE,QAAQ,CAAC,YAAY;QACnC,cAAc,EAAE,QAAQ,CAAC,cAAc;KACxC,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CACjC,WAAyE,EACzE,QAA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C,MAAM;QACN,eAAe,EAAE,WAAW,CAAC,eAAe;QAC5C,SAAS,EAAE,WAAW,CAAC,aAAa;QACpC,gBAAgB,EAAE,WAAW,CAAC,gBAAgB;QAC9C,OAAO;KACR,CAAC;AACJ,CAAC"}
package/lib/broker.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { IntegrationError } from "./errors.js";
2
+ import { callFailureFields, healthCode, isPolicyDenial, refusedCredentialCode, transportTimeoutFields, } from "./broker/outcomes.js";
3
+ import { connectedSummary, disconnectedSummary, grantedCapabilities, providerSummary, serviceCapabilities, serviceCapabilityStates, serviceSummary, } from "./broker/service-view.js";
2
4
  import { DEFAULT_SERVICE_RATE_LIMIT } from "./service-credentials/config.js";
3
5
  import { ServiceRateLimitError, ServiceRateLimiter, } from "./service-credentials/rate-limit.js";
4
6
  import { evaluateServiceOperation, narrowBoundary, } from "./service-credentials/policy.js";
@@ -36,14 +38,7 @@ export class IntegrationBroker {
36
38
  this.rateLimits.configure(rateLimit);
37
39
  }
38
40
  listProviders() {
39
- return this.providers.list().map((provider) => ({
40
- id: provider.id,
41
- displayName: provider.displayName,
42
- enabled: true,
43
- authModes: ["token"],
44
- capabilities: provider.capabilities,
45
- credentialHelp: provider.credentialHelp,
46
- }));
41
+ return this.providers.list().map(providerSummary);
47
42
  }
48
43
  list(principal) {
49
44
  return this.providers
@@ -54,61 +49,29 @@ export class IntegrationBroker {
54
49
  const provider = this.providers.get(providerId);
55
50
  this.ensureDefaultServiceBinding(principal, providerId);
56
51
  const integration = this.repository.find(principal, providerId);
57
- const service = this.serviceSummary(providerId, integration);
58
- if (integration === undefined) {
59
- return {
60
- provider: providerId,
61
- displayName: provider.displayName,
62
- status: "not_connected",
63
- portal: null,
64
- externalAccountName: null,
65
- credentialConfigured: false,
66
- credentialUpdatedAt: null,
67
- capabilities: provider.capabilities,
68
- capabilityInfo: provider.capabilityInfo,
69
- // Nothing is granted yet, so nothing carries a policy either.
70
- policy: [],
71
- lastValidatedAt: null,
72
- errorCode: null,
73
- credentialSource: "personal",
74
- service,
75
- };
76
- }
52
+ const profile = provider.capabilityServiceState === undefined || integration === undefined
53
+ ? undefined
54
+ : this.serviceCredentials?.find(providerId, integration.externalTenantId ?? "");
55
+ const capabilities = serviceCapabilityStates(provider, profile?.policy);
56
+ const service = serviceSummary(capabilities, profile, integration?.serviceSelection ?? null);
57
+ if (integration === undefined)
58
+ return disconnectedSummary(providerId, provider, service);
77
59
  const granted = this.grantedCapabilities(integration, provider);
78
60
  const policy = granted.map((capability) => ({
79
61
  capability,
80
- mode: this.repository.policy(integration, capability),
62
+ mode: this.repository.policy(integration, capability, integration.credentialSource === "service" ? "allow" : "deny"),
81
63
  }));
82
64
  const secret = this.repository.secretFor(principal, providerId);
83
- return {
84
- provider: providerId,
85
- displayName: provider.displayName,
86
- status: integration.status,
87
- portal: integration.externalTenantId,
88
- externalAccountName: integration.displayName,
89
- credentialConfigured: secret !== undefined,
90
- credentialUpdatedAt: secret?.updatedAt ?? null,
91
- capabilities: granted,
92
- capabilityInfo: provider.capabilityInfo,
93
- policy,
94
- lastValidatedAt: integration.lastValidatedAt,
95
- errorCode: integration.lastErrorCode,
96
- credentialSource: integration.credentialSource,
97
- service,
98
- };
65
+ return connectedSummary(providerId, provider, integration, granted, policy, secret, service);
99
66
  }
100
- /**
101
- * The capabilities a connection may use as it stands: the stored grant, with
102
- * anything this deployment has since withdrawn from the provider removed.
103
- * Everything that decides or displays the reach of a connection reads through
104
- * here — the call gate, the operator card, and the policy editor — so a
105
- * capability the deployment has taken away is neither served, nor offered as a
106
- * switch, nor able to collect a fresh allowance. A grant that survives only in
107
- * the database stops being served, rather than running until the connection is
108
- * next established.
109
- */
110
67
  grantedCapabilities(integration, provider) {
111
- return integration.capabilities.filter((capability) => provider.capabilities.includes(capability));
68
+ const profile = integration.credentialSource === "service"
69
+ ? this.serviceCredentials?.find(provider.id, integration.externalTenantId ?? "")
70
+ : undefined;
71
+ return grantedCapabilities(integration, provider, profile);
72
+ }
73
+ serviceCapabilities(providerId, profile) {
74
+ return serviceCapabilities(this.providers.get(providerId), profile?.policy);
112
75
  }
113
76
  /**
114
77
  * Connect one provider for one principal. The credential source is decided
@@ -147,7 +110,7 @@ export class IntegrationBroker {
147
110
  tenantId: profile.portal,
148
111
  externalUserId: `service:${profile.id}`,
149
112
  displayName: profile.label,
150
- capabilities: this.serviceCapabilities(providerId),
113
+ capabilities: this.serviceCapabilities(providerId, profile),
151
114
  credentialSource: "service",
152
115
  serviceProfileId: profile.id,
153
116
  });
@@ -281,7 +244,9 @@ export class IntegrationBroker {
281
244
  // A probe the upstream never answered is the same invisible failure as a
282
245
  // read that did: the row goes to `error` and nothing says the deadline
283
246
  // ended the probe rather than the credential being wrong.
284
- this.logTransportTimeout(providerId, "credential.validate", error);
247
+ const timeoutFields = transportTimeoutFields(providerId, "credential.validate", error);
248
+ if (timeoutFields !== undefined)
249
+ this.logger.warn("transport.timeout", timeoutFields);
285
250
  throw error;
286
251
  }
287
252
  }
@@ -374,7 +339,7 @@ export class IntegrationBroker {
374
339
  provider: providerId,
375
340
  source: "service",
376
341
  serviceProfileId: resolved.profile.id,
377
- capabilities: this.serviceCapabilities(providerId),
342
+ capabilities: this.serviceCapabilities(providerId, resolved.profile),
378
343
  tenantId: resolved.profile.portal,
379
344
  externalUserId: `service:${resolved.profile.id}`,
380
345
  displayName: resolved.profile.label,
@@ -542,7 +507,7 @@ export class IntegrationBroker {
542
507
  // has since withdrawn stays served until the connection is re-established
543
508
  // unless the live provider set is consulted as well. Denied here — before
544
509
  // the secret is decrypted and before anything reaches upstream.
545
- const mode = this.repository.policy(integration, capability);
510
+ const mode = this.repository.policy(integration, capability, integration.credentialSource === "service" ? "allow" : "deny");
546
511
  if (mode !== "allow" ||
547
512
  !this.grantedCapabilities(integration, provider).includes(capability)) {
548
513
  this.repository.audit({
@@ -573,6 +538,7 @@ export class IntegrationBroker {
573
538
  externalUserId: integration.externalUserId ?? undefined,
574
539
  credentialSource: integration.credentialSource,
575
540
  resourceBoundary: boundary,
541
+ serviceOperationPolicy: resolved?.profile.policy,
576
542
  }, request.operation, request.input);
577
543
  const data = typeof providerData === "object" &&
578
544
  providerData !== null &&
@@ -615,50 +581,19 @@ export class IntegrationBroker {
615
581
  serviceProfileId: resolved?.profile.id ?? null,
616
582
  sourceSessionId: request.sourceSessionId,
617
583
  });
618
- this.logTransportTimeout(request.provider, request.operation, error, resolved?.profile.id);
584
+ const timeoutFields = transportTimeoutFields(request.provider, request.operation, error, resolved?.profile.id);
585
+ if (timeoutFields !== undefined)
586
+ this.logger.warn("transport.timeout", timeoutFields);
619
587
  this.recordCallVerdict(principal, integration, error);
620
- this.logCallFailure(request.provider, integration, request.operation, error, resolved?.profile.id);
588
+ const failureFields = callFailureFields(request.provider, integration, request.operation, error, resolved?.profile.id);
589
+ if (failureFields !== undefined)
590
+ this.logger.warn("tool.call-failed", failureFields);
621
591
  throw error;
622
592
  }
623
593
  finally {
624
594
  releaseSlot?.();
625
595
  }
626
596
  }
627
- /**
628
- * Record a call this deployment's own deadline ended.
629
- *
630
- * Without it the failure is invisible where an operator looks for it: the
631
- * audit row says `error`, the trail of the reason code is the chat, and the
632
- * log — the one surface that outlives both — carried nothing about a provider
633
- * that stopped answering. The provider and the operation are this call's; the
634
- * deadline and the attempts come written on the error by the transport loop
635
- * that spent them, which is the only party that ever knew them.
636
- *
637
- * Nothing upstream is named here: no address, no query, no body, no
638
- * credential. Numbers, a provider id and an operation are enough to find the
639
- * call again in the trail.
640
- */
641
- logTransportTimeout(provider, operation, error, serviceProfileId) {
642
- if (!(error instanceof IntegrationError) ||
643
- error.code !== "UpstreamTimeout") {
644
- return;
645
- }
646
- const budget = error.budget;
647
- this.logger.warn("transport.timeout", {
648
- provider,
649
- operation,
650
- ...(budget === undefined
651
- ? {}
652
- : {
653
- timeoutMs: budget.timeoutMs,
654
- retries: budget.retries,
655
- attempts: budget.attempts,
656
- }),
657
- ...(serviceProfileId === undefined
658
- ? {}
659
- : { serviceProfile: serviceProfileId }),
660
- });
661
- }
662
597
  /**
663
598
  * Write what one live call learned about its binding back onto that binding.
664
599
  *
@@ -676,11 +611,10 @@ export class IntegrationBroker {
676
611
  * problem.
677
612
  */
678
613
  recordCallVerdict(principal, integration, error) {
679
- if (!(error instanceof IntegrationError))
614
+ const code = refusedCredentialCode(error);
615
+ if (code === undefined)
680
616
  return;
681
- if (!REFUSED_CREDENTIAL_CODES.includes(error.code))
682
- return;
683
- this.recordValidation(principal, integration.provider, integration, false, error.code);
617
+ this.recordValidation(principal, integration.provider, integration, false, code);
684
618
  }
685
619
  /**
686
620
  * Clear the verdict an earlier live call filed, once a later call got data
@@ -694,45 +628,6 @@ export class IntegrationBroker {
694
628
  return;
695
629
  this.recordValidation(principal, integration.provider, integration, true, null);
696
630
  }
697
- /**
698
- * Say in this plugin's own log what a refused live call met.
699
- *
700
- * The chat carries the sentence the model was shown, the audit trail carries
701
- * the result, and neither is where an operator looks; before this a live
702
- * refusal left no line behind at all. The fields describe the shape of the
703
- * answer — its status, its media type, the class of the transport failure —
704
- * never its body, and never a credential.
705
- *
706
- * Two refusals are left to their own records: a call this deployment's
707
- * deadline ended is `transport.timeout`, budget and all, and a refusal decided
708
- * without any answer — a policy switch, a connection that is not there — has
709
- * no upstream to report on, which is what the absence of diagnostics says.
710
- */
711
- logCallFailure(provider, integration, operation, error, serviceProfileId) {
712
- if (!(error instanceof IntegrationError))
713
- return;
714
- if (error.code === "UpstreamTimeout" || error.diagnostics === undefined) {
715
- return;
716
- }
717
- const facts = error.diagnostics;
718
- this.logger.warn("tool.call-failed", {
719
- provider,
720
- operation,
721
- reason: error.code,
722
- integrationId: integration.id,
723
- credentialSource: integration.credentialSource,
724
- ...(facts.status === undefined ? {} : { status: facts.status }),
725
- ...(facts.contentType === undefined
726
- ? {}
727
- : { contentType: facts.contentType }),
728
- ...(facts.errorClass === undefined
729
- ? {}
730
- : { errorClass: facts.errorClass }),
731
- ...(serviceProfileId === undefined
732
- ? {}
733
- : { serviceProfile: serviceProfileId }),
734
- });
735
- }
736
631
  /**
737
632
  * Spend one unit of the service-mode ceiling before the call leaves for
738
633
  * upstream. Both sides of the limit are consulted together: one principal may
@@ -798,6 +693,7 @@ export class IntegrationBroker {
798
693
  }
799
694
  const decision = evaluateServiceOperation({
800
695
  metadata: query.metadata,
696
+ operation: query.operation,
801
697
  capability: query.capability,
802
698
  profile: resolved.profile,
803
699
  boundaryKind: query.boundaryKind,
@@ -858,7 +754,7 @@ export class IntegrationBroker {
858
754
  tenantId: profile.portal,
859
755
  externalUserId: `service:${profile.id}`,
860
756
  displayName: profile.label,
861
- capabilities: this.serviceCapabilities(providerId),
757
+ capabilities: this.serviceCapabilities(providerId, profile),
862
758
  credentialSource: "service",
863
759
  serviceProfileId: profile.id,
864
760
  });
@@ -915,38 +811,6 @@ export class IntegrationBroker {
915
811
  resourceBoundary: resolved.profile.resources,
916
812
  });
917
813
  }
918
- /** Capabilities the managed credential can reach through this provider. */
919
- serviceCapabilities(providerId) {
920
- const provider = this.providers.get(providerId);
921
- if (provider.capabilityServiceState === undefined)
922
- return [];
923
- return provider.capabilities.filter((capability) => provider.capabilityServiceState?.(capability) === "available");
924
- }
925
- /**
926
- * Managed-credential state of one provider, as a client renders it. Null for a
927
- * provider that supports no managed credential at all, so nothing about the
928
- * feature appears where it does not apply.
929
- */
930
- serviceSummary(providerId, integration) {
931
- const provider = this.providers.get(providerId);
932
- if (provider.capabilityServiceState === undefined)
933
- return null;
934
- const capabilities = {};
935
- for (const capability of provider.capabilities) {
936
- capabilities[capability] =
937
- provider.capabilityServiceState(capability) ?? "unavailable";
938
- }
939
- const profile = integration === undefined
940
- ? undefined
941
- : this.serviceCredentials?.find(providerId, integration.externalTenantId ?? "");
942
- return {
943
- available: profile?.enabled === true,
944
- label: profile?.label ?? null,
945
- resources: profile?.resources ?? null,
946
- selection: integration?.serviceSelection ?? null,
947
- capabilities: Object.freeze(capabilities),
948
- };
949
- }
950
814
  requireConnected(principal, provider) {
951
815
  const integration = this.repository.find(principal, provider);
952
816
  if (integration === undefined ||
@@ -989,40 +853,4 @@ export class IntegrationBroker {
989
853
  }
990
854
  }
991
855
  }
992
- /** What a probe verdict means for the stored binding, if anything. */
993
- function healthCode(health) {
994
- switch (health?.status) {
995
- case undefined:
996
- case "healthy":
997
- return undefined;
998
- case "expired":
999
- return "CredentialExpired";
1000
- case "revoked":
1001
- return "CredentialRevoked";
1002
- case "unsafe_scope":
1003
- return "ServiceCredentialUnsafeScope";
1004
- default:
1005
- return "ProviderUnavailable";
1006
- }
1007
- }
1008
- /**
1009
- * Codes that mean the binding's own credential was refused, wherever the
1010
- * upstream said so — a rejected token, an expired one, a redirect to a sign-in
1011
- * page. They are the ones the operator's card can act on by reconnecting.
1012
- */
1013
- const REFUSED_CREDENTIAL_CODES = Object.freeze(["CredentialExpired", "CredentialRevoked", "InvalidCredential"]);
1014
- /** Codes that mean "policy refused this", wherever the refusal was decided. */
1015
- const DENIAL_CODES = Object.freeze([
1016
- "OperationDeniedByPolicy",
1017
- "OperationNotAllowedWithServiceCredential",
1018
- "SensitiveReadRequiresPersonalCredential",
1019
- "ServiceResourceNotAllowed",
1020
- "ServiceCredentialUnavailable",
1021
- "ServiceCredentialDisabled",
1022
- "ServiceCredentialInvalid",
1023
- "PersonalCredentialRequired",
1024
- ]);
1025
- function isPolicyDenial(error) {
1026
- return error instanceof IntegrationError && DENIAL_CODES.includes(error.code);
1027
- }
1028
856
  //# sourceMappingURL=broker.js.map