@open-mercato/tillio 0.10.1-develop.7803.1.e99e862b4e → 0.10.1-develop.7807.1.9b2b8953e9

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.
@@ -147,11 +147,16 @@ async function detachOperator(deps, operatorId, options = {}) {
147
147
  }
148
148
  }
149
149
  }
150
- const remaining = blob.operators.filter((entry) => entry.id !== operatorId);
151
- await saveOperatorsBlob(deps.credentialsService, deps.scope, {
152
- operators: remaining,
153
- defaultOperatorId: blob.defaultOperatorId === operatorId ? remaining[0]?.id ?? null : blob.defaultOperatorId
154
- });
150
+ const current = await readOperatorsBlob(deps.credentialsService, deps.scope);
151
+ const remaining = current.operators.filter(
152
+ (entry) => entry.id !== operatorId || entry.token !== operator.token
153
+ );
154
+ if (remaining.length < current.operators.length) {
155
+ await saveOperatorsBlob(deps.credentialsService, deps.scope, {
156
+ operators: remaining,
157
+ defaultOperatorId: current.defaultOperatorId === operatorId ? remaining[0]?.id ?? null : current.defaultOperatorId
158
+ });
159
+ }
155
160
  return { ok: true, detached: true, revoked };
156
161
  }
157
162
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/tillio/lib/operators.ts"],
4
- "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { IntegrationScope } from '@open-mercato/shared/modules/integrations/types'\nimport { TillioApiError } from './errors'\nimport { createTillioClient } from './client'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { IntegrationState } from '@open-mercato/core/modules/integrations/data/entities'\nimport { environmentSchema, readTenantSystemId } from './environment'\nimport type { TillioLockRunner } from './locking'\nimport { TILLIO_TIMEZONE } from './tz'\nimport { TILLIO_INTEGRATION_ID } from '../integration'\nimport {\n buildTenantDomain,\n computeEnvFingerprint,\n operatorPluginSchema,\n readOperatorsBlob,\n ringostatConfigSchema,\n saveOperatorsBlob,\n type TillioCredentialsService,\n type TillioOperatorPlugin,\n type TillioOperatorRecord,\n} from './operators-store'\n\nconst logger = createLogger('tillio').child({ component: 'operators' })\n\nexport type TillioResolvedEnvironment = {\n apiUrl: string\n apiKey: string\n tenantSystemId: string\n timeZone: string\n}\n\nexport const TILLIO_OPERATOR_RESOURCE_KIND = 'tillio.operator'\n\nexport type OperatorErrorSection = 'environment' | 'operator'\n\nexport class TillioEnvironmentNotReadyError extends Error {\n constructor(message = 'The Tillio environment is not ready. Save credentials and run the health check first.') {\n super(message)\n this.name = 'TillioEnvironmentNotReadyError'\n }\n}\n\nexport class TillioOperatorLimitError extends Error {\n constructor(message = 'An operator is already attached. Detach it before attaching another one.') {\n super(message)\n this.name = 'TillioOperatorLimitError'\n }\n}\n\n/**\n * Raised when the operator's token could not be revoked at Tillio. The local record stays in\n * place, because dropping it would leave a live token nobody holds a handle to any more.\n * `environmentMissing` separates the two outcomes for the caller: a provider failure is worth\n * retrying, a missing environment is not \u2014 it needs the credentials fixed, or a forced detach.\n */\nexport class TillioRevocationFailedError extends Error {\n readonly environmentMissing: boolean\n\n constructor(environmentMissing: boolean, message?: string) {\n super(\n message\n ?? (environmentMissing\n ? 'The Tillio environment is no longer configured, so the operator token cannot be revoked.'\n : 'Tillio did not confirm the operator token was revoked.'),\n )\n this.name = 'TillioRevocationFailedError'\n this.environmentMissing = environmentMissing\n }\n}\n\nexport function classifyTillioError(err: unknown): OperatorErrorSection {\n if (err instanceof TillioApiError) {\n if (err.status === 0 || err.status === 401 || err.status === 403) return 'environment'\n }\n return 'operator'\n}\n\nexport async function resolveEnvironment(\n credentialsService: TillioCredentialsService,\n scope: IntegrationScope,\n): Promise<TillioResolvedEnvironment | null> {\n const raw = await credentialsService.getRaw(TILLIO_INTEGRATION_ID, scope)\n const parsed = environmentSchema.safeParse(raw ?? {})\n if (!parsed.success) return null\n // Falls back to the legacy location until the next health check moves the identity across.\n const tenantSystemId = (await readTenantSystemId(credentialsService, scope)) ?? parsed.data.tenantSystemId\n if (!tenantSystemId) return null\n return {\n apiUrl: parsed.data.apiUrl,\n apiKey: parsed.data.apiKey,\n tenantSystemId,\n timeZone: parsed.data.timeZone ?? TILLIO_TIMEZONE,\n }\n}\n\nexport type TillioIntegrationState = {\n /** The administrator's switch. Provisioning and sweeps stay off while it is false. */\n enabled: boolean\n /** The last probe result. Says Tillio answers, not that anybody wants us talking to it. */\n healthy: boolean\n}\n\n// Both signals come off one row, and they fail for different reasons a user fixes in different\n// places, so callers get them apart rather than folded into a single boolean. A missing row\n// reads as disabled, matching `integrationStateService.resolveState`, which falls back to the\n// descriptor's `defaultState` and to `false` without one. The Tillio descriptor declares no\n// `defaultState`, so adding one there means switching this over to that service.\nexport async function readTillioIntegrationState(\n em: EntityManager,\n scope: IntegrationScope,\n): Promise<TillioIntegrationState> {\n const state = await findOneWithDecryption(\n em,\n IntegrationState,\n {\n integrationId: TILLIO_INTEGRATION_ID,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n deletedAt: null,\n },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n return {\n enabled: state?.isEnabled ?? false,\n healthy: state?.lastHealthStatus === 'healthy',\n }\n}\n\nfunction operatorIdForPlugin(plugin: TillioOperatorPlugin): string {\n return `${plugin.toLowerCase()}-1`\n}\n\nfunction normalizeOperatorConfig(plugin: TillioOperatorPlugin, config: Record<string, unknown>): Record<string, unknown> {\n if (plugin === 'Ringostat') return ringostatConfigSchema.parse(config)\n return config\n}\n\nexport type AttachOperatorDeps = {\n credentialsService: TillioCredentialsService\n scope: IntegrationScope\n appUrl: string\n /**\n * Serializes the slot check and the write. Required rather than optional so a new call site\n * has to decide: passing `(run) => run()` says the caller knows it cannot contend.\n */\n withLock: TillioLockRunner\n}\n\nexport type AttachOperatorInput = {\n plugin: TillioOperatorPlugin\n config: Record<string, unknown>\n label?: string\n}\n\nexport async function attachOperator(\n deps: AttachOperatorDeps,\n input: AttachOperatorInput,\n): Promise<TillioOperatorRecord> {\n const plugin = operatorPluginSchema.parse(input.plugin)\n const config = normalizeOperatorConfig(plugin, input.config)\n\n const environment = await resolveEnvironment(deps.credentialsService, deps.scope)\n if (!environment) throw new TillioEnvironmentNotReadyError()\n\n const blob = await readOperatorsBlob(deps.credentialsService, deps.scope)\n if (blob.operators.length > 0) throw new TillioOperatorLimitError()\n\n const operatorId = operatorIdForPlugin(plugin)\n const tenantDomain = buildTenantDomain(deps.appUrl, environment.tenantSystemId, operatorId)\n const client = createTillioClient(environment)\n\n await client.validateConfig(plugin, config, tenantDomain)\n const { token } = await client.addConfig(plugin, config, tenantDomain)\n\n const record: TillioOperatorRecord = {\n id: operatorId,\n plugin,\n ...(input.label ? { label: input.label } : {}),\n config,\n token,\n tenantDomain,\n // Pins the operator to the environment that issued its token. If the environment is later\n // edited the pairing is stale, and comparing this fingerprint is what raises `environment_drift`\n // instead of pulling against an instance the operator never belonged to.\n envFingerprint: computeEnvFingerprint(environment),\n }\n\n try {\n // The remote calls above stay outside the lock: holding a database transaction while\n // waiting on Tillio would tie a connection to their latency. Inside it, the slot is\n // re-checked and written as one step, so a concurrent attach either loses here and is\n // undone below, or wins and is the only stored operator.\n await deps.withLock(async () => {\n const current = await readOperatorsBlob(deps.credentialsService, deps.scope)\n if (current.operators.length > 0) throw new TillioOperatorLimitError()\n\n await saveOperatorsBlob(deps.credentialsService, deps.scope, {\n operators: [record],\n defaultOperatorId: operatorId,\n })\n })\n } catch (err) {\n // `addConfig` already registered this operator on Tillio's side. If we cannot persist it\n // locally we would lose the only reference to that remote config, so undo it before failing.\n await client.deleteConfig(plugin, token, tenantDomain).catch((revokeErr: unknown) => {\n logger.error('could not roll back the remote operator config', { operatorId, err: revokeErr })\n })\n throw err\n }\n\n return record\n}\n\nexport type DetachOperatorDeps = {\n credentialsService: TillioCredentialsService\n scope: IntegrationScope\n}\n\nexport type DetachOperatorOptions = {\n /**\n * Drop the local record even though the token could not be revoked. The caller has to\n * decide this explicitly, because the token stays live on Tillio's side afterwards.\n */\n force?: boolean\n}\n\nexport async function detachOperator(\n deps: DetachOperatorDeps,\n operatorId: string,\n options: DetachOperatorOptions = {},\n): Promise<{ ok: boolean; detached: boolean; revoked: boolean }> {\n const blob = await readOperatorsBlob(deps.credentialsService, deps.scope)\n const operator = blob.operators.find((entry) => entry.id === operatorId)\n if (!operator) return { ok: true, detached: false, revoked: false }\n\n const environment = await resolveEnvironment(deps.credentialsService, deps.scope)\n let revoked = false\n if (!environment) {\n if (!options.force) throw new TillioRevocationFailedError(true)\n } else {\n try {\n const client = createTillioClient(environment)\n await client.deleteConfig(operator.plugin, operator.token, operator.tenantDomain)\n revoked = true\n } catch (err) {\n logger.error('could not revoke the Tillio operator token', {\n operatorId,\n status: err instanceof TillioApiError ? err.status : undefined,\n detail: err instanceof TillioApiError ? err.detail : undefined,\n err,\n })\n if (!options.force) {\n throw new TillioRevocationFailedError(false)\n }\n }\n }\n\n const remaining = blob.operators.filter((entry) => entry.id !== operatorId)\n await saveOperatorsBlob(deps.credentialsService, deps.scope, {\n operators: remaining,\n defaultOperatorId: blob.defaultOperatorId === operatorId\n ? (remaining[0]?.id ?? null)\n : blob.defaultOperatorId,\n })\n\n return { ok: true, detached: true, revoked }\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAE7B,SAAS,sBAAsB;AAC/B,SAAS,0BAA0B;AAEnC,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAS,mBAAmB,0BAA0B;AAEtD,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAEP,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,YAAY,CAAC;AAS/D,MAAM,gCAAgC;AAItC,MAAM,uCAAuC,MAAM;AAAA,EACxD,YAAY,UAAU,yFAAyF;AAC7G,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,E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OACrB,KAAK;AAAA,EACX,CAAC;AAED,SAAO,EAAE,IAAI,MAAM,UAAU,MAAM,QAAQ;AAC7C;",
4
+ "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { IntegrationScope } from '@open-mercato/shared/modules/integrations/types'\nimport { TillioApiError } from './errors'\nimport { createTillioClient } from './client'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { IntegrationState } from '@open-mercato/core/modules/integrations/data/entities'\nimport { environmentSchema, readTenantSystemId } from './environment'\nimport type { TillioLockRunner } from './locking'\nimport { TILLIO_TIMEZONE } from './tz'\nimport { TILLIO_INTEGRATION_ID } from '../integration'\nimport {\n buildTenantDomain,\n computeEnvFingerprint,\n operatorPluginSchema,\n readOperatorsBlob,\n ringostatConfigSchema,\n saveOperatorsBlob,\n type TillioCredentialsService,\n type TillioOperatorPlugin,\n type TillioOperatorRecord,\n} from './operators-store'\n\nconst logger = createLogger('tillio').child({ component: 'operators' })\n\nexport type TillioResolvedEnvironment = {\n apiUrl: string\n apiKey: string\n tenantSystemId: string\n timeZone: string\n}\n\nexport const TILLIO_OPERATOR_RESOURCE_KIND = 'tillio.operator'\n\nexport type OperatorErrorSection = 'environment' | 'operator'\n\nexport class TillioEnvironmentNotReadyError extends Error {\n constructor(message = 'The Tillio environment is not ready. Save credentials and run the health check first.') {\n super(message)\n this.name = 'TillioEnvironmentNotReadyError'\n }\n}\n\nexport class TillioOperatorLimitError extends Error {\n constructor(message = 'An operator is already attached. Detach it before attaching another one.') {\n super(message)\n this.name = 'TillioOperatorLimitError'\n }\n}\n\n/**\n * Raised when the operator's token could not be revoked at Tillio. The local record stays in\n * place, because dropping it would leave a live token nobody holds a handle to any more.\n * `environmentMissing` separates the two outcomes for the caller: a provider failure is worth\n * retrying, a missing environment is not \u2014 it needs the credentials fixed, or a forced detach.\n */\nexport class TillioRevocationFailedError extends Error {\n readonly environmentMissing: boolean\n\n constructor(environmentMissing: boolean, message?: string) {\n super(\n message\n ?? (environmentMissing\n ? 'The Tillio environment is no longer configured, so the operator token cannot be revoked.'\n : 'Tillio did not confirm the operator token was revoked.'),\n )\n this.name = 'TillioRevocationFailedError'\n this.environmentMissing = environmentMissing\n }\n}\n\nexport function classifyTillioError(err: unknown): OperatorErrorSection {\n if (err instanceof TillioApiError) {\n if (err.status === 0 || err.status === 401 || err.status === 403) return 'environment'\n }\n return 'operator'\n}\n\nexport async function resolveEnvironment(\n credentialsService: TillioCredentialsService,\n scope: IntegrationScope,\n): Promise<TillioResolvedEnvironment | null> {\n const raw = await credentialsService.getRaw(TILLIO_INTEGRATION_ID, scope)\n const parsed = environmentSchema.safeParse(raw ?? {})\n if (!parsed.success) return null\n // Falls back to the legacy location until the next health check moves the identity across.\n const tenantSystemId = (await readTenantSystemId(credentialsService, scope)) ?? parsed.data.tenantSystemId\n if (!tenantSystemId) return null\n return {\n apiUrl: parsed.data.apiUrl,\n apiKey: parsed.data.apiKey,\n tenantSystemId,\n timeZone: parsed.data.timeZone ?? TILLIO_TIMEZONE,\n }\n}\n\nexport type TillioIntegrationState = {\n /** The administrator's switch. Provisioning and sweeps stay off while it is false. */\n enabled: boolean\n /** The last probe result. Says Tillio answers, not that anybody wants us talking to it. */\n healthy: boolean\n}\n\n// Both signals come off one row, and they fail for different reasons a user fixes in different\n// places, so callers get them apart rather than folded into a single boolean. A missing row\n// reads as disabled, matching `integrationStateService.resolveState`, which falls back to the\n// descriptor's `defaultState` and to `false` without one. The Tillio descriptor declares no\n// `defaultState`, so adding one there means switching this over to that service.\nexport async function readTillioIntegrationState(\n em: EntityManager,\n scope: IntegrationScope,\n): Promise<TillioIntegrationState> {\n const state = await findOneWithDecryption(\n em,\n IntegrationState,\n {\n integrationId: TILLIO_INTEGRATION_ID,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n deletedAt: null,\n },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n return {\n enabled: state?.isEnabled ?? false,\n healthy: state?.lastHealthStatus === 'healthy',\n }\n}\n\nfunction operatorIdForPlugin(plugin: TillioOperatorPlugin): string {\n return `${plugin.toLowerCase()}-1`\n}\n\nfunction normalizeOperatorConfig(plugin: TillioOperatorPlugin, config: Record<string, unknown>): Record<string, unknown> {\n if (plugin === 'Ringostat') return ringostatConfigSchema.parse(config)\n return config\n}\n\nexport type AttachOperatorDeps = {\n credentialsService: TillioCredentialsService\n scope: IntegrationScope\n appUrl: string\n /**\n * Serializes the slot check and the write. Required rather than optional so a new call site\n * has to decide: passing `(run) => run()` says the caller knows it cannot contend.\n */\n withLock: TillioLockRunner\n}\n\nexport type AttachOperatorInput = {\n plugin: TillioOperatorPlugin\n config: Record<string, unknown>\n label?: string\n}\n\nexport async function attachOperator(\n deps: AttachOperatorDeps,\n input: AttachOperatorInput,\n): Promise<TillioOperatorRecord> {\n const plugin = operatorPluginSchema.parse(input.plugin)\n const config = normalizeOperatorConfig(plugin, input.config)\n\n const environment = await resolveEnvironment(deps.credentialsService, deps.scope)\n if (!environment) throw new TillioEnvironmentNotReadyError()\n\n const blob = await readOperatorsBlob(deps.credentialsService, deps.scope)\n if (blob.operators.length > 0) throw new TillioOperatorLimitError()\n\n const operatorId = operatorIdForPlugin(plugin)\n const tenantDomain = buildTenantDomain(deps.appUrl, environment.tenantSystemId, operatorId)\n const client = createTillioClient(environment)\n\n await client.validateConfig(plugin, config, tenantDomain)\n const { token } = await client.addConfig(plugin, config, tenantDomain)\n\n const record: TillioOperatorRecord = {\n id: operatorId,\n plugin,\n ...(input.label ? { label: input.label } : {}),\n config,\n token,\n tenantDomain,\n // Pins the operator to the environment that issued its token. If the environment is later\n // edited the pairing is stale, and comparing this fingerprint is what raises `environment_drift`\n // instead of pulling against an instance the operator never belonged to.\n envFingerprint: computeEnvFingerprint(environment),\n }\n\n try {\n // The remote calls above stay outside the lock: holding a database transaction while\n // waiting on Tillio would tie a connection to their latency. Inside it, the slot is\n // re-checked and written as one step, so a concurrent attach either loses here and is\n // undone below, or wins and is the only stored operator.\n await deps.withLock(async () => {\n const current = await readOperatorsBlob(deps.credentialsService, deps.scope)\n if (current.operators.length > 0) throw new TillioOperatorLimitError()\n\n await saveOperatorsBlob(deps.credentialsService, deps.scope, {\n operators: [record],\n defaultOperatorId: operatorId,\n })\n })\n } catch (err) {\n // `addConfig` already registered this operator on Tillio's side. If we cannot persist it\n // locally we would lose the only reference to that remote config, so undo it before failing.\n await client.deleteConfig(plugin, token, tenantDomain).catch((revokeErr: unknown) => {\n logger.error('could not roll back the remote operator config', { operatorId, err: revokeErr })\n })\n throw err\n }\n\n return record\n}\n\nexport type DetachOperatorDeps = {\n credentialsService: TillioCredentialsService\n scope: IntegrationScope\n}\n\nexport type DetachOperatorOptions = {\n /**\n * Drop the local record even though the token could not be revoked. The caller has to\n * decide this explicitly, because the token stays live on Tillio's side afterwards.\n */\n force?: boolean\n}\n\nexport async function detachOperator(\n deps: DetachOperatorDeps,\n operatorId: string,\n options: DetachOperatorOptions = {},\n): Promise<{ ok: boolean; detached: boolean; revoked: boolean }> {\n const blob = await readOperatorsBlob(deps.credentialsService, deps.scope)\n const operator = blob.operators.find((entry) => entry.id === operatorId)\n if (!operator) return { ok: true, detached: false, revoked: false }\n\n const environment = await resolveEnvironment(deps.credentialsService, deps.scope)\n let revoked = false\n if (!environment) {\n if (!options.force) throw new TillioRevocationFailedError(true)\n } else {\n try {\n const client = createTillioClient(environment)\n await client.deleteConfig(operator.plugin, operator.token, operator.tenantDomain)\n revoked = true\n } catch (err) {\n logger.error('could not revoke the Tillio operator token', {\n operatorId,\n status: err instanceof TillioApiError ? err.status : undefined,\n detail: err instanceof TillioApiError ? err.detail : undefined,\n err,\n })\n if (!options.force) {\n throw new TillioRevocationFailedError(false)\n }\n }\n }\n\n const current = await readOperatorsBlob(deps.credentialsService, deps.scope)\n const remaining = current.operators.filter(\n (entry) => entry.id !== operatorId || entry.token !== operator.token,\n )\n if (remaining.length < current.operators.length) {\n await saveOperatorsBlob(deps.credentialsService, deps.scope, {\n operators: remaining,\n defaultOperatorId: current.defaultOperatorId === operatorId\n ? (remaining[0]?.id ?? null)\n : current.defaultOperatorId,\n })\n }\n\n return { ok: true, detached: true, revoked }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAE7B,SAAS,sBAAsB;AAC/B,SAAS,0BAA0B;AAEnC,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAS,mBAAmB,0BAA0B;AAEtD,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAEP,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,YAAY,CAAC;AAS/D,MAAM,gCAAgC;AAItC,MAAM,uCAAuC,MAAM;AAAA,EACxD,YAAY,UAAU,yFAAyF;AAC7G,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,iCAAiC,MAAM;AAAA,EAClD,YAAY,UAAU,4EAA4E;AAChG,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAQO,MAAM,oCAAoC,MAAM;AAAA,EAGrD,YAAY,oBAA6B,SAAkB;AACzD;AAAA,MACE,YACM,qBACA,6FACA;AAAA,IACR;AACA,SAAK,OAAO;AACZ,SAAK,qBAAqB;AAAA,EAC5B;AACF;AAEO,SAAS,oBAAoB,KAAoC;AACtE,MAAI,eAAe,gBAAgB;AACjC,QAAI,IAAI,WAAW,KAAK,IAAI,WAAW,OAAO,IAAI,WAAW,IAAK,QAAO;AAAA,EAC3E;AACA,SAAO;AACT;AAEA,eAAsB,mBACpB,oBACA,OAC2C;AAC3C,QAAM,MAAM,MAAM,mBAAmB,OAAO,uBAAuB,KAAK;AACxE,QAAM,SAAS,kBAAkB,UAAU,OAAO,CAAC,CAAC;AACpD,MAAI,CAAC,OAAO,QAAS,QAAO;AAE5B,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AI;AAAA,EAChE,OAAO;AACL,QAAI;AACF,YAAM,SAAS,mBAAmB,WAAW;AAC7C,YAAM,OAAO,aAAa,SAAS,QAAQ,SAAS,OAAO,SAAS,YAAY;AAChF,gBAAU;AAAA,IACZ,SAAS,KAAK;AACZ,aAAO,MAAM,8CAA8C;AAAA,QACzD;AAAA,QACA,QAAQ,eAAe,iBAAiB,IAAI,SAAS;AAAA,QACrD,QAAQ,eAAe,iBAAiB,IAAI,SAAS;AAAA,QACrD;AAAA,MACF,CAAC;AACD,UAAI,CAAC,QAAQ,OAAO;AAClB,cAAM,IAAI,4BAA4B,KAAK;AAAA,MAC7C;AAAA,IACF;AAAA,EACF;AAEA,QAAM,UAAU,MAAM,kBAAkB,KAAK,oBAAoB,KAAK,KAAK;AAC3E,QAAM,YAAY,QAAQ,UAAU;AAAA,IAClC,CAAC,UAAU,MAAM,OAAO,cAAc,MAAM,UAAU,SAAS;AAAA,EACjE;AACA,MAAI,UAAU,SAAS,QAAQ,UAAU,QAAQ;AAC/C,UAAM,kBAAkB,KAAK,oBAAoB,KAAK,OAAO;AAAA,MAC3D,WAAW;AAAA,MACX,mBAAmB,QAAQ,sBAAsB,aAC5C,UAAU,CAAC,GAAG,MAAM,OACrB,QAAQ;AAAA,IACd,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,IAAI,MAAM,UAAU,MAAM,QAAQ;AAC7C;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/tillio",
3
- "version": "0.10.1-develop.7803.1.e99e862b4e",
3
+ "version": "0.10.1-develop.7807.1.9b2b8953e9",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -53,21 +53,21 @@
53
53
  }
54
54
  },
55
55
  "dependencies": {
56
- "@open-mercato/core": "0.10.1-develop.7803.1.e99e862b4e",
57
- "@open-mercato/queue": "0.10.1-develop.7803.1.e99e862b4e",
58
- "@open-mercato/ui": "0.10.1-develop.7803.1.e99e862b4e"
56
+ "@open-mercato/core": "0.10.1-develop.7807.1.9b2b8953e9",
57
+ "@open-mercato/queue": "0.10.1-develop.7807.1.9b2b8953e9",
58
+ "@open-mercato/ui": "0.10.1-develop.7807.1.9b2b8953e9"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "@mikro-orm/postgresql": "^7.0.14",
62
- "@open-mercato/ai-assistant": "0.10.1-develop.7803.1.e99e862b4e",
63
- "@open-mercato/shared": "0.10.1-develop.7803.1.e99e862b4e",
62
+ "@open-mercato/ai-assistant": "0.10.1-develop.7807.1.9b2b8953e9",
63
+ "@open-mercato/shared": "0.10.1-develop.7807.1.9b2b8953e9",
64
64
  "react": "^19.0.0",
65
65
  "react-dom": "^19.0.0",
66
66
  "react-is": ">=18.0.0"
67
67
  },
68
68
  "devDependencies": {
69
- "@open-mercato/ai-assistant": "0.10.1-develop.7803.1.e99e862b4e",
70
- "@open-mercato/shared": "0.10.1-develop.7803.1.e99e862b4e",
69
+ "@open-mercato/ai-assistant": "0.10.1-develop.7807.1.9b2b8953e9",
70
+ "@open-mercato/shared": "0.10.1-develop.7807.1.9b2b8953e9",
71
71
  "@types/jest": "^30.0.0",
72
72
  "@types/react": "^19.2.18",
73
73
  "@types/react-dom": "^19.2.5",
@@ -234,6 +234,122 @@ describe('detachOperator', () => {
234
234
  const saved = store[TILLIO_OPERATORS_INTEGRATION_ID] as { operators: unknown[] }
235
235
  expect(saved.operators).toHaveLength(0)
236
236
  })
237
+
238
+ function attachedOperator(token: string, id = 'ringostat-1') {
239
+ return { id, plugin: 'Ringostat', config: { key: 'x' }, token, tenantDomain: 'd', envFingerprint: 'fp' }
240
+ }
241
+
242
+ function gatedDeleteConfig() {
243
+ let release: () => void = () => {}
244
+ const gate = new Promise<void>((resolve) => { release = resolve })
245
+ let calls = 0
246
+ const deleteConfig = jest.fn(async () => {
247
+ calls += 1
248
+ if (calls === 1) await gate
249
+ })
250
+ return { deleteConfig, release: () => release() }
251
+ }
252
+
253
+ function flushPending(): Promise<void> {
254
+ return new Promise((resolve) => setImmediate(resolve))
255
+ }
256
+
257
+ it('keeps an operator attached while its revocation call was in flight', async () => {
258
+ const { deleteConfig, release } = gatedDeleteConfig()
259
+ mockClient({ deleteConfig, addConfig: jest.fn().mockResolvedValue({ token: 'tok-B' }) })
260
+ const { service, store } = fakeStore({
261
+ [TILLIO_INTEGRATION_ID]: { ...readyEnv },
262
+ [TILLIO_OPERATORS_INTEGRATION_ID]: { operators: [attachedOperator('tok-A')], defaultOperatorId: 'ringostat-1' },
263
+ })
264
+
265
+ const slowDetach = detachOperator({ credentialsService: service, scope }, 'ringostat-1')
266
+ await flushPending()
267
+ await expect(detachOperator({ credentialsService: service, scope }, 'ringostat-1'))
268
+ .resolves.toEqual({ ok: true, detached: true, revoked: true })
269
+ const attached = await attachOperator(
270
+ { credentialsService: service, scope, appUrl, withLock: passThroughLock },
271
+ { plugin: 'Ringostat', config: { key: 'b' } },
272
+ )
273
+ const savesBeforeRelease = (service.save as jest.Mock).mock.calls.length
274
+ release()
275
+
276
+ await expect(slowDetach).resolves.toEqual({ ok: true, detached: true, revoked: true })
277
+ expect(attached.token).toBe('tok-B')
278
+ expect((service.save as jest.Mock).mock.calls).toHaveLength(savesBeforeRelease)
279
+ const saved = store[TILLIO_OPERATORS_INTEGRATION_ID] as { operators: Array<{ token: string }>; defaultOperatorId: string | null }
280
+ expect(saved.operators.map((entry) => entry.token)).toEqual(['tok-B'])
281
+ expect(saved.defaultOperatorId).toBe('ringostat-1')
282
+ })
283
+
284
+ it('removes nothing on a forced detach whose record was replaced meanwhile', async () => {
285
+ let release: () => void = () => {}
286
+ const gate = new Promise<void>((resolve) => { release = resolve })
287
+ mockClient({
288
+ deleteConfig: jest.fn(async () => {
289
+ await gate
290
+ throw new TillioApiError('nope', 422, 'invalid')
291
+ }),
292
+ })
293
+ const { service, store } = fakeStore({
294
+ [TILLIO_INTEGRATION_ID]: { ...readyEnv },
295
+ [TILLIO_OPERATORS_INTEGRATION_ID]: { operators: [attachedOperator('tok-A')], defaultOperatorId: 'ringostat-1' },
296
+ })
297
+
298
+ const forced = detachOperator({ credentialsService: service, scope }, 'ringostat-1', { force: true })
299
+ await flushPending()
300
+ store[TILLIO_OPERATORS_INTEGRATION_ID] = { operators: [attachedOperator('tok-B')], defaultOperatorId: 'ringostat-1' }
301
+ release()
302
+
303
+ await expect(forced).resolves.toEqual({ ok: true, detached: true, revoked: false })
304
+ expect(service.save).not.toHaveBeenCalled()
305
+ const saved = store[TILLIO_OPERATORS_INTEGRATION_ID] as { operators: Array<{ token: string }>; defaultOperatorId: string | null }
306
+ expect(saved.operators.map((entry) => entry.token)).toEqual(['tok-B'])
307
+ expect(saved.defaultOperatorId).toBe('ringostat-1')
308
+ })
309
+
310
+ it('writes from the blob as it stands after the revocation, not from the first read', async () => {
311
+ const { deleteConfig, release } = gatedDeleteConfig()
312
+ mockClient({ deleteConfig })
313
+ const { service, store } = fakeStore({
314
+ [TILLIO_INTEGRATION_ID]: { ...readyEnv },
315
+ [TILLIO_OPERATORS_INTEGRATION_ID]: { operators: [attachedOperator('tok-A')], defaultOperatorId: 'ringostat-1' },
316
+ })
317
+
318
+ const pending = detachOperator({ credentialsService: service, scope }, 'ringostat-1')
319
+ await flushPending()
320
+ store[TILLIO_OPERATORS_INTEGRATION_ID] = {
321
+ operators: [attachedOperator('tok-A'), attachedOperator('tok-other', 'other-1')],
322
+ defaultOperatorId: 'other-1',
323
+ }
324
+ release()
325
+
326
+ await expect(pending).resolves.toEqual({ ok: true, detached: true, revoked: true })
327
+ const saved = store[TILLIO_OPERATORS_INTEGRATION_ID] as { operators: Array<{ id: string }>; defaultOperatorId: string | null }
328
+ expect(saved.operators.map((entry) => entry.id)).toEqual(['other-1'])
329
+ expect(saved.defaultOperatorId).toBe('other-1')
330
+ })
331
+
332
+ it('hands the default to an operator stored meanwhile when the detached one was the default', async () => {
333
+ const { deleteConfig, release } = gatedDeleteConfig()
334
+ mockClient({ deleteConfig })
335
+ const { service, store } = fakeStore({
336
+ [TILLIO_INTEGRATION_ID]: { ...readyEnv },
337
+ [TILLIO_OPERATORS_INTEGRATION_ID]: { operators: [attachedOperator('tok-A')], defaultOperatorId: 'ringostat-1' },
338
+ })
339
+
340
+ const pending = detachOperator({ credentialsService: service, scope }, 'ringostat-1')
341
+ await flushPending()
342
+ store[TILLIO_OPERATORS_INTEGRATION_ID] = {
343
+ operators: [attachedOperator('tok-A'), attachedOperator('tok-other', 'other-1')],
344
+ defaultOperatorId: 'ringostat-1',
345
+ }
346
+ release()
347
+
348
+ await pending
349
+ const saved = store[TILLIO_OPERATORS_INTEGRATION_ID] as { operators: Array<{ id: string }>; defaultOperatorId: string | null }
350
+ expect(saved.operators.map((entry) => entry.id)).toEqual(['other-1'])
351
+ expect(saved.defaultOperatorId).toBe('other-1')
352
+ })
237
353
  })
238
354
 
239
355
  describe('classifyTillioError', () => {
@@ -257,13 +257,18 @@ export async function detachOperator(
257
257
  }
258
258
  }
259
259
 
260
- const remaining = blob.operators.filter((entry) => entry.id !== operatorId)
261
- await saveOperatorsBlob(deps.credentialsService, deps.scope, {
262
- operators: remaining,
263
- defaultOperatorId: blob.defaultOperatorId === operatorId
264
- ? (remaining[0]?.id ?? null)
265
- : blob.defaultOperatorId,
266
- })
260
+ const current = await readOperatorsBlob(deps.credentialsService, deps.scope)
261
+ const remaining = current.operators.filter(
262
+ (entry) => entry.id !== operatorId || entry.token !== operator.token,
263
+ )
264
+ if (remaining.length < current.operators.length) {
265
+ await saveOperatorsBlob(deps.credentialsService, deps.scope, {
266
+ operators: remaining,
267
+ defaultOperatorId: current.defaultOperatorId === operatorId
268
+ ? (remaining[0]?.id ?? null)
269
+ : current.defaultOperatorId,
270
+ })
271
+ }
267
272
 
268
273
  return { ok: true, detached: true, revoked }
269
274
  }