@contember/engine-tenant-api 2.2.0-alpha.8 → 2.2.0-alpha.9

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.
@@ -36,10 +36,11 @@ class ApiKeyManager {
36
36
  if (unpersistedResult !== null) {
37
37
  return new Response.ResponseOk(unpersistedResult);
38
38
  }
39
- const apiKeyRow = await readDbContext.queryHandler.fetch(new ApiKeyQuery.ApiKeyByTokenQuery(token));
40
- if (apiKeyRow === null) {
39
+ const fetchedApiKey = await this.fetchApiKeyByToken(dbContext, readDbContext, token);
40
+ if (fetchedApiKey === null) {
41
41
  return new Response.ResponseError("not_found", "API key was not found");
42
42
  }
43
+ const apiKeyRow = fetchedApiKey.row;
43
44
  if (apiKeyRow.disabled_at !== null) {
44
45
  return new Response.ResponseError(
45
46
  "disabled",
@@ -87,7 +88,7 @@ class ApiKeyManager {
87
88
  userAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent
88
89
  } : requestInfo;
89
90
  if (this.idpSessionRevalidator) {
90
- const outcome = await this.idpSessionRevalidator.revalidate(dbContext, readDbContext, apiKeyRow, effectiveInfo);
91
+ const outcome = await this.idpSessionRevalidator.revalidate(dbContext, fetchedApiKey.sourceDbContext, apiKeyRow, effectiveInfo);
91
92
  if (outcome === "revoked") {
92
93
  return new Response.ResponseError("disabled", "IdP session was revoked");
93
94
  }
@@ -120,6 +121,18 @@ class ApiKeyManager {
120
121
  )
121
122
  );
122
123
  }
124
+ async fetchApiKeyByToken(dbContext, readDbContext, token) {
125
+ const query = new ApiKeyQuery.ApiKeyByTokenQuery(token);
126
+ const replicaRow = await readDbContext.queryHandler.fetch(query);
127
+ if (replicaRow !== null) {
128
+ return { row: replicaRow, sourceDbContext: readDbContext };
129
+ }
130
+ if (readDbContext.client.connection === dbContext.client.connection) {
131
+ return null;
132
+ }
133
+ const primaryRow = await dbContext.queryHandler.fetch(query);
134
+ return primaryRow !== null ? { row: primaryRow, sourceDbContext: dbContext } : null;
135
+ }
123
136
  async createSessionApiKey(dbContext, identityId, expiration, requestInfo, trustForwardedInfo) {
124
137
  const { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo);
125
138
  return token;
@@ -1 +1 @@
1
- {"version":3,"file":"ApiKeyManager.cjs","sources":["../../../../../../../packages/engine-tenant-api/src/model/service/apiKey/ApiKeyManager.ts"],"sourcesContent":["import {\n\tApiKeyRequestInfo,\n\tCreateApiKeyCommand,\n\tDisableApiKeyCommand,\n\tDisableIdentityApiKeysCommand,\n\tDisableOneOffApiKeyCommand,\n\tPROLONG_THROTTLE_MS,\n\tProlongApiKeyCommand,\n} from '../../commands/index.js'\nimport { ApiKey } from '../../type/index.js'\n\nimport { Response, ResponseError, ResponseOk } from '../../utils/Response.js'\nimport { DatabaseContext, TokenHash } from '../../utils/index.js'\nimport { ApiKeyService, CreateApiKeyResponse } from './ApiKeyService.js'\nimport assert from 'node:assert'\nimport { Acl } from '@contember/schema'\nimport { ApiKeyByIdQuery, ApiKeyByTokenQuery, ApiKeyRow, ConfigurationQuery, IdentityQuery } from '../../queries/index.js'\nimport PostgresInterval from 'postgres-interval'\nimport { Config } from '../../type/Config.js'\nimport { intervalToPostgres, intervalToSeconds } from '../../utils/interval.js'\nimport { AuthPolicyResolver } from '../AuthPolicyResolver.js'\nimport { AuthLogService } from '../AuthLogService.js'\nimport { IdpSessionRevalidator } from '../idp/IdpSessionRevalidator.js'\nimport { UnpersistedApiKeyManager } from './UnpersistedApiKeyManager.js'\n\nexport class ApiKeyManager {\n\tconstructor(\n\t\tprivate readonly apiKeyService: ApiKeyService,\n\t\tprivate readonly authPolicyResolver: AuthPolicyResolver,\n\t\tprivate readonly authLogService: AuthLogService,\n\t\tprivate readonly unpersistedApiKeyManager: UnpersistedApiKeyManager = new UnpersistedApiKeyManager(),\n\t\tprivate readonly idpSessionRevalidator?: IdpSessionRevalidator,\n\t) {}\n\n\tasync verifyAndProlong(\n\t\tdbContext: DatabaseContext,\n\t\treadDbContext: DatabaseContext,\n\t\ttoken: string,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\tforwardedInfo?: ApiKeyRequestInfo,\n\t): Promise<VerifyResponse> {\n\t\tconst unpersistedResult = this.unpersistedApiKeyManager.verify(token)\n\t\tif (unpersistedResult !== null) {\n\t\t\t// Configured (unpersisted) root token: no DB row to prolong/track.\n\t\t\treturn new ResponseOk(unpersistedResult)\n\t\t}\n\n\t\tconst apiKeyRow = await readDbContext.queryHandler.fetch(new ApiKeyByTokenQuery(token))\n\t\tif (apiKeyRow === null) {\n\t\t\treturn new ResponseError(VerifyErrorCode.NOT_FOUND, 'API key was not found')\n\t\t}\n\n\t\tif (apiKeyRow.disabled_at !== null) {\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key was disabled at ${apiKeyRow.disabled_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// Single injectable clock for all session-policy time math (matches issuance,\n\t\t// which uses providers.now()), so the A19 idle/max logic is deterministically testable.\n\t\tconst now = dbContext.providers.now()\n\t\tif (apiKeyRow.expires_at !== null && apiKeyRow.expires_at <= now) {\n\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, `API key expired at ${apiKeyRow.expires_at.toISOString()}`)\n\t\t}\n\n\t\t// A19: absolute hard cap (defensive — the prolong clamp should already keep\n\t\t// expires_at <= max_expires_at, but enforce it here regardless).\n\t\tif (apiKeyRow.max_expires_at !== null && apiKeyRow.max_expires_at <= now) {\n\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key reached its maximum lifetime at ${apiKeyRow.max_expires_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// A19: idle timeout. Reject + disable when the session has been idle longer\n\t\t// than the policy's idle_timeout. A null idle_timeout (today's default) or a\n\t\t// never-used key (last_used_at null) are never idle-expired.\n\t\tif (apiKeyRow.idle_timeout !== null && apiKeyRow.last_used_at !== null) {\n\t\t\tconst idleMs = intervalToSeconds(apiKeyRow.idle_timeout) * 1000\n\t\t\t// last_used_at is written at most once per PROLONG_THROTTLE_MS (tracking is\n\t\t\t// throttled), so it can legitimately lag a continuously-active session by up\n\t\t\t// to that window. Add the throttle as slack so a small idle_timeout can't\n\t\t\t// idle-expire a session that is actually in use.\n\t\t\tif (now.getTime() - apiKeyRow.last_used_at.getTime() > idleMs + PROLONG_THROTTLE_MS) {\n\t\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\t\ttry {\n\t\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\t\ttype: 'session_expired_idle',\n\t\t\t\t\t\tidentityId: apiKeyRow.identity_id,\n\t\t\t\t\t\tpersonId: apiKeyRow.person_id,\n\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\teventData: {\n\t\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at?.toISOString() ?? null,\n\t\t\t\t\t\t\tidleTimeout: String(apiKeyRow.idle_timeout),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort: auth path must stay resilient */\n\t\t\t\t}\n\t\t\t\treturn new ResponseError(\n\t\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t\t`API key was idle since ${apiKeyRow.last_used_at.toISOString()} and exceeded the idle timeout`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst effectiveInfo: ApiKeyRequestInfo | undefined = apiKeyRow.trust_forwarded_info && forwardedInfo\n\t\t\t? {\n\t\t\t\tip: forwardedInfo.ip ?? requestInfo?.ip,\n\t\t\t\tuserAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent,\n\t\t\t}\n\t\t\t: requestInfo\n\n\t\t// Re-validate IdP-backed sessions against their identity provider (A24). In the\n\t\t// default `background` mode this returns immediately and revalidates after the\n\t\t// response (revocation lands on the next request); in `blocking` mode it can revoke\n\t\t// the current request. No-op for password sessions and IdPs without revalidation.\n\t\t// `effectiveInfo` is passed so the audit entries record the originating request's IP/UA.\n\t\tif (this.idpSessionRevalidator) {\n\t\t\tconst outcome = await this.idpSessionRevalidator.revalidate(dbContext, readDbContext, apiKeyRow, effectiveInfo)\n\t\t\tif (outcome === 'revoked') {\n\t\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, 'IdP session was revoked')\n\t\t\t}\n\t\t}\n\n\t\t// Detached (runs after the response), so a rejection here would be an unhandledRejection and can take the\n\t\t// worker down. Tracking is best-effort — the next request writes it again.\n\t\tsetImmediate(() => {\n\t\t\tdbContext.commandBus.execute(\n\t\t\t\tnew ProlongApiKeyCommand(\n\t\t\t\t\tapiKeyRow.id,\n\t\t\t\t\tapiKeyRow.type,\n\t\t\t\t\tapiKeyRow.expiration,\n\t\t\t\t\tapiKeyRow.expires_at,\n\t\t\t\t\teffectiveInfo,\n\t\t\t\t\t{\n\t\t\t\t\t\tlastIp: apiKeyRow.last_ip,\n\t\t\t\t\t\tlastUserAgent: apiKeyRow.last_user_agent,\n\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at,\n\t\t\t\t\t},\n\t\t\t\t\tapiKeyRow.max_expires_at,\n\t\t\t\t),\n\t\t\t).catch(() => {})\n\t\t})\n\n\t\treturn new ResponseOk(\n\t\t\tnew VerifyResult(\n\t\t\t\tapiKeyRow.identity_id,\n\t\t\t\tapiKeyRow.id,\n\t\t\t\tapiKeyRow.roles,\n\t\t\t\tapiKeyRow.person_id,\n\t\t\t\tapiKeyRow.trust_forwarded_info,\n\t\t\t),\n\t\t)\n\t}\n\n\tasync createSessionApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<string> {\n\t\tconst { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo)\n\t\treturn token\n\t}\n\n\t/**\n\t * Like {@link createSessionApiKey} but also returns the api_key id — needed when the\n\t * caller has to bind another row to the session (e.g. an `idp_session` for IdP\n\t * re-validation).\n\t */\n\tasync createSessionApiKeyWithId(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<{ id: string; token: string }> {\n\t\tconst config = await dbContext.queryHandler.fetch(new ConfigurationQuery(dbContext.providers))\n\n\t\t// A19: snapshot the effective session policy onto the api_key at sign-in.\n\t\t// With no matching policy, every field is null/baseline and the result is\n\t\t// byte-for-byte today's behavior.\n\t\tconst [identityRow] = await dbContext.queryHandler.fetch(new IdentityQuery([identityId]))\n\t\tconst globalRoles = identityRow?.roles ?? []\n\t\tconst policy = await this.authPolicyResolver.resolveForIdentity(dbContext, identityId, globalRoles)\n\n\t\tconst defaultExpirationMinutes = intervalToSeconds(config.login.defaultTokenExpiration) / 60\n\t\t// remember_me_allowed === false: ignore a client-supplied longer lifetime and\n\t\t// force the default. (true/null leave the requested expiration untouched.)\n\t\tconst requestedMinutes = policy.rememberMeAllowed === false\n\t\t\t? defaultExpirationMinutes\n\t\t\t: (expiration ?? defaultExpirationMinutes)\n\n\t\t// Cap by maxTokenExpiration (existing behavior) AND by the policy's\n\t\t// tokenExpiration (A19) — strictest wins.\n\t\tlet expirationCapped = config.login.maxTokenExpiration\n\t\t\t? Math.min(requestedMinutes, intervalToSeconds(config.login.maxTokenExpiration) / 60)\n\t\t\t: requestedMinutes\n\t\tif (policy.tokenExpiration) {\n\t\t\texpirationCapped = Math.min(expirationCapped, intervalToSeconds(policy.tokenExpiration) / 60)\n\t\t}\n\n\t\t// Absolute hard cap: issued_at + policy.tokenExpiration. NULL = uncapped\n\t\t// sliding window (today's behavior).\n\t\tconst issuedAt = dbContext.providers.now()\n\t\tconst maxExpiresAt = policy.tokenExpiration\n\t\t\t? new Date(issuedAt.getTime() + intervalToSeconds(policy.tokenExpiration) * 1000)\n\t\t\t: null\n\n\t\tconst command = new CreateApiKeyCommand({\n\t\t\ttype: ApiKey.Type.SESSION,\n\t\t\tidentityId,\n\t\t\texpiration: expirationCapped,\n\t\t\trequestInfo,\n\t\t\ttrustForwardedInfo,\n\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\tmaxExpiresAt,\n\t\t})\n\t\tconst { id, token } = await dbContext.commandBus.execute(command)\n\t\tassert(token !== undefined)\n\n\t\t// A19: audit only when a policy is actually in effect. With zero auth_policy\n\t\t// rows the resolved policy is inert and no extra insert happens.\n\t\tconst policyApplied = policy.mfaRequired === true\n\t\t\t|| policy.tokenExpiration !== null\n\t\t\t|| policy.idleTimeout !== null\n\t\t\t|| policy.rememberMeAllowed !== null\n\t\tif (policyApplied) {\n\t\t\ttry {\n\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\ttype: 'session_policy_applied',\n\t\t\t\t\tidentityId,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\teventData: {\n\t\t\t\t\t\ttokenExpiration: policy.tokenExpiration ? intervalToPostgres(policy.tokenExpiration) : null,\n\t\t\t\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\t\t\t\trememberMeAllowed: policy.rememberMeAllowed,\n\t\t\t\t\t\tmfaRequired: policy.mfaRequired,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t/* best-effort: sign-in must not break on an audit failure */\n\t\t\t}\n\t\t}\n\n\t\treturn { id, token }\n\t}\n\n\tasync findApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<ApiKeyRow | null> {\n\t\treturn await dbContext.queryHandler.fetch(\n\t\t\tnew ApiKeyByIdQuery(apiKeyId),\n\t\t)\n\t}\n\n\tasync disableOneOffApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableOneOffApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<boolean> {\n\t\treturn await dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableIdentityApiKeys(dbContext: DatabaseContext, identityId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableIdentityApiKeysCommand(identityId))\n\t}\n\n\tasync createGlobalPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tdescription: string,\n\t\troles: readonly string[],\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createPermanentApiKey(db, description, roles, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n\n\tasync createProjectPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tprojectId: string,\n\t\tmemberships: readonly Acl.Membership[],\n\t\tdescription: string,\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createProjectPermanentApiKey(db, projectId, memberships, description, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n}\n\nexport type VerifyResponse = Response<VerifyResult, VerifyErrorCode>\n\nexport class VerifyResult {\n\treadonly valid = true\n\n\tconstructor(\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly apiKeyId: string,\n\t\tpublic readonly roles: string[],\n\t\tpublic readonly personId: string | null,\n\t\tpublic readonly trustForwardedInfo: boolean = false,\n\t) {}\n}\n\nexport enum VerifyErrorCode {\n\tNOT_FOUND = 'not_found',\n\tDISABLED = 'disabled',\n\tEXPIRED = 'expired',\n\tNO_AUTH_HEADER = 'no_auth_header',\n\tINVALID_AUTH_HEADER = 'invalid_auth_header',\n}\n"],"names":["UnpersistedApiKeyManager","ResponseOk","ApiKeyByTokenQuery","ResponseError","DisableApiKeyCommand","intervalToSeconds","PROLONG_THROTTLE_MS","ProlongApiKeyCommand","ConfigurationQuery","IdentityQuery","CreateApiKeyCommand","ApiKey","intervalToPostgres","ApiKeyByIdQuery","DisableOneOffApiKeyCommand","DisableIdentityApiKeysCommand","VerifyErrorCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyBO,MAAM,cAAc;AAAA,EAC1B,YACkB,eACA,oBACA,gBACA,2BAAqD,IAAIA,yBAAAA,yBAAA,GACzD,uBAChB;AALgB,SAAA,gBAAA;AACA,SAAA,qBAAA;AACA,SAAA,iBAAA;AACA,SAAA,2BAAA;AACA,SAAA,wBAAA;AAAA,EACf;AAAA,EAEH,MAAM,iBACL,WACA,eACA,OACA,aACA,eAC0B;AAC1B,UAAM,oBAAoB,KAAK,yBAAyB,OAAO,KAAK;AACpE,QAAI,sBAAsB,MAAM;AAE/B,aAAO,IAAIC,SAAAA,WAAW,iBAAiB;AAAA,IACxC;AAEA,UAAM,YAAY,MAAM,cAAc,aAAa,MAAM,IAAIC,YAAAA,mBAAmB,KAAK,CAAC;AACtF,QAAI,cAAc,MAAM;AACvB,aAAO,IAAIC,SAAAA,cAAc,aAA2B,uBAAuB;AAAA,IAC5E;AAEA,QAAI,UAAU,gBAAgB,MAAM;AACnC,aAAO,IAAIA,SAAAA;AAAAA,QACV;AAAA,QACA,2BAA2B,UAAU,YAAY,YAAA,CAAa;AAAA,MAAA;AAAA,IAEhE;AAIA,UAAM,MAAM,UAAU,UAAU,IAAA;AAChC,QAAI,UAAU,eAAe,QAAQ,UAAU,cAAc,KAAK;AACjE,aAAO,IAAI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AA,SAAA,IAAU;AACVA,mBAAA,gBAAA,IAAiB;AACjBA,mBAAA,qBAAA,IAAsB;AALX,SAAAA;AAAA,GAAA,mBAAA,CAAA,CAAA;;;;"}
1
+ {"version":3,"file":"ApiKeyManager.cjs","sources":["../../../../../../../packages/engine-tenant-api/src/model/service/apiKey/ApiKeyManager.ts"],"sourcesContent":["import {\n\tApiKeyRequestInfo,\n\tCreateApiKeyCommand,\n\tDisableApiKeyCommand,\n\tDisableIdentityApiKeysCommand,\n\tDisableOneOffApiKeyCommand,\n\tPROLONG_THROTTLE_MS,\n\tProlongApiKeyCommand,\n} from '../../commands/index.js'\nimport { ApiKey } from '../../type/index.js'\n\nimport { Response, ResponseError, ResponseOk } from '../../utils/Response.js'\nimport { DatabaseContext, TokenHash } from '../../utils/index.js'\nimport { ApiKeyService, CreateApiKeyResponse } from './ApiKeyService.js'\nimport assert from 'node:assert'\nimport { Acl } from '@contember/schema'\nimport { ApiKeyByIdQuery, ApiKeyByTokenQuery, ApiKeyRow, ConfigurationQuery, IdentityQuery } from '../../queries/index.js'\nimport PostgresInterval from 'postgres-interval'\nimport { Config } from '../../type/Config.js'\nimport { intervalToPostgres, intervalToSeconds } from '../../utils/interval.js'\nimport { AuthPolicyResolver } from '../AuthPolicyResolver.js'\nimport { AuthLogService } from '../AuthLogService.js'\nimport { IdpSessionRevalidator } from '../idp/IdpSessionRevalidator.js'\nimport { UnpersistedApiKeyManager } from './UnpersistedApiKeyManager.js'\n\nexport class ApiKeyManager {\n\tconstructor(\n\t\tprivate readonly apiKeyService: ApiKeyService,\n\t\tprivate readonly authPolicyResolver: AuthPolicyResolver,\n\t\tprivate readonly authLogService: AuthLogService,\n\t\tprivate readonly unpersistedApiKeyManager: UnpersistedApiKeyManager = new UnpersistedApiKeyManager(),\n\t\tprivate readonly idpSessionRevalidator?: IdpSessionRevalidator,\n\t) {}\n\n\tasync verifyAndProlong(\n\t\tdbContext: DatabaseContext,\n\t\treadDbContext: DatabaseContext,\n\t\ttoken: string,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\tforwardedInfo?: ApiKeyRequestInfo,\n\t): Promise<VerifyResponse> {\n\t\tconst unpersistedResult = this.unpersistedApiKeyManager.verify(token)\n\t\tif (unpersistedResult !== null) {\n\t\t\t// Configured (unpersisted) root token: no DB row to prolong/track.\n\t\t\treturn new ResponseOk(unpersistedResult)\n\t\t}\n\n\t\tconst fetchedApiKey = await this.fetchApiKeyByToken(dbContext, readDbContext, token)\n\t\tif (fetchedApiKey === null) {\n\t\t\treturn new ResponseError(VerifyErrorCode.NOT_FOUND, 'API key was not found')\n\t\t}\n\t\tconst apiKeyRow = fetchedApiKey.row\n\n\t\tif (apiKeyRow.disabled_at !== null) {\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key was disabled at ${apiKeyRow.disabled_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// Single injectable clock for all session-policy time math (matches issuance,\n\t\t// which uses providers.now()), so the A19 idle/max logic is deterministically testable.\n\t\tconst now = dbContext.providers.now()\n\t\tif (apiKeyRow.expires_at !== null && apiKeyRow.expires_at <= now) {\n\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, `API key expired at ${apiKeyRow.expires_at.toISOString()}`)\n\t\t}\n\n\t\t// A19: absolute hard cap (defensive — the prolong clamp should already keep\n\t\t// expires_at <= max_expires_at, but enforce it here regardless).\n\t\tif (apiKeyRow.max_expires_at !== null && apiKeyRow.max_expires_at <= now) {\n\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key reached its maximum lifetime at ${apiKeyRow.max_expires_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// A19: idle timeout. Reject + disable when the session has been idle longer\n\t\t// than the policy's idle_timeout. A null idle_timeout (today's default) or a\n\t\t// never-used key (last_used_at null) are never idle-expired.\n\t\tif (apiKeyRow.idle_timeout !== null && apiKeyRow.last_used_at !== null) {\n\t\t\tconst idleMs = intervalToSeconds(apiKeyRow.idle_timeout) * 1000\n\t\t\t// last_used_at is written at most once per PROLONG_THROTTLE_MS (tracking is\n\t\t\t// throttled), so it can legitimately lag a continuously-active session by up\n\t\t\t// to that window. Add the throttle as slack so a small idle_timeout can't\n\t\t\t// idle-expire a session that is actually in use.\n\t\t\tif (now.getTime() - apiKeyRow.last_used_at.getTime() > idleMs + PROLONG_THROTTLE_MS) {\n\t\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\t\ttry {\n\t\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\t\ttype: 'session_expired_idle',\n\t\t\t\t\t\tidentityId: apiKeyRow.identity_id,\n\t\t\t\t\t\tpersonId: apiKeyRow.person_id,\n\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\teventData: {\n\t\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at?.toISOString() ?? null,\n\t\t\t\t\t\t\tidleTimeout: String(apiKeyRow.idle_timeout),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort: auth path must stay resilient */\n\t\t\t\t}\n\t\t\t\treturn new ResponseError(\n\t\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t\t`API key was idle since ${apiKeyRow.last_used_at.toISOString()} and exceeded the idle timeout`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst effectiveInfo: ApiKeyRequestInfo | undefined = apiKeyRow.trust_forwarded_info && forwardedInfo\n\t\t\t? {\n\t\t\t\tip: forwardedInfo.ip ?? requestInfo?.ip,\n\t\t\t\tuserAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent,\n\t\t\t}\n\t\t\t: requestInfo\n\n\t\t// Re-validate IdP-backed sessions against their identity provider (A24). In the\n\t\t// default `background` mode this returns immediately and revalidates after the\n\t\t// response (revocation lands on the next request); in `blocking` mode it can revoke\n\t\t// the current request. No-op for password sessions and IdPs without revalidation.\n\t\t// `effectiveInfo` is passed so the audit entries record the originating request's IP/UA.\n\t\t// The idp_session row is written together with the api_key, so it is read from where the key was found.\n\t\tif (this.idpSessionRevalidator) {\n\t\t\tconst outcome = await this.idpSessionRevalidator.revalidate(dbContext, fetchedApiKey.sourceDbContext, apiKeyRow, effectiveInfo)\n\t\t\tif (outcome === 'revoked') {\n\t\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, 'IdP session was revoked')\n\t\t\t}\n\t\t}\n\n\t\t// Detached (runs after the response), so a rejection here would be an unhandledRejection and can take the\n\t\t// worker down. Tracking is best-effort — the next request writes it again.\n\t\tsetImmediate(() => {\n\t\t\tdbContext.commandBus.execute(\n\t\t\t\tnew ProlongApiKeyCommand(\n\t\t\t\t\tapiKeyRow.id,\n\t\t\t\t\tapiKeyRow.type,\n\t\t\t\t\tapiKeyRow.expiration,\n\t\t\t\t\tapiKeyRow.expires_at,\n\t\t\t\t\teffectiveInfo,\n\t\t\t\t\t{\n\t\t\t\t\t\tlastIp: apiKeyRow.last_ip,\n\t\t\t\t\t\tlastUserAgent: apiKeyRow.last_user_agent,\n\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at,\n\t\t\t\t\t},\n\t\t\t\t\tapiKeyRow.max_expires_at,\n\t\t\t\t),\n\t\t\t).catch(() => {})\n\t\t})\n\n\t\treturn new ResponseOk(\n\t\t\tnew VerifyResult(\n\t\t\t\tapiKeyRow.identity_id,\n\t\t\t\tapiKeyRow.id,\n\t\t\t\tapiKeyRow.roles,\n\t\t\t\tapiKeyRow.person_id,\n\t\t\t\tapiKeyRow.trust_forwarded_info,\n\t\t\t),\n\t\t)\n\t}\n\n\tprivate async fetchApiKeyByToken(dbContext: DatabaseContext, readDbContext: DatabaseContext, token: string): Promise<FetchedApiKey | null> {\n\t\tconst query = new ApiKeyByTokenQuery(token)\n\t\tconst replicaRow = await readDbContext.queryHandler.fetch(query)\n\t\tif (replicaRow !== null) {\n\t\t\treturn { row: replicaRow, sourceDbContext: readDbContext }\n\t\t}\n\t\tif (readDbContext.client.connection === dbContext.client.connection) {\n\t\t\treturn null\n\t\t}\n\t\t// A token issued moments ago (sign-in, createSessionToken) may not have reached the read replica yet.\n\t\tconst primaryRow = await dbContext.queryHandler.fetch(query)\n\t\treturn primaryRow !== null ? { row: primaryRow, sourceDbContext: dbContext } : null\n\t}\n\n\tasync createSessionApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<string> {\n\t\tconst { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo)\n\t\treturn token\n\t}\n\n\t/**\n\t * Like {@link createSessionApiKey} but also returns the api_key id — needed when the\n\t * caller has to bind another row to the session (e.g. an `idp_session` for IdP\n\t * re-validation).\n\t */\n\tasync createSessionApiKeyWithId(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<{ id: string; token: string }> {\n\t\tconst config = await dbContext.queryHandler.fetch(new ConfigurationQuery(dbContext.providers))\n\n\t\t// A19: snapshot the effective session policy onto the api_key at sign-in.\n\t\t// With no matching policy, every field is null/baseline and the result is\n\t\t// byte-for-byte today's behavior.\n\t\tconst [identityRow] = await dbContext.queryHandler.fetch(new IdentityQuery([identityId]))\n\t\tconst globalRoles = identityRow?.roles ?? []\n\t\tconst policy = await this.authPolicyResolver.resolveForIdentity(dbContext, identityId, globalRoles)\n\n\t\tconst defaultExpirationMinutes = intervalToSeconds(config.login.defaultTokenExpiration) / 60\n\t\t// remember_me_allowed === false: ignore a client-supplied longer lifetime and\n\t\t// force the default. (true/null leave the requested expiration untouched.)\n\t\tconst requestedMinutes = policy.rememberMeAllowed === false\n\t\t\t? defaultExpirationMinutes\n\t\t\t: (expiration ?? defaultExpirationMinutes)\n\n\t\t// Cap by maxTokenExpiration (existing behavior) AND by the policy's\n\t\t// tokenExpiration (A19) — strictest wins.\n\t\tlet expirationCapped = config.login.maxTokenExpiration\n\t\t\t? Math.min(requestedMinutes, intervalToSeconds(config.login.maxTokenExpiration) / 60)\n\t\t\t: requestedMinutes\n\t\tif (policy.tokenExpiration) {\n\t\t\texpirationCapped = Math.min(expirationCapped, intervalToSeconds(policy.tokenExpiration) / 60)\n\t\t}\n\n\t\t// Absolute hard cap: issued_at + policy.tokenExpiration. NULL = uncapped\n\t\t// sliding window (today's behavior).\n\t\tconst issuedAt = dbContext.providers.now()\n\t\tconst maxExpiresAt = policy.tokenExpiration\n\t\t\t? new Date(issuedAt.getTime() + intervalToSeconds(policy.tokenExpiration) * 1000)\n\t\t\t: null\n\n\t\tconst command = new CreateApiKeyCommand({\n\t\t\ttype: ApiKey.Type.SESSION,\n\t\t\tidentityId,\n\t\t\texpiration: expirationCapped,\n\t\t\trequestInfo,\n\t\t\ttrustForwardedInfo,\n\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\tmaxExpiresAt,\n\t\t})\n\t\tconst { id, token } = await dbContext.commandBus.execute(command)\n\t\tassert(token !== undefined)\n\n\t\t// A19: audit only when a policy is actually in effect. With zero auth_policy\n\t\t// rows the resolved policy is inert and no extra insert happens.\n\t\tconst policyApplied = policy.mfaRequired === true\n\t\t\t|| policy.tokenExpiration !== null\n\t\t\t|| policy.idleTimeout !== null\n\t\t\t|| policy.rememberMeAllowed !== null\n\t\tif (policyApplied) {\n\t\t\ttry {\n\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\ttype: 'session_policy_applied',\n\t\t\t\t\tidentityId,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\teventData: {\n\t\t\t\t\t\ttokenExpiration: policy.tokenExpiration ? intervalToPostgres(policy.tokenExpiration) : null,\n\t\t\t\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\t\t\t\trememberMeAllowed: policy.rememberMeAllowed,\n\t\t\t\t\t\tmfaRequired: policy.mfaRequired,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t/* best-effort: sign-in must not break on an audit failure */\n\t\t\t}\n\t\t}\n\n\t\treturn { id, token }\n\t}\n\n\tasync findApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<ApiKeyRow | null> {\n\t\treturn await dbContext.queryHandler.fetch(\n\t\t\tnew ApiKeyByIdQuery(apiKeyId),\n\t\t)\n\t}\n\n\tasync disableOneOffApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableOneOffApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<boolean> {\n\t\treturn await dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableIdentityApiKeys(dbContext: DatabaseContext, identityId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableIdentityApiKeysCommand(identityId))\n\t}\n\n\tasync createGlobalPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tdescription: string,\n\t\troles: readonly string[],\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createPermanentApiKey(db, description, roles, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n\n\tasync createProjectPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tprojectId: string,\n\t\tmemberships: readonly Acl.Membership[],\n\t\tdescription: string,\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createProjectPermanentApiKey(db, projectId, memberships, description, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n}\n\ntype FetchedApiKey = {\n\trow: ApiKeyRow\n\tsourceDbContext: DatabaseContext\n}\n\nexport type VerifyResponse = Response<VerifyResult, VerifyErrorCode>\n\nexport class VerifyResult {\n\treadonly valid = true\n\n\tconstructor(\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly apiKeyId: string,\n\t\tpublic readonly roles: string[],\n\t\tpublic readonly personId: string | null,\n\t\tpublic readonly trustForwardedInfo: boolean = false,\n\t) {}\n}\n\nexport enum VerifyErrorCode {\n\tNOT_FOUND = 'not_found',\n\tDISABLED = 'disabled',\n\tEXPIRED = 'expired',\n\tNO_AUTH_HEADER = 'no_auth_header',\n\tINVALID_AUTH_HEADER = 'invalid_auth_header',\n}\n"],"names":["UnpersistedApiKeyManager","ResponseOk","ResponseError","DisableApiKeyCommand","intervalToSeconds","PROLONG_THROTTLE_MS","ProlongApiKeyCommand","ApiKeyByTokenQuery","ConfigurationQuery","IdentityQuery","CreateApiKeyCommand","ApiKey","intervalToPostgres","ApiKeyByIdQuery","DisableOneOffApiKeyCommand","DisableIdentityApiKeysCommand","VerifyErrorCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyBO,MAAM,cAAc;AAAA,EAC1B,YACkB,eACA,oBACA,gBACA,2BAAqD,IAAIA,yBAAAA,yBAAA,GACzD,uBAChB;AALgB,SAAA,gBAAA;AACA,SAAA,qBAAA;AACA,SAAA,iBAAA;AACA,SAAA,2BAAA;AACA,SAAA,wBAAA;AAAA,EACf;AAAA,EAEH,MAAM,iBACL,WACA,eACA,OACA,aACA,eAC0B;A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AC;AAAA,EAC5E;AAAA,EAEA,MAAM,cAAc,WAA4B,UAAoC;AACnF,WAAO,MAAM,UAAU,WAAW,QAAQ,IAAIX,qBAAAA,qBAAqB,QAAQ,CAAC;AAAA,EAC7E;AAAA,EAEA,MAAM,uBAAuB,WAA4B,YAAmC;AAC3F,UAAM,UAAU,WAAW,QAAQ,IAAIY,8BAAAA,8BAA8B,UAAU,CAAC;AAAA,EACjF;AAAA,EAEA,MAAM,4BACL,WACA,aACA,OACA,WACA,oBACgC;AAChC,WAAO,MAAM,UAAU,YAAY,OAAM,OAAM;AAC9C,aAAO,MAAM,KAAK,cAAc,sBAAsB,IAAI,aAAa,OAAO,WAAW,kBAAkB;AAAA,IAC5G,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,6BACL,WACA,WACA,aACA,aACA,WACA,oBACgC;AAChC,WAAO,MAAM,UAAU,YAAY,OAAM,OAAM;AAC9C,aAAO,MAAM,KAAK,cAAc,6BAA6B,IAAI,WAAW,aAAa,aAAa,WAAW,kBAAkB;AAAA,IACpI,CAAC;AAAA,EACF;AACD;AASO,MAAM,aAAa;AAAA,EAGzB,YACiB,YACA,UACA,OACA,UACA,qBAA8B,OAC7C;AALe,SAAA,aAAA;AACA,SAAA,WAAA;AACA,SAAA,QAAA;AACA,SAAA,WAAA;AACA,SAAA,qBAAA;AAPjB,kBAAA,MAAS,SAAQ,IAAA;AAAA,EAQd;AACJ;AAEO,IAAK,oCAAAC,qBAAL;AACNA,mBAAA,WAAA,IAAY;AACZA,mBAAA,UAAA,IAAW;AACXA,mBAAA,SAAA,IAAU;AACVA,mBAAA,gBAAA,IAAiB;AACjBA,mBAAA,qBAAA,IAAsB;AALX,SAAAA;AAAA,GAAA,mBAAA,CAAA,CAAA;;;;"}
@@ -34,10 +34,11 @@ class ApiKeyManager {
34
34
  if (unpersistedResult !== null) {
35
35
  return new ResponseOk(unpersistedResult);
36
36
  }
37
- const apiKeyRow = await readDbContext.queryHandler.fetch(new ApiKeyByTokenQuery(token));
38
- if (apiKeyRow === null) {
37
+ const fetchedApiKey = await this.fetchApiKeyByToken(dbContext, readDbContext, token);
38
+ if (fetchedApiKey === null) {
39
39
  return new ResponseError("not_found", "API key was not found");
40
40
  }
41
+ const apiKeyRow = fetchedApiKey.row;
41
42
  if (apiKeyRow.disabled_at !== null) {
42
43
  return new ResponseError(
43
44
  "disabled",
@@ -85,7 +86,7 @@ class ApiKeyManager {
85
86
  userAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent
86
87
  } : requestInfo;
87
88
  if (this.idpSessionRevalidator) {
88
- const outcome = await this.idpSessionRevalidator.revalidate(dbContext, readDbContext, apiKeyRow, effectiveInfo);
89
+ const outcome = await this.idpSessionRevalidator.revalidate(dbContext, fetchedApiKey.sourceDbContext, apiKeyRow, effectiveInfo);
89
90
  if (outcome === "revoked") {
90
91
  return new ResponseError("disabled", "IdP session was revoked");
91
92
  }
@@ -118,6 +119,18 @@ class ApiKeyManager {
118
119
  )
119
120
  );
120
121
  }
122
+ async fetchApiKeyByToken(dbContext, readDbContext, token) {
123
+ const query = new ApiKeyByTokenQuery(token);
124
+ const replicaRow = await readDbContext.queryHandler.fetch(query);
125
+ if (replicaRow !== null) {
126
+ return { row: replicaRow, sourceDbContext: readDbContext };
127
+ }
128
+ if (readDbContext.client.connection === dbContext.client.connection) {
129
+ return null;
130
+ }
131
+ const primaryRow = await dbContext.queryHandler.fetch(query);
132
+ return primaryRow !== null ? { row: primaryRow, sourceDbContext: dbContext } : null;
133
+ }
121
134
  async createSessionApiKey(dbContext, identityId, expiration, requestInfo, trustForwardedInfo) {
122
135
  const { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo);
123
136
  return token;
@@ -1 +1 @@
1
- {"version":3,"file":"ApiKeyManager.js","sources":["../../../../../../../packages/engine-tenant-api/src/model/service/apiKey/ApiKeyManager.ts"],"sourcesContent":["import {\n\tApiKeyRequestInfo,\n\tCreateApiKeyCommand,\n\tDisableApiKeyCommand,\n\tDisableIdentityApiKeysCommand,\n\tDisableOneOffApiKeyCommand,\n\tPROLONG_THROTTLE_MS,\n\tProlongApiKeyCommand,\n} from '../../commands/index.js'\nimport { ApiKey } from '../../type/index.js'\n\nimport { Response, ResponseError, ResponseOk } from '../../utils/Response.js'\nimport { DatabaseContext, TokenHash } from '../../utils/index.js'\nimport { ApiKeyService, CreateApiKeyResponse } from './ApiKeyService.js'\nimport assert from 'node:assert'\nimport { Acl } from '@contember/schema'\nimport { ApiKeyByIdQuery, ApiKeyByTokenQuery, ApiKeyRow, ConfigurationQuery, IdentityQuery } from '../../queries/index.js'\nimport PostgresInterval from 'postgres-interval'\nimport { Config } from '../../type/Config.js'\nimport { intervalToPostgres, intervalToSeconds } from '../../utils/interval.js'\nimport { AuthPolicyResolver } from '../AuthPolicyResolver.js'\nimport { AuthLogService } from '../AuthLogService.js'\nimport { IdpSessionRevalidator } from '../idp/IdpSessionRevalidator.js'\nimport { UnpersistedApiKeyManager } from './UnpersistedApiKeyManager.js'\n\nexport class ApiKeyManager {\n\tconstructor(\n\t\tprivate readonly apiKeyService: ApiKeyService,\n\t\tprivate readonly authPolicyResolver: AuthPolicyResolver,\n\t\tprivate readonly authLogService: AuthLogService,\n\t\tprivate readonly unpersistedApiKeyManager: UnpersistedApiKeyManager = new UnpersistedApiKeyManager(),\n\t\tprivate readonly idpSessionRevalidator?: IdpSessionRevalidator,\n\t) {}\n\n\tasync verifyAndProlong(\n\t\tdbContext: DatabaseContext,\n\t\treadDbContext: DatabaseContext,\n\t\ttoken: string,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\tforwardedInfo?: ApiKeyRequestInfo,\n\t): Promise<VerifyResponse> {\n\t\tconst unpersistedResult = this.unpersistedApiKeyManager.verify(token)\n\t\tif (unpersistedResult !== null) {\n\t\t\t// Configured (unpersisted) root token: no DB row to prolong/track.\n\t\t\treturn new ResponseOk(unpersistedResult)\n\t\t}\n\n\t\tconst apiKeyRow = await readDbContext.queryHandler.fetch(new ApiKeyByTokenQuery(token))\n\t\tif (apiKeyRow === null) {\n\t\t\treturn new ResponseError(VerifyErrorCode.NOT_FOUND, 'API key was not found')\n\t\t}\n\n\t\tif (apiKeyRow.disabled_at !== null) {\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key was disabled at ${apiKeyRow.disabled_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// Single injectable clock for all session-policy time math (matches issuance,\n\t\t// which uses providers.now()), so the A19 idle/max logic is deterministically testable.\n\t\tconst now = dbContext.providers.now()\n\t\tif (apiKeyRow.expires_at !== null && apiKeyRow.expires_at <= now) {\n\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, `API key expired at ${apiKeyRow.expires_at.toISOString()}`)\n\t\t}\n\n\t\t// A19: absolute hard cap (defensive — the prolong clamp should already keep\n\t\t// expires_at <= max_expires_at, but enforce it here regardless).\n\t\tif (apiKeyRow.max_expires_at !== null && apiKeyRow.max_expires_at <= now) {\n\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key reached its maximum lifetime at ${apiKeyRow.max_expires_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// A19: idle timeout. Reject + disable when the session has been idle longer\n\t\t// than the policy's idle_timeout. A null idle_timeout (today's default) or a\n\t\t// never-used key (last_used_at null) are never idle-expired.\n\t\tif (apiKeyRow.idle_timeout !== null && apiKeyRow.last_used_at !== null) {\n\t\t\tconst idleMs = intervalToSeconds(apiKeyRow.idle_timeout) * 1000\n\t\t\t// last_used_at is written at most once per PROLONG_THROTTLE_MS (tracking is\n\t\t\t// throttled), so it can legitimately lag a continuously-active session by up\n\t\t\t// to that window. Add the throttle as slack so a small idle_timeout can't\n\t\t\t// idle-expire a session that is actually in use.\n\t\t\tif (now.getTime() - apiKeyRow.last_used_at.getTime() > idleMs + PROLONG_THROTTLE_MS) {\n\t\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\t\ttry {\n\t\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\t\ttype: 'session_expired_idle',\n\t\t\t\t\t\tidentityId: apiKeyRow.identity_id,\n\t\t\t\t\t\tpersonId: apiKeyRow.person_id,\n\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\teventData: {\n\t\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at?.toISOString() ?? null,\n\t\t\t\t\t\t\tidleTimeout: String(apiKeyRow.idle_timeout),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort: auth path must stay resilient */\n\t\t\t\t}\n\t\t\t\treturn new ResponseError(\n\t\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t\t`API key was idle since ${apiKeyRow.last_used_at.toISOString()} and exceeded the idle timeout`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst effectiveInfo: ApiKeyRequestInfo | undefined = apiKeyRow.trust_forwarded_info && forwardedInfo\n\t\t\t? {\n\t\t\t\tip: forwardedInfo.ip ?? requestInfo?.ip,\n\t\t\t\tuserAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent,\n\t\t\t}\n\t\t\t: requestInfo\n\n\t\t// Re-validate IdP-backed sessions against their identity provider (A24). In the\n\t\t// default `background` mode this returns immediately and revalidates after the\n\t\t// response (revocation lands on the next request); in `blocking` mode it can revoke\n\t\t// the current request. No-op for password sessions and IdPs without revalidation.\n\t\t// `effectiveInfo` is passed so the audit entries record the originating request's IP/UA.\n\t\tif (this.idpSessionRevalidator) {\n\t\t\tconst outcome = await this.idpSessionRevalidator.revalidate(dbContext, readDbContext, apiKeyRow, effectiveInfo)\n\t\t\tif (outcome === 'revoked') {\n\t\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, 'IdP session was revoked')\n\t\t\t}\n\t\t}\n\n\t\t// Detached (runs after the response), so a rejection here would be an unhandledRejection and can take the\n\t\t// worker down. Tracking is best-effort — the next request writes it again.\n\t\tsetImmediate(() => {\n\t\t\tdbContext.commandBus.execute(\n\t\t\t\tnew ProlongApiKeyCommand(\n\t\t\t\t\tapiKeyRow.id,\n\t\t\t\t\tapiKeyRow.type,\n\t\t\t\t\tapiKeyRow.expiration,\n\t\t\t\t\tapiKeyRow.expires_at,\n\t\t\t\t\teffectiveInfo,\n\t\t\t\t\t{\n\t\t\t\t\t\tlastIp: apiKeyRow.last_ip,\n\t\t\t\t\t\tlastUserAgent: apiKeyRow.last_user_agent,\n\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at,\n\t\t\t\t\t},\n\t\t\t\t\tapiKeyRow.max_expires_at,\n\t\t\t\t),\n\t\t\t).catch(() => {})\n\t\t})\n\n\t\treturn new ResponseOk(\n\t\t\tnew VerifyResult(\n\t\t\t\tapiKeyRow.identity_id,\n\t\t\t\tapiKeyRow.id,\n\t\t\t\tapiKeyRow.roles,\n\t\t\t\tapiKeyRow.person_id,\n\t\t\t\tapiKeyRow.trust_forwarded_info,\n\t\t\t),\n\t\t)\n\t}\n\n\tasync createSessionApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<string> {\n\t\tconst { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo)\n\t\treturn token\n\t}\n\n\t/**\n\t * Like {@link createSessionApiKey} but also returns the api_key id — needed when the\n\t * caller has to bind another row to the session (e.g. an `idp_session` for IdP\n\t * re-validation).\n\t */\n\tasync createSessionApiKeyWithId(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<{ id: string; token: string }> {\n\t\tconst config = await dbContext.queryHandler.fetch(new ConfigurationQuery(dbContext.providers))\n\n\t\t// A19: snapshot the effective session policy onto the api_key at sign-in.\n\t\t// With no matching policy, every field is null/baseline and the result is\n\t\t// byte-for-byte today's behavior.\n\t\tconst [identityRow] = await dbContext.queryHandler.fetch(new IdentityQuery([identityId]))\n\t\tconst globalRoles = identityRow?.roles ?? []\n\t\tconst policy = await this.authPolicyResolver.resolveForIdentity(dbContext, identityId, globalRoles)\n\n\t\tconst defaultExpirationMinutes = intervalToSeconds(config.login.defaultTokenExpiration) / 60\n\t\t// remember_me_allowed === false: ignore a client-supplied longer lifetime and\n\t\t// force the default. (true/null leave the requested expiration untouched.)\n\t\tconst requestedMinutes = policy.rememberMeAllowed === false\n\t\t\t? defaultExpirationMinutes\n\t\t\t: (expiration ?? defaultExpirationMinutes)\n\n\t\t// Cap by maxTokenExpiration (existing behavior) AND by the policy's\n\t\t// tokenExpiration (A19) — strictest wins.\n\t\tlet expirationCapped = config.login.maxTokenExpiration\n\t\t\t? Math.min(requestedMinutes, intervalToSeconds(config.login.maxTokenExpiration) / 60)\n\t\t\t: requestedMinutes\n\t\tif (policy.tokenExpiration) {\n\t\t\texpirationCapped = Math.min(expirationCapped, intervalToSeconds(policy.tokenExpiration) / 60)\n\t\t}\n\n\t\t// Absolute hard cap: issued_at + policy.tokenExpiration. NULL = uncapped\n\t\t// sliding window (today's behavior).\n\t\tconst issuedAt = dbContext.providers.now()\n\t\tconst maxExpiresAt = policy.tokenExpiration\n\t\t\t? new Date(issuedAt.getTime() + intervalToSeconds(policy.tokenExpiration) * 1000)\n\t\t\t: null\n\n\t\tconst command = new CreateApiKeyCommand({\n\t\t\ttype: ApiKey.Type.SESSION,\n\t\t\tidentityId,\n\t\t\texpiration: expirationCapped,\n\t\t\trequestInfo,\n\t\t\ttrustForwardedInfo,\n\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\tmaxExpiresAt,\n\t\t})\n\t\tconst { id, token } = await dbContext.commandBus.execute(command)\n\t\tassert(token !== undefined)\n\n\t\t// A19: audit only when a policy is actually in effect. With zero auth_policy\n\t\t// rows the resolved policy is inert and no extra insert happens.\n\t\tconst policyApplied = policy.mfaRequired === true\n\t\t\t|| policy.tokenExpiration !== null\n\t\t\t|| policy.idleTimeout !== null\n\t\t\t|| policy.rememberMeAllowed !== null\n\t\tif (policyApplied) {\n\t\t\ttry {\n\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\ttype: 'session_policy_applied',\n\t\t\t\t\tidentityId,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\teventData: {\n\t\t\t\t\t\ttokenExpiration: policy.tokenExpiration ? intervalToPostgres(policy.tokenExpiration) : null,\n\t\t\t\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\t\t\t\trememberMeAllowed: policy.rememberMeAllowed,\n\t\t\t\t\t\tmfaRequired: policy.mfaRequired,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t/* best-effort: sign-in must not break on an audit failure */\n\t\t\t}\n\t\t}\n\n\t\treturn { id, token }\n\t}\n\n\tasync findApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<ApiKeyRow | null> {\n\t\treturn await dbContext.queryHandler.fetch(\n\t\t\tnew ApiKeyByIdQuery(apiKeyId),\n\t\t)\n\t}\n\n\tasync disableOneOffApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableOneOffApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<boolean> {\n\t\treturn await dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableIdentityApiKeys(dbContext: DatabaseContext, identityId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableIdentityApiKeysCommand(identityId))\n\t}\n\n\tasync createGlobalPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tdescription: string,\n\t\troles: readonly string[],\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createPermanentApiKey(db, description, roles, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n\n\tasync createProjectPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tprojectId: string,\n\t\tmemberships: readonly Acl.Membership[],\n\t\tdescription: string,\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createProjectPermanentApiKey(db, projectId, memberships, description, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n}\n\nexport type VerifyResponse = Response<VerifyResult, VerifyErrorCode>\n\nexport class VerifyResult {\n\treadonly valid = true\n\n\tconstructor(\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly apiKeyId: string,\n\t\tpublic readonly roles: string[],\n\t\tpublic readonly personId: string | null,\n\t\tpublic readonly trustForwardedInfo: boolean = false,\n\t) {}\n}\n\nexport enum VerifyErrorCode {\n\tNOT_FOUND = 'not_found',\n\tDISABLED = 'disabled',\n\tEXPIRED = 'expired',\n\tNO_AUTH_HEADER = 'no_auth_header',\n\tINVALID_AUTH_HEADER = 'invalid_auth_header',\n}\n"],"names":["VerifyErrorCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyBO,MAAM,cAAc;AAAA,EAC1B,YACkB,eACA,oBACA,gBACA,2BAAqD,IAAI,yBAAA,GACzD,uBAChB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C,WAAO,MAAM,UAAU,YAAY,OAAM,OAAM;AAC9C,aAAO,MAAM,KAAK,cAAc,6BAA6B,IAAI,WAAW,aAAa,aAAa,WAAW,kBAAkB;AAAA,IACpI,CAAC;AAAA,EACF;AACD;AAIO,MAAM,aAAa;AAAA,EAGzB,YACiB,YACA,UACA,OACA,UACA,qBAA8B,OAC7C;AALe,SAAA,aAAA;AACA,SAAA,WAAA;AACA,SAAA,QAAA;AACA,SAAA,WAAA;AACA,SAAA,qBAAA;AAPjB,kBAAA,MAAS,SAAQ,IAAA;AAAA,EAQd;AACJ;AAEO,IAAK,oCAAAA,qBAAL;AACNA,mBAAA,WAAA,IAAY;AACZA,mBAAA,UAAA,IAAW;AACXA,mBAAA,SAAA,IAAU;AACVA,mBAAA,gBAAA,IAAiB;AACjBA,mBAAA,qBAAA,IAAsB;AALX,SAAAA;AAAA,GAAA,mBAAA,CAAA,CAAA;"}
1
+ {"version":3,"file":"ApiKeyManager.js","sources":["../../../../../../../packages/engine-tenant-api/src/model/service/apiKey/ApiKeyManager.ts"],"sourcesContent":["import {\n\tApiKeyRequestInfo,\n\tCreateApiKeyCommand,\n\tDisableApiKeyCommand,\n\tDisableIdentityApiKeysCommand,\n\tDisableOneOffApiKeyCommand,\n\tPROLONG_THROTTLE_MS,\n\tProlongApiKeyCommand,\n} from '../../commands/index.js'\nimport { ApiKey } from '../../type/index.js'\n\nimport { Response, ResponseError, ResponseOk } from '../../utils/Response.js'\nimport { DatabaseContext, TokenHash } from '../../utils/index.js'\nimport { ApiKeyService, CreateApiKeyResponse } from './ApiKeyService.js'\nimport assert from 'node:assert'\nimport { Acl } from '@contember/schema'\nimport { ApiKeyByIdQuery, ApiKeyByTokenQuery, ApiKeyRow, ConfigurationQuery, IdentityQuery } from '../../queries/index.js'\nimport PostgresInterval from 'postgres-interval'\nimport { Config } from '../../type/Config.js'\nimport { intervalToPostgres, intervalToSeconds } from '../../utils/interval.js'\nimport { AuthPolicyResolver } from '../AuthPolicyResolver.js'\nimport { AuthLogService } from '../AuthLogService.js'\nimport { IdpSessionRevalidator } from '../idp/IdpSessionRevalidator.js'\nimport { UnpersistedApiKeyManager } from './UnpersistedApiKeyManager.js'\n\nexport class ApiKeyManager {\n\tconstructor(\n\t\tprivate readonly apiKeyService: ApiKeyService,\n\t\tprivate readonly authPolicyResolver: AuthPolicyResolver,\n\t\tprivate readonly authLogService: AuthLogService,\n\t\tprivate readonly unpersistedApiKeyManager: UnpersistedApiKeyManager = new UnpersistedApiKeyManager(),\n\t\tprivate readonly idpSessionRevalidator?: IdpSessionRevalidator,\n\t) {}\n\n\tasync verifyAndProlong(\n\t\tdbContext: DatabaseContext,\n\t\treadDbContext: DatabaseContext,\n\t\ttoken: string,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\tforwardedInfo?: ApiKeyRequestInfo,\n\t): Promise<VerifyResponse> {\n\t\tconst unpersistedResult = this.unpersistedApiKeyManager.verify(token)\n\t\tif (unpersistedResult !== null) {\n\t\t\t// Configured (unpersisted) root token: no DB row to prolong/track.\n\t\t\treturn new ResponseOk(unpersistedResult)\n\t\t}\n\n\t\tconst fetchedApiKey = await this.fetchApiKeyByToken(dbContext, readDbContext, token)\n\t\tif (fetchedApiKey === null) {\n\t\t\treturn new ResponseError(VerifyErrorCode.NOT_FOUND, 'API key was not found')\n\t\t}\n\t\tconst apiKeyRow = fetchedApiKey.row\n\n\t\tif (apiKeyRow.disabled_at !== null) {\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key was disabled at ${apiKeyRow.disabled_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// Single injectable clock for all session-policy time math (matches issuance,\n\t\t// which uses providers.now()), so the A19 idle/max logic is deterministically testable.\n\t\tconst now = dbContext.providers.now()\n\t\tif (apiKeyRow.expires_at !== null && apiKeyRow.expires_at <= now) {\n\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, `API key expired at ${apiKeyRow.expires_at.toISOString()}`)\n\t\t}\n\n\t\t// A19: absolute hard cap (defensive — the prolong clamp should already keep\n\t\t// expires_at <= max_expires_at, but enforce it here regardless).\n\t\tif (apiKeyRow.max_expires_at !== null && apiKeyRow.max_expires_at <= now) {\n\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key reached its maximum lifetime at ${apiKeyRow.max_expires_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// A19: idle timeout. Reject + disable when the session has been idle longer\n\t\t// than the policy's idle_timeout. A null idle_timeout (today's default) or a\n\t\t// never-used key (last_used_at null) are never idle-expired.\n\t\tif (apiKeyRow.idle_timeout !== null && apiKeyRow.last_used_at !== null) {\n\t\t\tconst idleMs = intervalToSeconds(apiKeyRow.idle_timeout) * 1000\n\t\t\t// last_used_at is written at most once per PROLONG_THROTTLE_MS (tracking is\n\t\t\t// throttled), so it can legitimately lag a continuously-active session by up\n\t\t\t// to that window. Add the throttle as slack so a small idle_timeout can't\n\t\t\t// idle-expire a session that is actually in use.\n\t\t\tif (now.getTime() - apiKeyRow.last_used_at.getTime() > idleMs + PROLONG_THROTTLE_MS) {\n\t\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\t\ttry {\n\t\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\t\ttype: 'session_expired_idle',\n\t\t\t\t\t\tidentityId: apiKeyRow.identity_id,\n\t\t\t\t\t\tpersonId: apiKeyRow.person_id,\n\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\teventData: {\n\t\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at?.toISOString() ?? null,\n\t\t\t\t\t\t\tidleTimeout: String(apiKeyRow.idle_timeout),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort: auth path must stay resilient */\n\t\t\t\t}\n\t\t\t\treturn new ResponseError(\n\t\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t\t`API key was idle since ${apiKeyRow.last_used_at.toISOString()} and exceeded the idle timeout`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst effectiveInfo: ApiKeyRequestInfo | undefined = apiKeyRow.trust_forwarded_info && forwardedInfo\n\t\t\t? {\n\t\t\t\tip: forwardedInfo.ip ?? requestInfo?.ip,\n\t\t\t\tuserAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent,\n\t\t\t}\n\t\t\t: requestInfo\n\n\t\t// Re-validate IdP-backed sessions against their identity provider (A24). In the\n\t\t// default `background` mode this returns immediately and revalidates after the\n\t\t// response (revocation lands on the next request); in `blocking` mode it can revoke\n\t\t// the current request. No-op for password sessions and IdPs without revalidation.\n\t\t// `effectiveInfo` is passed so the audit entries record the originating request's IP/UA.\n\t\t// The idp_session row is written together with the api_key, so it is read from where the key was found.\n\t\tif (this.idpSessionRevalidator) {\n\t\t\tconst outcome = await this.idpSessionRevalidator.revalidate(dbContext, fetchedApiKey.sourceDbContext, apiKeyRow, effectiveInfo)\n\t\t\tif (outcome === 'revoked') {\n\t\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, 'IdP session was revoked')\n\t\t\t}\n\t\t}\n\n\t\t// Detached (runs after the response), so a rejection here would be an unhandledRejection and can take the\n\t\t// worker down. Tracking is best-effort — the next request writes it again.\n\t\tsetImmediate(() => {\n\t\t\tdbContext.commandBus.execute(\n\t\t\t\tnew ProlongApiKeyCommand(\n\t\t\t\t\tapiKeyRow.id,\n\t\t\t\t\tapiKeyRow.type,\n\t\t\t\t\tapiKeyRow.expiration,\n\t\t\t\t\tapiKeyRow.expires_at,\n\t\t\t\t\teffectiveInfo,\n\t\t\t\t\t{\n\t\t\t\t\t\tlastIp: apiKeyRow.last_ip,\n\t\t\t\t\t\tlastUserAgent: apiKeyRow.last_user_agent,\n\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at,\n\t\t\t\t\t},\n\t\t\t\t\tapiKeyRow.max_expires_at,\n\t\t\t\t),\n\t\t\t).catch(() => {})\n\t\t})\n\n\t\treturn new ResponseOk(\n\t\t\tnew VerifyResult(\n\t\t\t\tapiKeyRow.identity_id,\n\t\t\t\tapiKeyRow.id,\n\t\t\t\tapiKeyRow.roles,\n\t\t\t\tapiKeyRow.person_id,\n\t\t\t\tapiKeyRow.trust_forwarded_info,\n\t\t\t),\n\t\t)\n\t}\n\n\tprivate async fetchApiKeyByToken(dbContext: DatabaseContext, readDbContext: DatabaseContext, token: string): Promise<FetchedApiKey | null> {\n\t\tconst query = new ApiKeyByTokenQuery(token)\n\t\tconst replicaRow = await readDbContext.queryHandler.fetch(query)\n\t\tif (replicaRow !== null) {\n\t\t\treturn { row: replicaRow, sourceDbContext: readDbContext }\n\t\t}\n\t\tif (readDbContext.client.connection === dbContext.client.connection) {\n\t\t\treturn null\n\t\t}\n\t\t// A token issued moments ago (sign-in, createSessionToken) may not have reached the read replica yet.\n\t\tconst primaryRow = await dbContext.queryHandler.fetch(query)\n\t\treturn primaryRow !== null ? { row: primaryRow, sourceDbContext: dbContext } : null\n\t}\n\n\tasync createSessionApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<string> {\n\t\tconst { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo)\n\t\treturn token\n\t}\n\n\t/**\n\t * Like {@link createSessionApiKey} but also returns the api_key id — needed when the\n\t * caller has to bind another row to the session (e.g. an `idp_session` for IdP\n\t * re-validation).\n\t */\n\tasync createSessionApiKeyWithId(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<{ id: string; token: string }> {\n\t\tconst config = await dbContext.queryHandler.fetch(new ConfigurationQuery(dbContext.providers))\n\n\t\t// A19: snapshot the effective session policy onto the api_key at sign-in.\n\t\t// With no matching policy, every field is null/baseline and the result is\n\t\t// byte-for-byte today's behavior.\n\t\tconst [identityRow] = await dbContext.queryHandler.fetch(new IdentityQuery([identityId]))\n\t\tconst globalRoles = identityRow?.roles ?? []\n\t\tconst policy = await this.authPolicyResolver.resolveForIdentity(dbContext, identityId, globalRoles)\n\n\t\tconst defaultExpirationMinutes = intervalToSeconds(config.login.defaultTokenExpiration) / 60\n\t\t// remember_me_allowed === false: ignore a client-supplied longer lifetime and\n\t\t// force the default. (true/null leave the requested expiration untouched.)\n\t\tconst requestedMinutes = policy.rememberMeAllowed === false\n\t\t\t? defaultExpirationMinutes\n\t\t\t: (expiration ?? defaultExpirationMinutes)\n\n\t\t// Cap by maxTokenExpiration (existing behavior) AND by the policy's\n\t\t// tokenExpiration (A19) — strictest wins.\n\t\tlet expirationCapped = config.login.maxTokenExpiration\n\t\t\t? Math.min(requestedMinutes, intervalToSeconds(config.login.maxTokenExpiration) / 60)\n\t\t\t: requestedMinutes\n\t\tif (policy.tokenExpiration) {\n\t\t\texpirationCapped = Math.min(expirationCapped, intervalToSeconds(policy.tokenExpiration) / 60)\n\t\t}\n\n\t\t// Absolute hard cap: issued_at + policy.tokenExpiration. NULL = uncapped\n\t\t// sliding window (today's behavior).\n\t\tconst issuedAt = dbContext.providers.now()\n\t\tconst maxExpiresAt = policy.tokenExpiration\n\t\t\t? new Date(issuedAt.getTime() + intervalToSeconds(policy.tokenExpiration) * 1000)\n\t\t\t: null\n\n\t\tconst command = new CreateApiKeyCommand({\n\t\t\ttype: ApiKey.Type.SESSION,\n\t\t\tidentityId,\n\t\t\texpiration: expirationCapped,\n\t\t\trequestInfo,\n\t\t\ttrustForwardedInfo,\n\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\tmaxExpiresAt,\n\t\t})\n\t\tconst { id, token } = await dbContext.commandBus.execute(command)\n\t\tassert(token !== undefined)\n\n\t\t// A19: audit only when a policy is actually in effect. With zero auth_policy\n\t\t// rows the resolved policy is inert and no extra insert happens.\n\t\tconst policyApplied = policy.mfaRequired === true\n\t\t\t|| policy.tokenExpiration !== null\n\t\t\t|| policy.idleTimeout !== null\n\t\t\t|| policy.rememberMeAllowed !== null\n\t\tif (policyApplied) {\n\t\t\ttry {\n\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\ttype: 'session_policy_applied',\n\t\t\t\t\tidentityId,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\teventData: {\n\t\t\t\t\t\ttokenExpiration: policy.tokenExpiration ? intervalToPostgres(policy.tokenExpiration) : null,\n\t\t\t\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\t\t\t\trememberMeAllowed: policy.rememberMeAllowed,\n\t\t\t\t\t\tmfaRequired: policy.mfaRequired,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t/* best-effort: sign-in must not break on an audit failure */\n\t\t\t}\n\t\t}\n\n\t\treturn { id, token }\n\t}\n\n\tasync findApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<ApiKeyRow | null> {\n\t\treturn await dbContext.queryHandler.fetch(\n\t\t\tnew ApiKeyByIdQuery(apiKeyId),\n\t\t)\n\t}\n\n\tasync disableOneOffApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableOneOffApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<boolean> {\n\t\treturn await dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableIdentityApiKeys(dbContext: DatabaseContext, identityId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableIdentityApiKeysCommand(identityId))\n\t}\n\n\tasync createGlobalPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tdescription: string,\n\t\troles: readonly string[],\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createPermanentApiKey(db, description, roles, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n\n\tasync createProjectPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tprojectId: string,\n\t\tmemberships: readonly Acl.Membership[],\n\t\tdescription: string,\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createProjectPermanentApiKey(db, projectId, memberships, description, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n}\n\ntype FetchedApiKey = {\n\trow: ApiKeyRow\n\tsourceDbContext: DatabaseContext\n}\n\nexport type VerifyResponse = Response<VerifyResult, VerifyErrorCode>\n\nexport class VerifyResult {\n\treadonly valid = true\n\n\tconstructor(\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly apiKeyId: string,\n\t\tpublic readonly roles: string[],\n\t\tpublic readonly personId: string | null,\n\t\tpublic readonly trustForwardedInfo: boolean = false,\n\t) {}\n}\n\nexport enum VerifyErrorCode {\n\tNOT_FOUND = 'not_found',\n\tDISABLED = 'disabled',\n\tEXPIRED = 'expired',\n\tNO_AUTH_HEADER = 'no_auth_header',\n\tINVALID_AUTH_HEADER = 'invalid_auth_header',\n}\n"],"names":["VerifyErrorCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyBO,MAAM,cAAc;AAAA,EAC1B,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A,EAC5E;AAAA,EAEA,MAAM,cAAc,WAA4B,UAAoC;AACnF,WAAO,MAAM,UAAU,WAAW,QAAQ,IAAI,qBAAqB,QAAQ,CAAC;AAAA,EAC7E;AAAA,EAEA,MAAM,uBAAuB,WAA4B,YAAmC;AAC3F,UAAM,UAAU,WAAW,QAAQ,IAAI,8BAA8B,UAAU,CAAC;AAAA,EACjF;AAAA,EAEA,MAAM,4BACL,WACA,aACA,OACA,WACA,oBACgC;AAChC,WAAO,MAAM,UAAU,YAAY,OAAM,OAAM;AAC9C,aAAO,MAAM,KAAK,cAAc,sBAAsB,IAAI,aAAa,OAAO,WAAW,kBAAkB;AAAA,IAC5G,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,6BACL,WACA,WACA,aACA,aACA,WACA,oBACgC;AAChC,WAAO,MAAM,UAAU,YAAY,OAAM,OAAM;AAC9C,aAAO,MAAM,KAAK,cAAc,6BAA6B,IAAI,WAAW,aAAa,aAAa,WAAW,kBAAkB;AAAA,IACpI,CAAC;AAAA,EACF;AACD;AASO,MAAM,aAAa;AAAA,EAGzB,YACiB,YACA,UACA,OACA,UACA,qBAA8B,OAC7C;AALe,SAAA,aAAA;AACA,SAAA,WAAA;AACA,SAAA,QAAA;AACA,SAAA,WAAA;AACA,SAAA,qBAAA;AAPjB,kBAAA,MAAS,SAAQ,IAAA;AAAA,EAQd;AACJ;AAEO,IAAK,oCAAAA,qBAAL;AACNA,mBAAA,WAAA,IAAY;AACZA,mBAAA,UAAA,IAAW;AACXA,mBAAA,SAAA,IAAU;AACVA,mBAAA,gBAAA,IAAiB;AACjBA,mBAAA,qBAAA,IAAsB;AALX,SAAAA;AAAA,GAAA,mBAAA,CAAA,CAAA;"}
@@ -36,10 +36,11 @@ class ApiKeyManager {
36
36
  if (unpersistedResult !== null) {
37
37
  return new Response.ResponseOk(unpersistedResult);
38
38
  }
39
- const apiKeyRow = await readDbContext.queryHandler.fetch(new ApiKeyQuery.ApiKeyByTokenQuery(token));
40
- if (apiKeyRow === null) {
39
+ const fetchedApiKey = await this.fetchApiKeyByToken(dbContext, readDbContext, token);
40
+ if (fetchedApiKey === null) {
41
41
  return new Response.ResponseError("not_found", "API key was not found");
42
42
  }
43
+ const apiKeyRow = fetchedApiKey.row;
43
44
  if (apiKeyRow.disabled_at !== null) {
44
45
  return new Response.ResponseError(
45
46
  "disabled",
@@ -87,7 +88,7 @@ class ApiKeyManager {
87
88
  userAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent
88
89
  } : requestInfo;
89
90
  if (this.idpSessionRevalidator) {
90
- const outcome = await this.idpSessionRevalidator.revalidate(dbContext, readDbContext, apiKeyRow, effectiveInfo);
91
+ const outcome = await this.idpSessionRevalidator.revalidate(dbContext, fetchedApiKey.sourceDbContext, apiKeyRow, effectiveInfo);
91
92
  if (outcome === "revoked") {
92
93
  return new Response.ResponseError("disabled", "IdP session was revoked");
93
94
  }
@@ -120,6 +121,18 @@ class ApiKeyManager {
120
121
  )
121
122
  );
122
123
  }
124
+ async fetchApiKeyByToken(dbContext, readDbContext, token) {
125
+ const query = new ApiKeyQuery.ApiKeyByTokenQuery(token);
126
+ const replicaRow = await readDbContext.queryHandler.fetch(query);
127
+ if (replicaRow !== null) {
128
+ return { row: replicaRow, sourceDbContext: readDbContext };
129
+ }
130
+ if (readDbContext.client.connection === dbContext.client.connection) {
131
+ return null;
132
+ }
133
+ const primaryRow = await dbContext.queryHandler.fetch(query);
134
+ return primaryRow !== null ? { row: primaryRow, sourceDbContext: dbContext } : null;
135
+ }
123
136
  async createSessionApiKey(dbContext, identityId, expiration, requestInfo, trustForwardedInfo) {
124
137
  const { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo);
125
138
  return token;
@@ -1 +1 @@
1
- {"version":3,"file":"ApiKeyManager.cjs","sources":["../../../../../../../packages/engine-tenant-api/src/model/service/apiKey/ApiKeyManager.ts"],"sourcesContent":["import {\n\tApiKeyRequestInfo,\n\tCreateApiKeyCommand,\n\tDisableApiKeyCommand,\n\tDisableIdentityApiKeysCommand,\n\tDisableOneOffApiKeyCommand,\n\tPROLONG_THROTTLE_MS,\n\tProlongApiKeyCommand,\n} from '../../commands/index.js'\nimport { ApiKey } from '../../type/index.js'\n\nimport { Response, ResponseError, ResponseOk } from '../../utils/Response.js'\nimport { DatabaseContext, TokenHash } from '../../utils/index.js'\nimport { ApiKeyService, CreateApiKeyResponse } from './ApiKeyService.js'\nimport assert from 'node:assert'\nimport { Acl } from '@contember/schema'\nimport { ApiKeyByIdQuery, ApiKeyByTokenQuery, ApiKeyRow, ConfigurationQuery, IdentityQuery } from '../../queries/index.js'\nimport PostgresInterval from 'postgres-interval'\nimport { Config } from '../../type/Config.js'\nimport { intervalToPostgres, intervalToSeconds } from '../../utils/interval.js'\nimport { AuthPolicyResolver } from '../AuthPolicyResolver.js'\nimport { AuthLogService } from '../AuthLogService.js'\nimport { IdpSessionRevalidator } from '../idp/IdpSessionRevalidator.js'\nimport { UnpersistedApiKeyManager } from './UnpersistedApiKeyManager.js'\n\nexport class ApiKeyManager {\n\tconstructor(\n\t\tprivate readonly apiKeyService: ApiKeyService,\n\t\tprivate readonly authPolicyResolver: AuthPolicyResolver,\n\t\tprivate readonly authLogService: AuthLogService,\n\t\tprivate readonly unpersistedApiKeyManager: UnpersistedApiKeyManager = new UnpersistedApiKeyManager(),\n\t\tprivate readonly idpSessionRevalidator?: IdpSessionRevalidator,\n\t) {}\n\n\tasync verifyAndProlong(\n\t\tdbContext: DatabaseContext,\n\t\treadDbContext: DatabaseContext,\n\t\ttoken: string,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\tforwardedInfo?: ApiKeyRequestInfo,\n\t): Promise<VerifyResponse> {\n\t\tconst unpersistedResult = this.unpersistedApiKeyManager.verify(token)\n\t\tif (unpersistedResult !== null) {\n\t\t\t// Configured (unpersisted) root token: no DB row to prolong/track.\n\t\t\treturn new ResponseOk(unpersistedResult)\n\t\t}\n\n\t\tconst apiKeyRow = await readDbContext.queryHandler.fetch(new ApiKeyByTokenQuery(token))\n\t\tif (apiKeyRow === null) {\n\t\t\treturn new ResponseError(VerifyErrorCode.NOT_FOUND, 'API key was not found')\n\t\t}\n\n\t\tif (apiKeyRow.disabled_at !== null) {\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key was disabled at ${apiKeyRow.disabled_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// Single injectable clock for all session-policy time math (matches issuance,\n\t\t// which uses providers.now()), so the A19 idle/max logic is deterministically testable.\n\t\tconst now = dbContext.providers.now()\n\t\tif (apiKeyRow.expires_at !== null && apiKeyRow.expires_at <= now) {\n\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, `API key expired at ${apiKeyRow.expires_at.toISOString()}`)\n\t\t}\n\n\t\t// A19: absolute hard cap (defensive — the prolong clamp should already keep\n\t\t// expires_at <= max_expires_at, but enforce it here regardless).\n\t\tif (apiKeyRow.max_expires_at !== null && apiKeyRow.max_expires_at <= now) {\n\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key reached its maximum lifetime at ${apiKeyRow.max_expires_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// A19: idle timeout. Reject + disable when the session has been idle longer\n\t\t// than the policy's idle_timeout. A null idle_timeout (today's default) or a\n\t\t// never-used key (last_used_at null) are never idle-expired.\n\t\tif (apiKeyRow.idle_timeout !== null && apiKeyRow.last_used_at !== null) {\n\t\t\tconst idleMs = intervalToSeconds(apiKeyRow.idle_timeout) * 1000\n\t\t\t// last_used_at is written at most once per PROLONG_THROTTLE_MS (tracking is\n\t\t\t// throttled), so it can legitimately lag a continuously-active session by up\n\t\t\t// to that window. Add the throttle as slack so a small idle_timeout can't\n\t\t\t// idle-expire a session that is actually in use.\n\t\t\tif (now.getTime() - apiKeyRow.last_used_at.getTime() > idleMs + PROLONG_THROTTLE_MS) {\n\t\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\t\ttry {\n\t\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\t\ttype: 'session_expired_idle',\n\t\t\t\t\t\tidentityId: apiKeyRow.identity_id,\n\t\t\t\t\t\tpersonId: apiKeyRow.person_id,\n\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\teventData: {\n\t\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at?.toISOString() ?? null,\n\t\t\t\t\t\t\tidleTimeout: String(apiKeyRow.idle_timeout),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort: auth path must stay resilient */\n\t\t\t\t}\n\t\t\t\treturn new ResponseError(\n\t\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t\t`API key was idle since ${apiKeyRow.last_used_at.toISOString()} and exceeded the idle timeout`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst effectiveInfo: ApiKeyRequestInfo | undefined = apiKeyRow.trust_forwarded_info && forwardedInfo\n\t\t\t? {\n\t\t\t\tip: forwardedInfo.ip ?? requestInfo?.ip,\n\t\t\t\tuserAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent,\n\t\t\t}\n\t\t\t: requestInfo\n\n\t\t// Re-validate IdP-backed sessions against their identity provider (A24). In the\n\t\t// default `background` mode this returns immediately and revalidates after the\n\t\t// response (revocation lands on the next request); in `blocking` mode it can revoke\n\t\t// the current request. No-op for password sessions and IdPs without revalidation.\n\t\t// `effectiveInfo` is passed so the audit entries record the originating request's IP/UA.\n\t\tif (this.idpSessionRevalidator) {\n\t\t\tconst outcome = await this.idpSessionRevalidator.revalidate(dbContext, readDbContext, apiKeyRow, effectiveInfo)\n\t\t\tif (outcome === 'revoked') {\n\t\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, 'IdP session was revoked')\n\t\t\t}\n\t\t}\n\n\t\t// Detached (runs after the response), so a rejection here would be an unhandledRejection and can take the\n\t\t// worker down. Tracking is best-effort — the next request writes it again.\n\t\tsetImmediate(() => {\n\t\t\tdbContext.commandBus.execute(\n\t\t\t\tnew ProlongApiKeyCommand(\n\t\t\t\t\tapiKeyRow.id,\n\t\t\t\t\tapiKeyRow.type,\n\t\t\t\t\tapiKeyRow.expiration,\n\t\t\t\t\tapiKeyRow.expires_at,\n\t\t\t\t\teffectiveInfo,\n\t\t\t\t\t{\n\t\t\t\t\t\tlastIp: apiKeyRow.last_ip,\n\t\t\t\t\t\tlastUserAgent: apiKeyRow.last_user_agent,\n\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at,\n\t\t\t\t\t},\n\t\t\t\t\tapiKeyRow.max_expires_at,\n\t\t\t\t),\n\t\t\t).catch(() => {})\n\t\t})\n\n\t\treturn new ResponseOk(\n\t\t\tnew VerifyResult(\n\t\t\t\tapiKeyRow.identity_id,\n\t\t\t\tapiKeyRow.id,\n\t\t\t\tapiKeyRow.roles,\n\t\t\t\tapiKeyRow.person_id,\n\t\t\t\tapiKeyRow.trust_forwarded_info,\n\t\t\t),\n\t\t)\n\t}\n\n\tasync createSessionApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<string> {\n\t\tconst { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo)\n\t\treturn token\n\t}\n\n\t/**\n\t * Like {@link createSessionApiKey} but also returns the api_key id — needed when the\n\t * caller has to bind another row to the session (e.g. an `idp_session` for IdP\n\t * re-validation).\n\t */\n\tasync createSessionApiKeyWithId(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<{ id: string; token: string }> {\n\t\tconst config = await dbContext.queryHandler.fetch(new ConfigurationQuery(dbContext.providers))\n\n\t\t// A19: snapshot the effective session policy onto the api_key at sign-in.\n\t\t// With no matching policy, every field is null/baseline and the result is\n\t\t// byte-for-byte today's behavior.\n\t\tconst [identityRow] = await dbContext.queryHandler.fetch(new IdentityQuery([identityId]))\n\t\tconst globalRoles = identityRow?.roles ?? []\n\t\tconst policy = await this.authPolicyResolver.resolveForIdentity(dbContext, identityId, globalRoles)\n\n\t\tconst defaultExpirationMinutes = intervalToSeconds(config.login.defaultTokenExpiration) / 60\n\t\t// remember_me_allowed === false: ignore a client-supplied longer lifetime and\n\t\t// force the default. (true/null leave the requested expiration untouched.)\n\t\tconst requestedMinutes = policy.rememberMeAllowed === false\n\t\t\t? defaultExpirationMinutes\n\t\t\t: (expiration ?? defaultExpirationMinutes)\n\n\t\t// Cap by maxTokenExpiration (existing behavior) AND by the policy's\n\t\t// tokenExpiration (A19) — strictest wins.\n\t\tlet expirationCapped = config.login.maxTokenExpiration\n\t\t\t? Math.min(requestedMinutes, intervalToSeconds(config.login.maxTokenExpiration) / 60)\n\t\t\t: requestedMinutes\n\t\tif (policy.tokenExpiration) {\n\t\t\texpirationCapped = Math.min(expirationCapped, intervalToSeconds(policy.tokenExpiration) / 60)\n\t\t}\n\n\t\t// Absolute hard cap: issued_at + policy.tokenExpiration. NULL = uncapped\n\t\t// sliding window (today's behavior).\n\t\tconst issuedAt = dbContext.providers.now()\n\t\tconst maxExpiresAt = policy.tokenExpiration\n\t\t\t? new Date(issuedAt.getTime() + intervalToSeconds(policy.tokenExpiration) * 1000)\n\t\t\t: null\n\n\t\tconst command = new CreateApiKeyCommand({\n\t\t\ttype: ApiKey.Type.SESSION,\n\t\t\tidentityId,\n\t\t\texpiration: expirationCapped,\n\t\t\trequestInfo,\n\t\t\ttrustForwardedInfo,\n\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\tmaxExpiresAt,\n\t\t})\n\t\tconst { id, token } = await dbContext.commandBus.execute(command)\n\t\tassert(token !== undefined)\n\n\t\t// A19: audit only when a policy is actually in effect. With zero auth_policy\n\t\t// rows the resolved policy is inert and no extra insert happens.\n\t\tconst policyApplied = policy.mfaRequired === true\n\t\t\t|| policy.tokenExpiration !== null\n\t\t\t|| policy.idleTimeout !== null\n\t\t\t|| policy.rememberMeAllowed !== null\n\t\tif (policyApplied) {\n\t\t\ttry {\n\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\ttype: 'session_policy_applied',\n\t\t\t\t\tidentityId,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\teventData: {\n\t\t\t\t\t\ttokenExpiration: policy.tokenExpiration ? intervalToPostgres(policy.tokenExpiration) : null,\n\t\t\t\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\t\t\t\trememberMeAllowed: policy.rememberMeAllowed,\n\t\t\t\t\t\tmfaRequired: policy.mfaRequired,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t/* best-effort: sign-in must not break on an audit failure */\n\t\t\t}\n\t\t}\n\n\t\treturn { id, token }\n\t}\n\n\tasync findApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<ApiKeyRow | null> {\n\t\treturn await dbContext.queryHandler.fetch(\n\t\t\tnew ApiKeyByIdQuery(apiKeyId),\n\t\t)\n\t}\n\n\tasync disableOneOffApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableOneOffApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<boolean> {\n\t\treturn await dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableIdentityApiKeys(dbContext: DatabaseContext, identityId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableIdentityApiKeysCommand(identityId))\n\t}\n\n\tasync createGlobalPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tdescription: string,\n\t\troles: readonly string[],\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createPermanentApiKey(db, description, roles, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n\n\tasync createProjectPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tprojectId: string,\n\t\tmemberships: readonly Acl.Membership[],\n\t\tdescription: string,\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createProjectPermanentApiKey(db, projectId, memberships, description, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n}\n\nexport type VerifyResponse = Response<VerifyResult, VerifyErrorCode>\n\nexport class VerifyResult {\n\treadonly valid = true\n\n\tconstructor(\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly apiKeyId: string,\n\t\tpublic readonly roles: string[],\n\t\tpublic readonly personId: string | null,\n\t\tpublic readonly trustForwardedInfo: boolean = false,\n\t) {}\n}\n\nexport enum VerifyErrorCode {\n\tNOT_FOUND = 'not_found',\n\tDISABLED = 'disabled',\n\tEXPIRED = 'expired',\n\tNO_AUTH_HEADER = 'no_auth_header',\n\tINVALID_AUTH_HEADER = 'invalid_auth_header',\n}\n"],"names":["UnpersistedApiKeyManager","ResponseOk","ApiKeyByTokenQuery","ResponseError","DisableApiKeyCommand","intervalToSeconds","PROLONG_THROTTLE_MS","ProlongApiKeyCommand","ConfigurationQuery","IdentityQuery","CreateApiKeyCommand","ApiKey","intervalToPostgres","ApiKeyByIdQuery","DisableOneOffApiKeyCommand","DisableIdentityApiKeysCommand","VerifyErrorCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyBO,MAAM,cAAc;AAAA,EAC1B,YACkB,eACA,oBACA,gBACA,2BAAqD,IAAIA,yBAAAA,yBAAA,GACzD,uBAChB;AALgB,SAAA,gBAAA;AACA,SAAA,qBAAA;AACA,SAAA,iBAAA;AACA,SAAA,2BAAA;AACA,SAAA,wBAAA;AAAA,EACf;AAAA,EAEH,MAAM,iBACL,WACA,eACA,OACA,aACA,eAC0B;AAC1B,UAAM,oBAAoB,KAAK,yBAAyB,OAAO,KAAK;AACpE,QAAI,sBAAsB,MAAM;AAE/B,aAAO,IAAIC,SAAAA,WAAW,iBAAiB;AAAA,IACxC;AAEA,UAAM,YAAY,MAAM,cAAc,aAAa,MAAM,IAAIC,YAAAA,mBAAmB,KAAK,CAAC;AACtF,QAAI,cAAc,MAAM;AACvB,aAAO,IAAIC,SAAAA,cAAc,aAA2B,uBAAuB;AAAA,IAC5E;AAEA,QAAI,UAAU,gBAAgB,MAAM;AACnC,aAAO,IAAIA,SAAAA;AAAAA,QACV;AAAA,QACA,2BAA2B,UAAU,YAAY,YAAA,CAAa;AAAA,MAAA;AAAA,IAEhE;AAIA,UAAM,MAAM,UAAU,UAAU,IAAA;AAChC,QAAI,UAAU,eAAe,QAAQ,UAAU,cAAc,KAAK;AACjE,aAAO,IAAIA,SAAAA,cAAc,YAA0B,sBAAsB,UAAU,WAAW,YAAA,CAAa,EAAE;AAAA,IAC9G;AAIA,QAAI,UAAU,mBAAmB,QAAQ,UAAU,kBAAkB,KAAK;AACzE,YAAM,UAAU,WAAW,QAAQ,IAAIC,qBAAAA,qBAAqB,UAAU,EAAE,CAAC;AACzE,aAAO,IAAID,SAAAA;AAAAA,QACV;AAAA,QACA,2CAA2C,UAAU,eAAe,YAAA,CAAa;AAAA,MAAA;AAAA,IAE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c,WAA4B,UAAoC;AACnF,WAAO,MAAM,UAAU,WAAW,QAAQ,IAAIV,qBAAAA,qBAAqB,QAAQ,CAAC;AAAA,EAC7E;AAAA,EAEA,MAAM,uBAAuB,WAA4B,YAAmC;AAC3F,UAAM,UAAU,WAAW,QAAQ,IAAIW,8BAAAA,8BAA8B,UAAU,CAAC;AAAA,EACjF;AAAA,EAEA,MAAM,4BACL,WACA,aACA,OACA,WACA,oBACgC;AAChC,WAAO,MAAM,UAAU,YAAY,OAAM,OAAM;AAC9C,aAAO,MAAM,KAAK,cAAc,sBAAsB,IAAI,aAAa,OAAO,WAAW,kBAAkB;AAAA,IAC5G,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,6BACL,WACA,WACA,aACA,aACA,WACA,oBACgC;AAChC,WAAO,MAAM,UAAU,YAAY,OAAM,OAAM;AAC9C,aAAO,MAAM,KAAK,cAAc,6BAA6B,IAAI,WAAW,aAAa,aAAa,WAAW,kBAAkB;AAAA,IACpI,CAAC;AAAA,EACF;AACD;AAIO,MAAM,aAAa;AAAA,EAGzB,YACiB,YACA,UACA,OACA,UACA,qBAA8B,OAC7C;AALe,SAAA,aAAA;AACA,SAAA,WAAA;AACA,SAAA,QAAA;AACA,SAAA,WAAA;AACA,SAAA,qBAAA;AAPjB,kBAAA,MAAS,SAAQ,IAAA;AAAA,EAQd;AACJ;AAEO,IAAK,oCAAAC,qBAAL;AACNA,mBAAA,WAAA,IAAY;AACZA,mBAAA,UAAA,IAAW;AACXA,mBAAA,SAAA,IAAU;AACVA,mBAAA,gBAAA,IAAiB;AACjBA,mBAAA,qBAAA,IAAsB;AALX,SAAAA;AAAA,GAAA,mBAAA,CAAA,CAAA;;;;"}
1
+ {"version":3,"file":"ApiKeyManager.cjs","sources":["../../../../../../../packages/engine-tenant-api/src/model/service/apiKey/ApiKeyManager.ts"],"sourcesContent":["import {\n\tApiKeyRequestInfo,\n\tCreateApiKeyCommand,\n\tDisableApiKeyCommand,\n\tDisableIdentityApiKeysCommand,\n\tDisableOneOffApiKeyCommand,\n\tPROLONG_THROTTLE_MS,\n\tProlongApiKeyCommand,\n} from '../../commands/index.js'\nimport { ApiKey } from '../../type/index.js'\n\nimport { Response, ResponseError, ResponseOk } from '../../utils/Response.js'\nimport { DatabaseContext, TokenHash } from '../../utils/index.js'\nimport { ApiKeyService, CreateApiKeyResponse } from './ApiKeyService.js'\nimport assert from 'node:assert'\nimport { Acl } from '@contember/schema'\nimport { ApiKeyByIdQuery, ApiKeyByTokenQuery, ApiKeyRow, ConfigurationQuery, IdentityQuery } from '../../queries/index.js'\nimport PostgresInterval from 'postgres-interval'\nimport { Config } from '../../type/Config.js'\nimport { intervalToPostgres, intervalToSeconds } from '../../utils/interval.js'\nimport { AuthPolicyResolver } from '../AuthPolicyResolver.js'\nimport { AuthLogService } from '../AuthLogService.js'\nimport { IdpSessionRevalidator } from '../idp/IdpSessionRevalidator.js'\nimport { UnpersistedApiKeyManager } from './UnpersistedApiKeyManager.js'\n\nexport class ApiKeyManager {\n\tconstructor(\n\t\tprivate readonly apiKeyService: ApiKeyService,\n\t\tprivate readonly authPolicyResolver: AuthPolicyResolver,\n\t\tprivate readonly authLogService: AuthLogService,\n\t\tprivate readonly unpersistedApiKeyManager: UnpersistedApiKeyManager = new UnpersistedApiKeyManager(),\n\t\tprivate readonly idpSessionRevalidator?: IdpSessionRevalidator,\n\t) {}\n\n\tasync verifyAndProlong(\n\t\tdbContext: DatabaseContext,\n\t\treadDbContext: DatabaseContext,\n\t\ttoken: string,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\tforwardedInfo?: ApiKeyRequestInfo,\n\t): Promise<VerifyResponse> {\n\t\tconst unpersistedResult = this.unpersistedApiKeyManager.verify(token)\n\t\tif (unpersistedResult !== null) {\n\t\t\t// Configured (unpersisted) root token: no DB row to prolong/track.\n\t\t\treturn new ResponseOk(unpersistedResult)\n\t\t}\n\n\t\tconst fetchedApiKey = await this.fetchApiKeyByToken(dbContext, readDbContext, token)\n\t\tif (fetchedApiKey === null) {\n\t\t\treturn new ResponseError(VerifyErrorCode.NOT_FOUND, 'API key was not found')\n\t\t}\n\t\tconst apiKeyRow = fetchedApiKey.row\n\n\t\tif (apiKeyRow.disabled_at !== null) {\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key was disabled at ${apiKeyRow.disabled_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// Single injectable clock for all session-policy time math (matches issuance,\n\t\t// which uses providers.now()), so the A19 idle/max logic is deterministically testable.\n\t\tconst now = dbContext.providers.now()\n\t\tif (apiKeyRow.expires_at !== null && apiKeyRow.expires_at <= now) {\n\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, `API key expired at ${apiKeyRow.expires_at.toISOString()}`)\n\t\t}\n\n\t\t// A19: absolute hard cap (defensive — the prolong clamp should already keep\n\t\t// expires_at <= max_expires_at, but enforce it here regardless).\n\t\tif (apiKeyRow.max_expires_at !== null && apiKeyRow.max_expires_at <= now) {\n\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key reached its maximum lifetime at ${apiKeyRow.max_expires_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// A19: idle timeout. Reject + disable when the session has been idle longer\n\t\t// than the policy's idle_timeout. A null idle_timeout (today's default) or a\n\t\t// never-used key (last_used_at null) are never idle-expired.\n\t\tif (apiKeyRow.idle_timeout !== null && apiKeyRow.last_used_at !== null) {\n\t\t\tconst idleMs = intervalToSeconds(apiKeyRow.idle_timeout) * 1000\n\t\t\t// last_used_at is written at most once per PROLONG_THROTTLE_MS (tracking is\n\t\t\t// throttled), so it can legitimately lag a continuously-active session by up\n\t\t\t// to that window. Add the throttle as slack so a small idle_timeout can't\n\t\t\t// idle-expire a session that is actually in use.\n\t\t\tif (now.getTime() - apiKeyRow.last_used_at.getTime() > idleMs + PROLONG_THROTTLE_MS) {\n\t\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\t\ttry {\n\t\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\t\ttype: 'session_expired_idle',\n\t\t\t\t\t\tidentityId: apiKeyRow.identity_id,\n\t\t\t\t\t\tpersonId: apiKeyRow.person_id,\n\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\teventData: {\n\t\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at?.toISOString() ?? null,\n\t\t\t\t\t\t\tidleTimeout: String(apiKeyRow.idle_timeout),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort: auth path must stay resilient */\n\t\t\t\t}\n\t\t\t\treturn new ResponseError(\n\t\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t\t`API key was idle since ${apiKeyRow.last_used_at.toISOString()} and exceeded the idle timeout`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst effectiveInfo: ApiKeyRequestInfo | undefined = apiKeyRow.trust_forwarded_info && forwardedInfo\n\t\t\t? {\n\t\t\t\tip: forwardedInfo.ip ?? requestInfo?.ip,\n\t\t\t\tuserAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent,\n\t\t\t}\n\t\t\t: requestInfo\n\n\t\t// Re-validate IdP-backed sessions against their identity provider (A24). In the\n\t\t// default `background` mode this returns immediately and revalidates after the\n\t\t// response (revocation lands on the next request); in `blocking` mode it can revoke\n\t\t// the current request. No-op for password sessions and IdPs without revalidation.\n\t\t// `effectiveInfo` is passed so the audit entries record the originating request's IP/UA.\n\t\t// The idp_session row is written together with the api_key, so it is read from where the key was found.\n\t\tif (this.idpSessionRevalidator) {\n\t\t\tconst outcome = await this.idpSessionRevalidator.revalidate(dbContext, fetchedApiKey.sourceDbContext, apiKeyRow, effectiveInfo)\n\t\t\tif (outcome === 'revoked') {\n\t\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, 'IdP session was revoked')\n\t\t\t}\n\t\t}\n\n\t\t// Detached (runs after the response), so a rejection here would be an unhandledRejection and can take the\n\t\t// worker down. Tracking is best-effort — the next request writes it again.\n\t\tsetImmediate(() => {\n\t\t\tdbContext.commandBus.execute(\n\t\t\t\tnew ProlongApiKeyCommand(\n\t\t\t\t\tapiKeyRow.id,\n\t\t\t\t\tapiKeyRow.type,\n\t\t\t\t\tapiKeyRow.expiration,\n\t\t\t\t\tapiKeyRow.expires_at,\n\t\t\t\t\teffectiveInfo,\n\t\t\t\t\t{\n\t\t\t\t\t\tlastIp: apiKeyRow.last_ip,\n\t\t\t\t\t\tlastUserAgent: apiKeyRow.last_user_agent,\n\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at,\n\t\t\t\t\t},\n\t\t\t\t\tapiKeyRow.max_expires_at,\n\t\t\t\t),\n\t\t\t).catch(() => {})\n\t\t})\n\n\t\treturn new ResponseOk(\n\t\t\tnew VerifyResult(\n\t\t\t\tapiKeyRow.identity_id,\n\t\t\t\tapiKeyRow.id,\n\t\t\t\tapiKeyRow.roles,\n\t\t\t\tapiKeyRow.person_id,\n\t\t\t\tapiKeyRow.trust_forwarded_info,\n\t\t\t),\n\t\t)\n\t}\n\n\tprivate async fetchApiKeyByToken(dbContext: DatabaseContext, readDbContext: DatabaseContext, token: string): Promise<FetchedApiKey | null> {\n\t\tconst query = new ApiKeyByTokenQuery(token)\n\t\tconst replicaRow = await readDbContext.queryHandler.fetch(query)\n\t\tif (replicaRow !== null) {\n\t\t\treturn { row: replicaRow, sourceDbContext: readDbContext }\n\t\t}\n\t\tif (readDbContext.client.connection === dbContext.client.connection) {\n\t\t\treturn null\n\t\t}\n\t\t// A token issued moments ago (sign-in, createSessionToken) may not have reached the read replica yet.\n\t\tconst primaryRow = await dbContext.queryHandler.fetch(query)\n\t\treturn primaryRow !== null ? { row: primaryRow, sourceDbContext: dbContext } : null\n\t}\n\n\tasync createSessionApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<string> {\n\t\tconst { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo)\n\t\treturn token\n\t}\n\n\t/**\n\t * Like {@link createSessionApiKey} but also returns the api_key id — needed when the\n\t * caller has to bind another row to the session (e.g. an `idp_session` for IdP\n\t * re-validation).\n\t */\n\tasync createSessionApiKeyWithId(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<{ id: string; token: string }> {\n\t\tconst config = await dbContext.queryHandler.fetch(new ConfigurationQuery(dbContext.providers))\n\n\t\t// A19: snapshot the effective session policy onto the api_key at sign-in.\n\t\t// With no matching policy, every field is null/baseline and the result is\n\t\t// byte-for-byte today's behavior.\n\t\tconst [identityRow] = await dbContext.queryHandler.fetch(new IdentityQuery([identityId]))\n\t\tconst globalRoles = identityRow?.roles ?? []\n\t\tconst policy = await this.authPolicyResolver.resolveForIdentity(dbContext, identityId, globalRoles)\n\n\t\tconst defaultExpirationMinutes = intervalToSeconds(config.login.defaultTokenExpiration) / 60\n\t\t// remember_me_allowed === false: ignore a client-supplied longer lifetime and\n\t\t// force the default. (true/null leave the requested expiration untouched.)\n\t\tconst requestedMinutes = policy.rememberMeAllowed === false\n\t\t\t? defaultExpirationMinutes\n\t\t\t: (expiration ?? defaultExpirationMinutes)\n\n\t\t// Cap by maxTokenExpiration (existing behavior) AND by the policy's\n\t\t// tokenExpiration (A19) — strictest wins.\n\t\tlet expirationCapped = config.login.maxTokenExpiration\n\t\t\t? Math.min(requestedMinutes, intervalToSeconds(config.login.maxTokenExpiration) / 60)\n\t\t\t: requestedMinutes\n\t\tif (policy.tokenExpiration) {\n\t\t\texpirationCapped = Math.min(expirationCapped, intervalToSeconds(policy.tokenExpiration) / 60)\n\t\t}\n\n\t\t// Absolute hard cap: issued_at + policy.tokenExpiration. NULL = uncapped\n\t\t// sliding window (today's behavior).\n\t\tconst issuedAt = dbContext.providers.now()\n\t\tconst maxExpiresAt = policy.tokenExpiration\n\t\t\t? new Date(issuedAt.getTime() + intervalToSeconds(policy.tokenExpiration) * 1000)\n\t\t\t: null\n\n\t\tconst command = new CreateApiKeyCommand({\n\t\t\ttype: ApiKey.Type.SESSION,\n\t\t\tidentityId,\n\t\t\texpiration: expirationCapped,\n\t\t\trequestInfo,\n\t\t\ttrustForwardedInfo,\n\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\tmaxExpiresAt,\n\t\t})\n\t\tconst { id, token } = await dbContext.commandBus.execute(command)\n\t\tassert(token !== undefined)\n\n\t\t// A19: audit only when a policy is actually in effect. With zero auth_policy\n\t\t// rows the resolved policy is inert and no extra insert happens.\n\t\tconst policyApplied = policy.mfaRequired === true\n\t\t\t|| policy.tokenExpiration !== null\n\t\t\t|| policy.idleTimeout !== null\n\t\t\t|| policy.rememberMeAllowed !== null\n\t\tif (policyApplied) {\n\t\t\ttry {\n\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\ttype: 'session_policy_applied',\n\t\t\t\t\tidentityId,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\teventData: {\n\t\t\t\t\t\ttokenExpiration: policy.tokenExpiration ? intervalToPostgres(policy.tokenExpiration) : null,\n\t\t\t\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\t\t\t\trememberMeAllowed: policy.rememberMeAllowed,\n\t\t\t\t\t\tmfaRequired: policy.mfaRequired,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t/* best-effort: sign-in must not break on an audit failure */\n\t\t\t}\n\t\t}\n\n\t\treturn { id, token }\n\t}\n\n\tasync findApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<ApiKeyRow | null> {\n\t\treturn await dbContext.queryHandler.fetch(\n\t\t\tnew ApiKeyByIdQuery(apiKeyId),\n\t\t)\n\t}\n\n\tasync disableOneOffApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableOneOffApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<boolean> {\n\t\treturn await dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableIdentityApiKeys(dbContext: DatabaseContext, identityId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableIdentityApiKeysCommand(identityId))\n\t}\n\n\tasync createGlobalPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tdescription: string,\n\t\troles: readonly string[],\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createPermanentApiKey(db, description, roles, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n\n\tasync createProjectPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tprojectId: string,\n\t\tmemberships: readonly Acl.Membership[],\n\t\tdescription: string,\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createProjectPermanentApiKey(db, projectId, memberships, description, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n}\n\ntype FetchedApiKey = {\n\trow: ApiKeyRow\n\tsourceDbContext: DatabaseContext\n}\n\nexport type VerifyResponse = Response<VerifyResult, VerifyErrorCode>\n\nexport class VerifyResult {\n\treadonly valid = true\n\n\tconstructor(\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly apiKeyId: string,\n\t\tpublic readonly roles: string[],\n\t\tpublic readonly personId: string | null,\n\t\tpublic readonly trustForwardedInfo: boolean = false,\n\t) {}\n}\n\nexport enum VerifyErrorCode {\n\tNOT_FOUND = 'not_found',\n\tDISABLED = 'disabled',\n\tEXPIRED = 'expired',\n\tNO_AUTH_HEADER = 'no_auth_header',\n\tINVALID_AUTH_HEADER = 'invalid_auth_header',\n}\n"],"names":["UnpersistedApiKeyManager","ResponseOk","ResponseError","DisableApiKeyCommand","intervalToSeconds","PROLONG_THROTTLE_MS","ProlongApiKeyCommand","ApiKeyByTokenQuery","ConfigurationQuery","IdentityQuery","CreateApiKeyCommand","ApiKey","intervalToPostgres","ApiKeyByIdQuery","DisableOneOffApiKeyCommand","DisableIdentityApiKeysCommand","VerifyErrorCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyBO,MAAM,cAAc;AAAA,EAC1B,YACkB,eACA,oBACA,gBACA,2BAAqD,IAAIA,yBAAAA,yBAAA,GACzD,uBAChB;AALgB,SAAA,gBAAA;AACA,SAAA,qBAAA;AACA,SAAA,iBAAA;AACA,SAAA,2BAAA;AACA,SAAA,wBAAA;AAAA,EACf;AAAA,EAEH,MAAM,iBACL,WACA,eACA,OACA,aACA,eAC0B;AAC1B,UAAM,oBAAoB,KAAK,yBAAyB,OAAO,KAAK;AACpE,QAAI,sBAAsB,MAAM;AAE/B,aAAO,IAAIC,SAAAA,WAAW,iBAAiB;AAAA,IACxC;AAEA,UAAM,gBAAgB,MAAM,KAAK,mBAAmB,WAAW,eAAe,KAAK;AACnF,QAAI,kBAAkB,MAAM;AAC3B,aAAO,IAAIC,SAAAA,cAAc,aAA2B,uBAAuB;AAAA,IAC5E;AACA,UAAM,YAAY,cAAc;AAEhC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ACA,oBACgC;AAChC,WAAO,MAAM,UAAU,YAAY,OAAM,OAAM;AAC9C,aAAO,MAAM,KAAK,cAAc,sBAAsB,IAAI,aAAa,OAAO,WAAW,kBAAkB;AAAA,IAC5G,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,6BACL,WACA,WACA,aACA,aACA,WACA,oBACgC;AAChC,WAAO,MAAM,UAAU,YAAY,OAAM,OAAM;AAC9C,aAAO,MAAM,KAAK,cAAc,6BAA6B,IAAI,WAAW,aAAa,aAAa,WAAW,kBAAkB;AAAA,IACpI,CAAC;AAAA,EACF;AACD;AASO,MAAM,aAAa;AAAA,EAGzB,YACiB,YACA,UACA,OACA,UACA,qBAA8B,OAC7C;AALe,SAAA,aAAA;AACA,SAAA,WAAA;AACA,SAAA,QAAA;AACA,SAAA,WAAA;AACA,SAAA,qBAAA;AAPjB,kBAAA,MAAS,SAAQ,IAAA;AAAA,EAQd;AACJ;AAEO,IAAK,oCAAAC,qBAAL;AACNA,mBAAA,WAAA,IAAY;AACZA,mBAAA,UAAA,IAAW;AACXA,mBAAA,SAAA,IAAU;AACVA,mBAAA,gBAAA,IAAiB;AACjBA,mBAAA,qBAAA,IAAsB;AALX,SAAAA;AAAA,GAAA,mBAAA,CAAA,CAAA;;;;"}
@@ -34,10 +34,11 @@ class ApiKeyManager {
34
34
  if (unpersistedResult !== null) {
35
35
  return new ResponseOk(unpersistedResult);
36
36
  }
37
- const apiKeyRow = await readDbContext.queryHandler.fetch(new ApiKeyByTokenQuery(token));
38
- if (apiKeyRow === null) {
37
+ const fetchedApiKey = await this.fetchApiKeyByToken(dbContext, readDbContext, token);
38
+ if (fetchedApiKey === null) {
39
39
  return new ResponseError("not_found", "API key was not found");
40
40
  }
41
+ const apiKeyRow = fetchedApiKey.row;
41
42
  if (apiKeyRow.disabled_at !== null) {
42
43
  return new ResponseError(
43
44
  "disabled",
@@ -85,7 +86,7 @@ class ApiKeyManager {
85
86
  userAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent
86
87
  } : requestInfo;
87
88
  if (this.idpSessionRevalidator) {
88
- const outcome = await this.idpSessionRevalidator.revalidate(dbContext, readDbContext, apiKeyRow, effectiveInfo);
89
+ const outcome = await this.idpSessionRevalidator.revalidate(dbContext, fetchedApiKey.sourceDbContext, apiKeyRow, effectiveInfo);
89
90
  if (outcome === "revoked") {
90
91
  return new ResponseError("disabled", "IdP session was revoked");
91
92
  }
@@ -118,6 +119,18 @@ class ApiKeyManager {
118
119
  )
119
120
  );
120
121
  }
122
+ async fetchApiKeyByToken(dbContext, readDbContext, token) {
123
+ const query = new ApiKeyByTokenQuery(token);
124
+ const replicaRow = await readDbContext.queryHandler.fetch(query);
125
+ if (replicaRow !== null) {
126
+ return { row: replicaRow, sourceDbContext: readDbContext };
127
+ }
128
+ if (readDbContext.client.connection === dbContext.client.connection) {
129
+ return null;
130
+ }
131
+ const primaryRow = await dbContext.queryHandler.fetch(query);
132
+ return primaryRow !== null ? { row: primaryRow, sourceDbContext: dbContext } : null;
133
+ }
121
134
  async createSessionApiKey(dbContext, identityId, expiration, requestInfo, trustForwardedInfo) {
122
135
  const { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo);
123
136
  return token;
@@ -1 +1 @@
1
- {"version":3,"file":"ApiKeyManager.js","sources":["../../../../../../../packages/engine-tenant-api/src/model/service/apiKey/ApiKeyManager.ts"],"sourcesContent":["import {\n\tApiKeyRequestInfo,\n\tCreateApiKeyCommand,\n\tDisableApiKeyCommand,\n\tDisableIdentityApiKeysCommand,\n\tDisableOneOffApiKeyCommand,\n\tPROLONG_THROTTLE_MS,\n\tProlongApiKeyCommand,\n} from '../../commands/index.js'\nimport { ApiKey } from '../../type/index.js'\n\nimport { Response, ResponseError, ResponseOk } from '../../utils/Response.js'\nimport { DatabaseContext, TokenHash } from '../../utils/index.js'\nimport { ApiKeyService, CreateApiKeyResponse } from './ApiKeyService.js'\nimport assert from 'node:assert'\nimport { Acl } from '@contember/schema'\nimport { ApiKeyByIdQuery, ApiKeyByTokenQuery, ApiKeyRow, ConfigurationQuery, IdentityQuery } from '../../queries/index.js'\nimport PostgresInterval from 'postgres-interval'\nimport { Config } from '../../type/Config.js'\nimport { intervalToPostgres, intervalToSeconds } from '../../utils/interval.js'\nimport { AuthPolicyResolver } from '../AuthPolicyResolver.js'\nimport { AuthLogService } from '../AuthLogService.js'\nimport { IdpSessionRevalidator } from '../idp/IdpSessionRevalidator.js'\nimport { UnpersistedApiKeyManager } from './UnpersistedApiKeyManager.js'\n\nexport class ApiKeyManager {\n\tconstructor(\n\t\tprivate readonly apiKeyService: ApiKeyService,\n\t\tprivate readonly authPolicyResolver: AuthPolicyResolver,\n\t\tprivate readonly authLogService: AuthLogService,\n\t\tprivate readonly unpersistedApiKeyManager: UnpersistedApiKeyManager = new UnpersistedApiKeyManager(),\n\t\tprivate readonly idpSessionRevalidator?: IdpSessionRevalidator,\n\t) {}\n\n\tasync verifyAndProlong(\n\t\tdbContext: DatabaseContext,\n\t\treadDbContext: DatabaseContext,\n\t\ttoken: string,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\tforwardedInfo?: ApiKeyRequestInfo,\n\t): Promise<VerifyResponse> {\n\t\tconst unpersistedResult = this.unpersistedApiKeyManager.verify(token)\n\t\tif (unpersistedResult !== null) {\n\t\t\t// Configured (unpersisted) root token: no DB row to prolong/track.\n\t\t\treturn new ResponseOk(unpersistedResult)\n\t\t}\n\n\t\tconst apiKeyRow = await readDbContext.queryHandler.fetch(new ApiKeyByTokenQuery(token))\n\t\tif (apiKeyRow === null) {\n\t\t\treturn new ResponseError(VerifyErrorCode.NOT_FOUND, 'API key was not found')\n\t\t}\n\n\t\tif (apiKeyRow.disabled_at !== null) {\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key was disabled at ${apiKeyRow.disabled_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// Single injectable clock for all session-policy time math (matches issuance,\n\t\t// which uses providers.now()), so the A19 idle/max logic is deterministically testable.\n\t\tconst now = dbContext.providers.now()\n\t\tif (apiKeyRow.expires_at !== null && apiKeyRow.expires_at <= now) {\n\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, `API key expired at ${apiKeyRow.expires_at.toISOString()}`)\n\t\t}\n\n\t\t// A19: absolute hard cap (defensive — the prolong clamp should already keep\n\t\t// expires_at <= max_expires_at, but enforce it here regardless).\n\t\tif (apiKeyRow.max_expires_at !== null && apiKeyRow.max_expires_at <= now) {\n\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key reached its maximum lifetime at ${apiKeyRow.max_expires_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// A19: idle timeout. Reject + disable when the session has been idle longer\n\t\t// than the policy's idle_timeout. A null idle_timeout (today's default) or a\n\t\t// never-used key (last_used_at null) are never idle-expired.\n\t\tif (apiKeyRow.idle_timeout !== null && apiKeyRow.last_used_at !== null) {\n\t\t\tconst idleMs = intervalToSeconds(apiKeyRow.idle_timeout) * 1000\n\t\t\t// last_used_at is written at most once per PROLONG_THROTTLE_MS (tracking is\n\t\t\t// throttled), so it can legitimately lag a continuously-active session by up\n\t\t\t// to that window. Add the throttle as slack so a small idle_timeout can't\n\t\t\t// idle-expire a session that is actually in use.\n\t\t\tif (now.getTime() - apiKeyRow.last_used_at.getTime() > idleMs + PROLONG_THROTTLE_MS) {\n\t\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\t\ttry {\n\t\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\t\ttype: 'session_expired_idle',\n\t\t\t\t\t\tidentityId: apiKeyRow.identity_id,\n\t\t\t\t\t\tpersonId: apiKeyRow.person_id,\n\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\teventData: {\n\t\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at?.toISOString() ?? null,\n\t\t\t\t\t\t\tidleTimeout: String(apiKeyRow.idle_timeout),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort: auth path must stay resilient */\n\t\t\t\t}\n\t\t\t\treturn new ResponseError(\n\t\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t\t`API key was idle since ${apiKeyRow.last_used_at.toISOString()} and exceeded the idle timeout`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst effectiveInfo: ApiKeyRequestInfo | undefined = apiKeyRow.trust_forwarded_info && forwardedInfo\n\t\t\t? {\n\t\t\t\tip: forwardedInfo.ip ?? requestInfo?.ip,\n\t\t\t\tuserAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent,\n\t\t\t}\n\t\t\t: requestInfo\n\n\t\t// Re-validate IdP-backed sessions against their identity provider (A24). In the\n\t\t// default `background` mode this returns immediately and revalidates after the\n\t\t// response (revocation lands on the next request); in `blocking` mode it can revoke\n\t\t// the current request. No-op for password sessions and IdPs without revalidation.\n\t\t// `effectiveInfo` is passed so the audit entries record the originating request's IP/UA.\n\t\tif (this.idpSessionRevalidator) {\n\t\t\tconst outcome = await this.idpSessionRevalidator.revalidate(dbContext, readDbContext, apiKeyRow, effectiveInfo)\n\t\t\tif (outcome === 'revoked') {\n\t\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, 'IdP session was revoked')\n\t\t\t}\n\t\t}\n\n\t\t// Detached (runs after the response), so a rejection here would be an unhandledRejection and can take the\n\t\t// worker down. Tracking is best-effort — the next request writes it again.\n\t\tsetImmediate(() => {\n\t\t\tdbContext.commandBus.execute(\n\t\t\t\tnew ProlongApiKeyCommand(\n\t\t\t\t\tapiKeyRow.id,\n\t\t\t\t\tapiKeyRow.type,\n\t\t\t\t\tapiKeyRow.expiration,\n\t\t\t\t\tapiKeyRow.expires_at,\n\t\t\t\t\teffectiveInfo,\n\t\t\t\t\t{\n\t\t\t\t\t\tlastIp: apiKeyRow.last_ip,\n\t\t\t\t\t\tlastUserAgent: apiKeyRow.last_user_agent,\n\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at,\n\t\t\t\t\t},\n\t\t\t\t\tapiKeyRow.max_expires_at,\n\t\t\t\t),\n\t\t\t).catch(() => {})\n\t\t})\n\n\t\treturn new ResponseOk(\n\t\t\tnew VerifyResult(\n\t\t\t\tapiKeyRow.identity_id,\n\t\t\t\tapiKeyRow.id,\n\t\t\t\tapiKeyRow.roles,\n\t\t\t\tapiKeyRow.person_id,\n\t\t\t\tapiKeyRow.trust_forwarded_info,\n\t\t\t),\n\t\t)\n\t}\n\n\tasync createSessionApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<string> {\n\t\tconst { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo)\n\t\treturn token\n\t}\n\n\t/**\n\t * Like {@link createSessionApiKey} but also returns the api_key id — needed when the\n\t * caller has to bind another row to the session (e.g. an `idp_session` for IdP\n\t * re-validation).\n\t */\n\tasync createSessionApiKeyWithId(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<{ id: string; token: string }> {\n\t\tconst config = await dbContext.queryHandler.fetch(new ConfigurationQuery(dbContext.providers))\n\n\t\t// A19: snapshot the effective session policy onto the api_key at sign-in.\n\t\t// With no matching policy, every field is null/baseline and the result is\n\t\t// byte-for-byte today's behavior.\n\t\tconst [identityRow] = await dbContext.queryHandler.fetch(new IdentityQuery([identityId]))\n\t\tconst globalRoles = identityRow?.roles ?? []\n\t\tconst policy = await this.authPolicyResolver.resolveForIdentity(dbContext, identityId, globalRoles)\n\n\t\tconst defaultExpirationMinutes = intervalToSeconds(config.login.defaultTokenExpiration) / 60\n\t\t// remember_me_allowed === false: ignore a client-supplied longer lifetime and\n\t\t// force the default. (true/null leave the requested expiration untouched.)\n\t\tconst requestedMinutes = policy.rememberMeAllowed === false\n\t\t\t? defaultExpirationMinutes\n\t\t\t: (expiration ?? defaultExpirationMinutes)\n\n\t\t// Cap by maxTokenExpiration (existing behavior) AND by the policy's\n\t\t// tokenExpiration (A19) — strictest wins.\n\t\tlet expirationCapped = config.login.maxTokenExpiration\n\t\t\t? Math.min(requestedMinutes, intervalToSeconds(config.login.maxTokenExpiration) / 60)\n\t\t\t: requestedMinutes\n\t\tif (policy.tokenExpiration) {\n\t\t\texpirationCapped = Math.min(expirationCapped, intervalToSeconds(policy.tokenExpiration) / 60)\n\t\t}\n\n\t\t// Absolute hard cap: issued_at + policy.tokenExpiration. NULL = uncapped\n\t\t// sliding window (today's behavior).\n\t\tconst issuedAt = dbContext.providers.now()\n\t\tconst maxExpiresAt = policy.tokenExpiration\n\t\t\t? new Date(issuedAt.getTime() + intervalToSeconds(policy.tokenExpiration) * 1000)\n\t\t\t: null\n\n\t\tconst command = new CreateApiKeyCommand({\n\t\t\ttype: ApiKey.Type.SESSION,\n\t\t\tidentityId,\n\t\t\texpiration: expirationCapped,\n\t\t\trequestInfo,\n\t\t\ttrustForwardedInfo,\n\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\tmaxExpiresAt,\n\t\t})\n\t\tconst { id, token } = await dbContext.commandBus.execute(command)\n\t\tassert(token !== undefined)\n\n\t\t// A19: audit only when a policy is actually in effect. With zero auth_policy\n\t\t// rows the resolved policy is inert and no extra insert happens.\n\t\tconst policyApplied = policy.mfaRequired === true\n\t\t\t|| policy.tokenExpiration !== null\n\t\t\t|| policy.idleTimeout !== null\n\t\t\t|| policy.rememberMeAllowed !== null\n\t\tif (policyApplied) {\n\t\t\ttry {\n\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\ttype: 'session_policy_applied',\n\t\t\t\t\tidentityId,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\teventData: {\n\t\t\t\t\t\ttokenExpiration: policy.tokenExpiration ? intervalToPostgres(policy.tokenExpiration) : null,\n\t\t\t\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\t\t\t\trememberMeAllowed: policy.rememberMeAllowed,\n\t\t\t\t\t\tmfaRequired: policy.mfaRequired,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t/* best-effort: sign-in must not break on an audit failure */\n\t\t\t}\n\t\t}\n\n\t\treturn { id, token }\n\t}\n\n\tasync findApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<ApiKeyRow | null> {\n\t\treturn await dbContext.queryHandler.fetch(\n\t\t\tnew ApiKeyByIdQuery(apiKeyId),\n\t\t)\n\t}\n\n\tasync disableOneOffApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableOneOffApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<boolean> {\n\t\treturn await dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableIdentityApiKeys(dbContext: DatabaseContext, identityId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableIdentityApiKeysCommand(identityId))\n\t}\n\n\tasync createGlobalPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tdescription: string,\n\t\troles: readonly string[],\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createPermanentApiKey(db, description, roles, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n\n\tasync createProjectPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tprojectId: string,\n\t\tmemberships: readonly Acl.Membership[],\n\t\tdescription: string,\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createProjectPermanentApiKey(db, projectId, memberships, description, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n}\n\nexport type VerifyResponse = Response<VerifyResult, VerifyErrorCode>\n\nexport class VerifyResult {\n\treadonly valid = true\n\n\tconstructor(\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly apiKeyId: string,\n\t\tpublic readonly roles: string[],\n\t\tpublic readonly personId: string | null,\n\t\tpublic readonly trustForwardedInfo: boolean = false,\n\t) {}\n}\n\nexport enum VerifyErrorCode {\n\tNOT_FOUND = 'not_found',\n\tDISABLED = 'disabled',\n\tEXPIRED = 'expired',\n\tNO_AUTH_HEADER = 'no_auth_header',\n\tINVALID_AUTH_HEADER = 'invalid_auth_header',\n}\n"],"names":["VerifyErrorCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyBO,MAAM,cAAc;AAAA,EAC1B,YACkB,eACA,oBACA,gBACA,2BAAqD,IAAI,yBAAA,GACzD,uBAChB;AALgB,SAAA,gBAAA;AACA,SAAA,qBAAA;AACA,SAAA,iBAAA;AACA,SAAA,2BAAA;AACA,SAAA,wBAAA;AAAA,EACf;AAAA,EAEH,MAAM,iBACL,WACA,eACA,OACA,aACA,eAC0B;AAC1B,UAAM,oBAAoB,KAAK,yBAAyB,OAAO,KAAK;AACpE,QAAI,sBAAsB,MAAM;AAE/B,aAAO,IAAI,WAAW,iBAAiB;AAAA,IACxC;AAEA,UAAM,YAAY,MAAM,cAAc,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AA;AAPjB,kBAAA,MAAS,SAAQ,IAAA;AAAA,EAQd;AACJ;AAEO,IAAK,oCAAAA,qBAAL;AACNA,mBAAA,WAAA,IAAY;AACZA,mBAAA,UAAA,IAAW;AACXA,mBAAA,SAAA,IAAU;AACVA,mBAAA,gBAAA,IAAiB;AACjBA,mBAAA,qBAAA,IAAsB;AALX,SAAAA;AAAA,GAAA,mBAAA,CAAA,CAAA;"}
1
+ {"version":3,"file":"ApiKeyManager.js","sources":["../../../../../../../packages/engine-tenant-api/src/model/service/apiKey/ApiKeyManager.ts"],"sourcesContent":["import {\n\tApiKeyRequestInfo,\n\tCreateApiKeyCommand,\n\tDisableApiKeyCommand,\n\tDisableIdentityApiKeysCommand,\n\tDisableOneOffApiKeyCommand,\n\tPROLONG_THROTTLE_MS,\n\tProlongApiKeyCommand,\n} from '../../commands/index.js'\nimport { ApiKey } from '../../type/index.js'\n\nimport { Response, ResponseError, ResponseOk } from '../../utils/Response.js'\nimport { DatabaseContext, TokenHash } from '../../utils/index.js'\nimport { ApiKeyService, CreateApiKeyResponse } from './ApiKeyService.js'\nimport assert from 'node:assert'\nimport { Acl } from '@contember/schema'\nimport { ApiKeyByIdQuery, ApiKeyByTokenQuery, ApiKeyRow, ConfigurationQuery, IdentityQuery } from '../../queries/index.js'\nimport PostgresInterval from 'postgres-interval'\nimport { Config } from '../../type/Config.js'\nimport { intervalToPostgres, intervalToSeconds } from '../../utils/interval.js'\nimport { AuthPolicyResolver } from '../AuthPolicyResolver.js'\nimport { AuthLogService } from '../AuthLogService.js'\nimport { IdpSessionRevalidator } from '../idp/IdpSessionRevalidator.js'\nimport { UnpersistedApiKeyManager } from './UnpersistedApiKeyManager.js'\n\nexport class ApiKeyManager {\n\tconstructor(\n\t\tprivate readonly apiKeyService: ApiKeyService,\n\t\tprivate readonly authPolicyResolver: AuthPolicyResolver,\n\t\tprivate readonly authLogService: AuthLogService,\n\t\tprivate readonly unpersistedApiKeyManager: UnpersistedApiKeyManager = new UnpersistedApiKeyManager(),\n\t\tprivate readonly idpSessionRevalidator?: IdpSessionRevalidator,\n\t) {}\n\n\tasync verifyAndProlong(\n\t\tdbContext: DatabaseContext,\n\t\treadDbContext: DatabaseContext,\n\t\ttoken: string,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\tforwardedInfo?: ApiKeyRequestInfo,\n\t): Promise<VerifyResponse> {\n\t\tconst unpersistedResult = this.unpersistedApiKeyManager.verify(token)\n\t\tif (unpersistedResult !== null) {\n\t\t\t// Configured (unpersisted) root token: no DB row to prolong/track.\n\t\t\treturn new ResponseOk(unpersistedResult)\n\t\t}\n\n\t\tconst fetchedApiKey = await this.fetchApiKeyByToken(dbContext, readDbContext, token)\n\t\tif (fetchedApiKey === null) {\n\t\t\treturn new ResponseError(VerifyErrorCode.NOT_FOUND, 'API key was not found')\n\t\t}\n\t\tconst apiKeyRow = fetchedApiKey.row\n\n\t\tif (apiKeyRow.disabled_at !== null) {\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key was disabled at ${apiKeyRow.disabled_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// Single injectable clock for all session-policy time math (matches issuance,\n\t\t// which uses providers.now()), so the A19 idle/max logic is deterministically testable.\n\t\tconst now = dbContext.providers.now()\n\t\tif (apiKeyRow.expires_at !== null && apiKeyRow.expires_at <= now) {\n\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, `API key expired at ${apiKeyRow.expires_at.toISOString()}`)\n\t\t}\n\n\t\t// A19: absolute hard cap (defensive — the prolong clamp should already keep\n\t\t// expires_at <= max_expires_at, but enforce it here regardless).\n\t\tif (apiKeyRow.max_expires_at !== null && apiKeyRow.max_expires_at <= now) {\n\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\treturn new ResponseError(\n\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t`API key reached its maximum lifetime at ${apiKeyRow.max_expires_at.toISOString()}`,\n\t\t\t)\n\t\t}\n\n\t\t// A19: idle timeout. Reject + disable when the session has been idle longer\n\t\t// than the policy's idle_timeout. A null idle_timeout (today's default) or a\n\t\t// never-used key (last_used_at null) are never idle-expired.\n\t\tif (apiKeyRow.idle_timeout !== null && apiKeyRow.last_used_at !== null) {\n\t\t\tconst idleMs = intervalToSeconds(apiKeyRow.idle_timeout) * 1000\n\t\t\t// last_used_at is written at most once per PROLONG_THROTTLE_MS (tracking is\n\t\t\t// throttled), so it can legitimately lag a continuously-active session by up\n\t\t\t// to that window. Add the throttle as slack so a small idle_timeout can't\n\t\t\t// idle-expire a session that is actually in use.\n\t\t\tif (now.getTime() - apiKeyRow.last_used_at.getTime() > idleMs + PROLONG_THROTTLE_MS) {\n\t\t\t\tawait dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyRow.id))\n\t\t\t\ttry {\n\t\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\t\ttype: 'session_expired_idle',\n\t\t\t\t\t\tidentityId: apiKeyRow.identity_id,\n\t\t\t\t\t\tpersonId: apiKeyRow.person_id,\n\t\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\teventData: {\n\t\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at?.toISOString() ?? null,\n\t\t\t\t\t\t\tidleTimeout: String(apiKeyRow.idle_timeout),\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort: auth path must stay resilient */\n\t\t\t\t}\n\t\t\t\treturn new ResponseError(\n\t\t\t\t\tVerifyErrorCode.DISABLED,\n\t\t\t\t\t`API key was idle since ${apiKeyRow.last_used_at.toISOString()} and exceeded the idle timeout`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst effectiveInfo: ApiKeyRequestInfo | undefined = apiKeyRow.trust_forwarded_info && forwardedInfo\n\t\t\t? {\n\t\t\t\tip: forwardedInfo.ip ?? requestInfo?.ip,\n\t\t\t\tuserAgent: forwardedInfo.userAgent ?? requestInfo?.userAgent,\n\t\t\t}\n\t\t\t: requestInfo\n\n\t\t// Re-validate IdP-backed sessions against their identity provider (A24). In the\n\t\t// default `background` mode this returns immediately and revalidates after the\n\t\t// response (revocation lands on the next request); in `blocking` mode it can revoke\n\t\t// the current request. No-op for password sessions and IdPs without revalidation.\n\t\t// `effectiveInfo` is passed so the audit entries record the originating request's IP/UA.\n\t\t// The idp_session row is written together with the api_key, so it is read from where the key was found.\n\t\tif (this.idpSessionRevalidator) {\n\t\t\tconst outcome = await this.idpSessionRevalidator.revalidate(dbContext, fetchedApiKey.sourceDbContext, apiKeyRow, effectiveInfo)\n\t\t\tif (outcome === 'revoked') {\n\t\t\t\treturn new ResponseError(VerifyErrorCode.DISABLED, 'IdP session was revoked')\n\t\t\t}\n\t\t}\n\n\t\t// Detached (runs after the response), so a rejection here would be an unhandledRejection and can take the\n\t\t// worker down. Tracking is best-effort — the next request writes it again.\n\t\tsetImmediate(() => {\n\t\t\tdbContext.commandBus.execute(\n\t\t\t\tnew ProlongApiKeyCommand(\n\t\t\t\t\tapiKeyRow.id,\n\t\t\t\t\tapiKeyRow.type,\n\t\t\t\t\tapiKeyRow.expiration,\n\t\t\t\t\tapiKeyRow.expires_at,\n\t\t\t\t\teffectiveInfo,\n\t\t\t\t\t{\n\t\t\t\t\t\tlastIp: apiKeyRow.last_ip,\n\t\t\t\t\t\tlastUserAgent: apiKeyRow.last_user_agent,\n\t\t\t\t\t\tlastUsedAt: apiKeyRow.last_used_at,\n\t\t\t\t\t},\n\t\t\t\t\tapiKeyRow.max_expires_at,\n\t\t\t\t),\n\t\t\t).catch(() => {})\n\t\t})\n\n\t\treturn new ResponseOk(\n\t\t\tnew VerifyResult(\n\t\t\t\tapiKeyRow.identity_id,\n\t\t\t\tapiKeyRow.id,\n\t\t\t\tapiKeyRow.roles,\n\t\t\t\tapiKeyRow.person_id,\n\t\t\t\tapiKeyRow.trust_forwarded_info,\n\t\t\t),\n\t\t)\n\t}\n\n\tprivate async fetchApiKeyByToken(dbContext: DatabaseContext, readDbContext: DatabaseContext, token: string): Promise<FetchedApiKey | null> {\n\t\tconst query = new ApiKeyByTokenQuery(token)\n\t\tconst replicaRow = await readDbContext.queryHandler.fetch(query)\n\t\tif (replicaRow !== null) {\n\t\t\treturn { row: replicaRow, sourceDbContext: readDbContext }\n\t\t}\n\t\tif (readDbContext.client.connection === dbContext.client.connection) {\n\t\t\treturn null\n\t\t}\n\t\t// A token issued moments ago (sign-in, createSessionToken) may not have reached the read replica yet.\n\t\tconst primaryRow = await dbContext.queryHandler.fetch(query)\n\t\treturn primaryRow !== null ? { row: primaryRow, sourceDbContext: dbContext } : null\n\t}\n\n\tasync createSessionApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<string> {\n\t\tconst { token } = await this.createSessionApiKeyWithId(dbContext, identityId, expiration, requestInfo, trustForwardedInfo)\n\t\treturn token\n\t}\n\n\t/**\n\t * Like {@link createSessionApiKey} but also returns the api_key id — needed when the\n\t * caller has to bind another row to the session (e.g. an `idp_session` for IdP\n\t * re-validation).\n\t */\n\tasync createSessionApiKeyWithId(\n\t\tdbContext: DatabaseContext,\n\t\tidentityId: string,\n\t\texpiration?: number,\n\t\trequestInfo?: ApiKeyRequestInfo,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<{ id: string; token: string }> {\n\t\tconst config = await dbContext.queryHandler.fetch(new ConfigurationQuery(dbContext.providers))\n\n\t\t// A19: snapshot the effective session policy onto the api_key at sign-in.\n\t\t// With no matching policy, every field is null/baseline and the result is\n\t\t// byte-for-byte today's behavior.\n\t\tconst [identityRow] = await dbContext.queryHandler.fetch(new IdentityQuery([identityId]))\n\t\tconst globalRoles = identityRow?.roles ?? []\n\t\tconst policy = await this.authPolicyResolver.resolveForIdentity(dbContext, identityId, globalRoles)\n\n\t\tconst defaultExpirationMinutes = intervalToSeconds(config.login.defaultTokenExpiration) / 60\n\t\t// remember_me_allowed === false: ignore a client-supplied longer lifetime and\n\t\t// force the default. (true/null leave the requested expiration untouched.)\n\t\tconst requestedMinutes = policy.rememberMeAllowed === false\n\t\t\t? defaultExpirationMinutes\n\t\t\t: (expiration ?? defaultExpirationMinutes)\n\n\t\t// Cap by maxTokenExpiration (existing behavior) AND by the policy's\n\t\t// tokenExpiration (A19) — strictest wins.\n\t\tlet expirationCapped = config.login.maxTokenExpiration\n\t\t\t? Math.min(requestedMinutes, intervalToSeconds(config.login.maxTokenExpiration) / 60)\n\t\t\t: requestedMinutes\n\t\tif (policy.tokenExpiration) {\n\t\t\texpirationCapped = Math.min(expirationCapped, intervalToSeconds(policy.tokenExpiration) / 60)\n\t\t}\n\n\t\t// Absolute hard cap: issued_at + policy.tokenExpiration. NULL = uncapped\n\t\t// sliding window (today's behavior).\n\t\tconst issuedAt = dbContext.providers.now()\n\t\tconst maxExpiresAt = policy.tokenExpiration\n\t\t\t? new Date(issuedAt.getTime() + intervalToSeconds(policy.tokenExpiration) * 1000)\n\t\t\t: null\n\n\t\tconst command = new CreateApiKeyCommand({\n\t\t\ttype: ApiKey.Type.SESSION,\n\t\t\tidentityId,\n\t\t\texpiration: expirationCapped,\n\t\t\trequestInfo,\n\t\t\ttrustForwardedInfo,\n\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\tmaxExpiresAt,\n\t\t})\n\t\tconst { id, token } = await dbContext.commandBus.execute(command)\n\t\tassert(token !== undefined)\n\n\t\t// A19: audit only when a policy is actually in effect. With zero auth_policy\n\t\t// rows the resolved policy is inert and no extra insert happens.\n\t\tconst policyApplied = policy.mfaRequired === true\n\t\t\t|| policy.tokenExpiration !== null\n\t\t\t|| policy.idleTimeout !== null\n\t\t\t|| policy.rememberMeAllowed !== null\n\t\tif (policyApplied) {\n\t\t\ttry {\n\t\t\t\tawait this.authLogService.logSessionEvent(dbContext, {\n\t\t\t\t\ttype: 'session_policy_applied',\n\t\t\t\t\tidentityId,\n\t\t\t\t\tipAddress: requestInfo?.ip,\n\t\t\t\t\tuserAgent: requestInfo?.userAgent,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\teventData: {\n\t\t\t\t\t\ttokenExpiration: policy.tokenExpiration ? intervalToPostgres(policy.tokenExpiration) : null,\n\t\t\t\t\t\tidleTimeout: policy.idleTimeout ? intervalToPostgres(policy.idleTimeout) : null,\n\t\t\t\t\t\trememberMeAllowed: policy.rememberMeAllowed,\n\t\t\t\t\t\tmfaRequired: policy.mfaRequired,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t/* best-effort: sign-in must not break on an audit failure */\n\t\t\t}\n\t\t}\n\n\t\treturn { id, token }\n\t}\n\n\tasync findApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<ApiKeyRow | null> {\n\t\treturn await dbContext.queryHandler.fetch(\n\t\t\tnew ApiKeyByIdQuery(apiKeyId),\n\t\t)\n\t}\n\n\tasync disableOneOffApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableOneOffApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableApiKey(dbContext: DatabaseContext, apiKeyId: string): Promise<boolean> {\n\t\treturn await dbContext.commandBus.execute(new DisableApiKeyCommand(apiKeyId))\n\t}\n\n\tasync disableIdentityApiKeys(dbContext: DatabaseContext, identityId: string): Promise<void> {\n\t\tawait dbContext.commandBus.execute(new DisableIdentityApiKeysCommand(identityId))\n\t}\n\n\tasync createGlobalPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tdescription: string,\n\t\troles: readonly string[],\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createPermanentApiKey(db, description, roles, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n\n\tasync createProjectPermanentApiKey(\n\t\tdbContext: DatabaseContext,\n\t\tprojectId: string,\n\t\tmemberships: readonly Acl.Membership[],\n\t\tdescription: string,\n\t\ttokenHash?: TokenHash,\n\t\ttrustForwardedInfo?: boolean,\n\t): Promise<CreateApiKeyResponse> {\n\t\treturn await dbContext.transaction(async db => {\n\t\t\treturn await this.apiKeyService.createProjectPermanentApiKey(db, projectId, memberships, description, tokenHash, trustForwardedInfo)\n\t\t})\n\t}\n}\n\ntype FetchedApiKey = {\n\trow: ApiKeyRow\n\tsourceDbContext: DatabaseContext\n}\n\nexport type VerifyResponse = Response<VerifyResult, VerifyErrorCode>\n\nexport class VerifyResult {\n\treadonly valid = true\n\n\tconstructor(\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly apiKeyId: string,\n\t\tpublic readonly roles: string[],\n\t\tpublic readonly personId: string | null,\n\t\tpublic readonly trustForwardedInfo: boolean = false,\n\t) {}\n}\n\nexport enum VerifyErrorCode {\n\tNOT_FOUND = 'not_found',\n\tDISABLED = 'disabled',\n\tEXPIRED = 'expired',\n\tNO_AUTH_HEADER = 'no_auth_header',\n\tINVALID_AUTH_HEADER = 'invalid_auth_header',\n}\n"],"names":["VerifyErrorCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyBO,MAAM,cAAc;AAAA,EAC1B,YACkB,eACA,oBACA,gBACA,2BAAqD,IAAI,yBAAA,GACzD,uBAChB;AALgB,SAAA,gBAAA;AACA,SAAA,qBAAA;AACA,SAAA,iBAAA;AACA,SAAA,2BAAA;AACA,SAAA,wBAAA;AAAA,EACf;AAAA,EAEH,MAAM,iBACL,WACA,eACA,OACA,aACA,eAC0B;AAC1B,UAAM,oBAAoB,KAAK,yBAAyB,OAAO,KAAK;AACpE,QAAI,sBAAsB,MAAM;AAE/B,aAAO,IAAI,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M,UAAU,YAAY,OAAM,OAAM;AAC9C,aAAO,MAAM,KAAK,cAAc,sBAAsB,IAAI,aAAa,OAAO,WAAW,kBAAkB;AAAA,IAC5G,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,6BACL,WACA,WACA,aACA,aACA,WACA,oBACgC;AAChC,WAAO,MAAM,UAAU,YAAY,OAAM,OAAM;AAC9C,aAAO,MAAM,KAAK,cAAc,6BAA6B,IAAI,WAAW,aAAa,aAAa,WAAW,kBAAkB;AAAA,IACpI,CAAC;AAAA,EACF;AACD;AASO,MAAM,aAAa;AAAA,EAGzB,YACiB,YACA,UACA,OACA,UACA,qBAA8B,OAC7C;AALe,SAAA,aAAA;AACA,SAAA,WAAA;AACA,SAAA,QAAA;AACA,SAAA,WAAA;AACA,SAAA,qBAAA;AAPjB,kBAAA,MAAS,SAAQ,IAAA;AAAA,EAQd;AACJ;AAEO,IAAK,oCAAAA,qBAAL;AACNA,mBAAA,WAAA,IAAY;AACZA,mBAAA,UAAA,IAAW;AACXA,mBAAA,SAAA,IAAU;AACVA,mBAAA,gBAAA,IAAiB;AACjBA,mBAAA,qBAAA,IAAsB;AALX,SAAAA;AAAA,GAAA,mBAAA,CAAA,CAAA;"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=verifyAndProlongReplica.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verifyAndProlongReplica.test.d.ts","sourceRoot":"","sources":["../../../../../tests/cases/unit/apiKey/verifyAndProlongReplica.test.ts"],"names":[],"mappings":""}