@camunda/ccma-shared-types 18.4.0 → 18.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-tokens/agent-tokens.d.ts +1 -1
- package/dist/agent-tokens/agent-tokens.js.map +1 -1
- package/dist/annotations/white-glove.d.ts +1 -1
- package/dist/annotations/white-glove.js.map +1 -1
- package/dist/approvals/expected-value.d.ts +1 -1
- package/dist/approvals/expected-value.js.map +1 -1
- package/dist/approvals/policy.d.ts +1 -1
- package/dist/approvals/policy.js.map +1 -1
- package/dist/approvals/use-cases.const.d.ts +3 -3
- package/dist/approvals/use-cases.const.js.map +1 -1
- package/dist/charts/chart-metrics.js.map +1 -1
- package/dist/charts/chart-spec.js.map +1 -1
- package/dist/constants/direct-route-lock.const.d.ts +2 -2
- package/dist/constants/direct-route-lock.const.js.map +1 -1
- package/dist/constants/tsuga.const.d.ts +5 -0
- package/dist/constants/tsuga.const.js +5 -0
- package/dist/constants/tsuga.const.js.map +7 -0
- package/dist/dtos/ActiveUsers.dto.d.ts +1 -1
- package/dist/dtos/Annotation.dto.d.ts +1 -1
- package/dist/dtos/Annotation.dto.js.map +1 -1
- package/dist/dtos/ApprovalJob.dto.d.ts +1 -1
- package/dist/dtos/ApprovalJob.dto.js.map +1 -1
- package/dist/dtos/ApprovalSummaryNames.dto.d.ts +1 -1
- package/dist/dtos/ControlV2.dto.js.map +1 -1
- package/dist/dtos/Dashboard.dto.d.ts +1 -1
- package/dist/dtos/Dashboard.dto.js.map +1 -1
- package/dist/dtos/ExternalWebapp.dto.d.ts +1 -1
- package/dist/dtos/FeatureFlags.dto.d.ts +2 -2
- package/dist/dtos/FeatureFlags.dto.js.map +1 -1
- package/dist/dtos/Hdp.dto.d.ts +1 -1
- package/dist/dtos/M2mTokenCount.dto.d.ts +1 -1
- package/dist/dtos/PermissionHolders.dto.d.ts +1 -1
- package/dist/dtos/PermissionHolders.dto.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +2 -2
- package/dist/permissions/combo.js +3 -0
- package/dist/permissions/combo.js.map +2 -2
- package/dist/permissions/console.permissions.d.ts +14 -2
- package/dist/permissions/console.permissions.js +9 -1
- package/dist/permissions/console.permissions.js.map +2 -2
- package/dist/utils/camundiPermissionAugmenter.utils.d.ts +1 -1
- package/dist/utils/camundiPermissionAugmenter.utils.js.map +1 -1
- package/dist/utils/qa-user.utils.d.ts +1 -1
- package/dist/utils/qa-user.utils.js.map +1 -1
- package/package.json +1 -1
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* control-backend stores the clients. token-issuer exchanges the credentials
|
|
6
6
|
* for an Auth0 token of the agent audience. control-backend, console-backend
|
|
7
|
-
* and accounts-
|
|
7
|
+
* and accounts-ng accept that token on their read routes. Every type and
|
|
8
8
|
* rule that two of these services share is in this file.
|
|
9
9
|
*/
|
|
10
10
|
/** AGENT_CLAIM is the claim of an agent token that names the client. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/agent-tokens/agent-tokens.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport { AccountsPermissions } from '../permissions/accounts.permissions.js'\nimport { ConsolePermissions } from '../permissions/console.permissions.js'\n\n/**\n * The agent tokens of ccmacli: machine credentials that a Camundi creates in\n * Camunda Control for an agent, with read access only.\n *\n * control-backend stores the clients. token-issuer exchanges the credentials\n * for an Auth0 token of the agent audience. control-backend, console-backend\n * and accounts-
|
|
4
|
+
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport { AccountsPermissions } from '../permissions/accounts.permissions.js'\nimport { ConsolePermissions } from '../permissions/console.permissions.js'\n\n/**\n * The agent tokens of ccmacli: machine credentials that a Camundi creates in\n * Camunda Control for an agent, with read access only.\n *\n * control-backend stores the clients. token-issuer exchanges the credentials\n * for an Auth0 token of the agent audience. control-backend, console-backend\n * and accounts-ng accept that token on their read routes. Every type and\n * rule that two of these services share is in this file.\n */\n\n/** AGENT_CLAIM is the claim of an agent token that names the client. */\nexport const AGENT_CLAIM = 'https://camunda.com/agent'\n\n/** AGENT_CLIENT_ID_PREFIX starts every client id of an agent client. */\nexport const AGENT_CLIENT_ID_PREFIX = 'ccma_'\n\n/** AGENT_TOKENS_FEATURE_FLAG closes create and rotate while it is off. */\nexport const AGENT_TOKENS_FEATURE_FLAG = 'control.agentTokens'\n\n/**\n * AGENT_SLACK_GRANTS_FEATURE_FLAG closes the create and the extend of a\n * binding, and the create of a grant, while it is off. The redeem stays open:\n * a code made before the flag went off works until it expires (`AGENT_GRANT_TTL_MS`).\n */\nexport const AGENT_SLACK_GRANTS_FEATURE_FLAG = 'control.agentSlackGrants'\n\n/**\n * The form of a Slack channel ID: public (`C`) or private (`G`) channel.\n * A binding stores the ID, never the name.\n */\nexport const AGENT_SLACK_CHANNEL_PATTERN = /^[CG][A-Z0-9]{8,}$/\n\n/** AGENT_GRANT_TTL_MS is the time in which a grant code can be redeemed. */\nexport const AGENT_GRANT_TTL_MS = 120_000\n\n/** AGENT_GRANTS_PER_HOUR_MAX is the limit of new grants for one binding. */\nexport const AGENT_GRANTS_PER_HOUR_MAX = 10\n\n/** AGENT_TOKEN_EXPIRY_DAYS lists the lifetimes that a creator can choose. */\nexport const AGENT_TOKEN_EXPIRY_DAYS = [7, 30, 90] as const\n\nexport type AgentTokenExpiryDays = (typeof AGENT_TOKEN_EXPIRY_DAYS)[number]\n\n/** AGENT_TOKEN_NAME_MAX is the length limit of a name, after the trim. */\nexport const AGENT_TOKEN_NAME_MAX = 64\n\n/** AGENT_TOKENS_ACTIVE_MAX is the limit of active clients for one creator. */\nexport const AGENT_TOKENS_ACTIVE_MAX = 10\n\n/**\n * `secret` is a client with an id and a secret. `slack` is a binding to one\n * Slack channel: it has no secret, and a grant gives it a token.\n */\nexport type AgentTokenKind = 'secret' | 'slack'\n\n/** Phase 1 has read access only. Phase 2 adds `write`. */\nexport type AgentAccess = 'read'\n\n/** The value of `AGENT_CLAIM` in a verified agent token. */\nexport interface AgentClaim {\n uuid: string\n access: AgentAccess\n /** The `sub` of the Camundi who created the client. */\n createdByUserId: string\n}\n\n/** `inactive` means that the creator is no longer a Camundi. */\nexport type AgentTokenStatus = 'active' | 'expired' | 'revoked' | 'inactive'\n\n/** AGENT_TOKEN_STATUSES lists every value of `AgentTokenStatus`. */\nexport const AGENT_TOKEN_STATUSES = [\n 'active',\n 'expired',\n 'revoked',\n 'inactive',\n] as const satisfies readonly AgentTokenStatus[]\n\n/** One agent client, as its creator sees it. It never holds the secret. */\nexport interface AgentToken {\n uuid: string\n clientId: string\n name: string\n access: AgentAccess\n kind: AgentTokenKind\n /** The channel ID of a binding. It is absent when `kind` is `secret`. */\n slackChannelId?: string\n status: AgentTokenStatus\n createdAt: string\n expiresAt: string\n lastUsedAt?: string\n revokedAt?: string\n}\n\n/**\n * AgentTokenCreated is the answer of create and rotate. It is the only answer\n * that holds `clientSecret`, and the backend cannot show the secret again.\n */\nexport interface AgentTokenCreated extends AgentToken {\n /** Absent for a binding, which has no secret. */\n clientSecret?: string\n}\n\n/** One agent client, as the admin list shows it. */\nexport interface AgentTokenAdmin extends AgentToken {\n createdBy: { userId: string; email: string }\n revokedByUserId?: string\n}\n\n/** The body of `POST /api/agent-tokens`. */\nexport interface CreateAgentTokenDto {\n name: string\n expiresInDays: AgentTokenExpiryDays\n /** Set it to make a binding to this channel. Then there is no secret. */\n slackChannelId?: string\n}\n\n/** The body of `POST /api/agent-tokens/:uuid/extend`. */\nexport interface ExtendAgentTokenDto {\n expiresInDays: AgentTokenExpiryDays\n}\n\n/** The body of `POST /internal/agent-grants`. CloudBot sends it. */\nexport interface CreateAgentGrantDto {\n slackChannelId: string\n slackThreadTs: string\n requestedBySlackUserId: string\n requestedByEmail: string\n /** The S256 challenge of the PKCE verifier that only ccmacli knows. */\n codeChallenge: string\n}\n\n/** The answer of `POST /internal/agent-grants`. */\nexport interface AgentGrantCreated {\n code: string\n expiresAt: string\n}\n\n/** Why control-backend refuses a grant. CloudBot words the reply from it. */\nexport type AgentGrantRefusalReason =\n | 'no_binding'\n | 'expired'\n | 'revoked'\n | 'inactive'\n | 'requester_unknown'\n | 'rate_limited'\n | 'thread_busy'\n | 'feature_off'\n\n/** The body of the 409 answer of `POST /internal/agent-grants`. */\nexport interface AgentGrantRefusal {\n code: string\n message: string\n reason: AgentGrantRefusalReason\n expiredAt?: string\n ownerEmail?: string\n}\n\n/** The body of `POST /internal/agent-grants/redeem`. token-issuer sends it. */\nexport interface RedeemAgentGrantDto {\n code: string\n codeVerifier: string\n}\n\n/** The answer of `POST /internal/agent-clients/verify`. */\nexport interface AgentVerifyResponse {\n uuid: string\n access: AgentAccess\n createdByUserId: string\n}\n\n/**\n * The answer of `GET /internal/agent-clients/:uuid/status`.\n *\n * `permissions` is `AGENT_READ_PERMISSIONS` of all backends, intersected with\n * the permissions of the creator at the create or the last extend. It is empty\n * when `active` is false.\n */\nexport interface AgentStatusResponse {\n active: boolean\n permissions: string[]\n}\n\n/**\n * AGENT_READ_PERMISSIONS is the most that an agent token can do in each\n * backend. A backend intersects its set with the `permissions` of the status\n * answer, so an agent never holds a permission that its creator did not hold.\n *\n * `crtp` is a publish permission. It is here for one read only, the\n * release-train sanity check. The agent allowlist of console-backend, which a\n * later change of epic #10804 adds, must be the bound. Never add a route to\n * that allowlist that `crtp` guards for a write.\n */\nexport const AGENT_READ_PERMISSIONS: Readonly<{\n control: readonly string[]\n console: readonly string[]\n accounts: readonly string[]\n}> = {\n control: [AccountsPermissions.READ_ALL],\n console: [\n ConsolePermissions.CHANNELS_AND_GENERATIONS_ADMIN_SEE,\n ConsolePermissions.CLUSTERS_READALLCLUSTERINFO,\n ConsolePermissions.CLUSTER_PLAN_SEE_ALL,\n ConsolePermissions.RELEASE_TRAIN_PUBLISH,\n ],\n accounts: [AccountsPermissions.READ_ALL],\n}\n\n/** agentReadPermissionUnion is the union of the three backend sets. */\nexport function agentReadPermissionUnion(): string[] {\n return [\n ...new Set([\n ...AGENT_READ_PERMISSIONS.control,\n ...AGENT_READ_PERMISSIONS.console,\n ...AGENT_READ_PERMISSIONS.accounts,\n ]),\n ]\n}\n\n/** The codes of the two denials that only an agent token can get. */\nexport const AGENT_ERROR = {\n readOnly: 'auth.agent_read_only',\n inactive: 'auth.agent_inactive',\n} as const\n\nconst UUID_SHAPE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/**\n * parseAgentClaim reads `AGENT_CLAIM` from the payload of a VERIFIED token.\n * It returns `undefined` when the claim is absent or has a wrong shape, and\n * the caller must then refuse the token.\n */\nexport function parseAgentClaim(\n payload: Record<string, unknown>,\n): AgentClaim | undefined {\n const claim = payload[AGENT_CLAIM]\n if (typeof claim !== 'object' || claim === null || Array.isArray(claim)) {\n return undefined\n }\n const { uuid, access, createdByUserId } = claim as Record<string, unknown>\n if (\n typeof uuid !== 'string' ||\n !UUID_SHAPE.test(uuid) ||\n access !== 'read' ||\n typeof createdByUserId !== 'string' ||\n createdByUserId.length === 0\n ) {\n return undefined\n }\n return { uuid, access, createdByUserId }\n}\n"],
|
|
5
5
|
"mappings": "AAMA,SAAS,2BAA2B;AACpC,SAAS,0BAA0B;AAa5B,MAAM,cAAc;AAGpB,MAAM,yBAAyB;AAG/B,MAAM,4BAA4B;AAOlC,MAAM,kCAAkC;AAMxC,MAAM,8BAA8B;AAGpC,MAAM,qBAAqB;AAG3B,MAAM,4BAA4B;AAGlC,MAAM,0BAA0B,CAAC,GAAG,IAAI,EAAE;AAK1C,MAAM,uBAAuB;AAG7B,MAAM,0BAA0B;AAuBhC,MAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAqHO,MAAM,yBAIR;AAAA,EACH,SAAS,CAAC,oBAAoB,QAAQ;AAAA,EACtC,SAAS;AAAA,IACP,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,EACrB;AAAA,EACA,UAAU,CAAC,oBAAoB,QAAQ;AACzC;AAGO,SAAS,2BAAqC;AACnD,SAAO;AAAA,IACL,GAAG,oBAAI,IAAI;AAAA,MACT,GAAG,uBAAuB;AAAA,MAC1B,GAAG,uBAAuB;AAAA,MAC1B,GAAG,uBAAuB;AAAA,IAC5B,CAAC;AAAA,EACH;AACF;AAGO,MAAM,cAAc;AAAA,EACzB,UAAU;AAAA,EACV,UAAU;AACZ;AAEA,MAAM,aACJ;AAOK,SAAS,gBACd,SACwB;AACxB,QAAM,QAAQ,QAAQ,WAAW;AACjC,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG;AACvE,WAAO;AAAA,EACT;AACA,QAAM,EAAE,MAAM,QAAQ,gBAAgB,IAAI;AAC1C,MACE,OAAO,SAAS,YAChB,CAAC,WAAW,KAAK,IAAI,KACrB,WAAW,UACX,OAAO,oBAAoB,YAC3B,gBAAgB,WAAW,GAC3B;AACA,WAAO;AAAA,EACT;AACA,SAAO,EAAE,MAAM,QAAQ,gBAAgB;AACzC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AnnotationDto, AnnotationLookupEntryDto } from '../dtos/Annotation.dto.js';
|
|
2
2
|
/**
|
|
3
3
|
* The tag that marks a white-glove org or cluster. A Camundi sets it in
|
|
4
|
-
* Control like any other tag. Control and
|
|
4
|
+
* Control like any other tag. Control, ccmacli and CloudBot read it and warn.
|
|
5
5
|
*/
|
|
6
6
|
export declare const WHITE_GLOVE_TAG = "white-glove";
|
|
7
7
|
/** What every surface shows for a marked org or cluster. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/annotations/white-glove.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport type {\n AnnotationDto,\n AnnotationLookupEntryDto,\n} from '../dtos/Annotation.dto.js'\nimport { normalizeTagName } from '../dtos/Annotation.dto.js'\n\n/**\n * The tag that marks a white-glove org or cluster. A Camundi sets it in\n * Control like any other tag. Control and
|
|
4
|
+
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport type {\n AnnotationDto,\n AnnotationLookupEntryDto,\n} from '../dtos/Annotation.dto.js'\nimport { normalizeTagName } from '../dtos/Annotation.dto.js'\n\n/**\n * The tag that marks a white-glove org or cluster. A Camundi sets it in\n * Control like any other tag. Control, ccmacli and CloudBot read it and warn.\n */\nexport const WHITE_GLOVE_TAG = 'white-glove'\n\n/** What every surface shows for a marked org or cluster. */\nexport const WHITE_GLOVE_WARNING =\n 'White-glove customer. Do not change without asking the stakeholders.'\n\nconst WHITE_GLOVE_NORMALIZED = normalizeTagName(WHITE_GLOVE_TAG)\n\n/** Whether a tag name is the white-glove tag, after normalizing. */\nexport function isWhiteGloveName(name: string): boolean {\n return normalizeTagName(name) === WHITE_GLOVE_NORMALIZED\n}\n\n/**\n * The white-glove tag annotation of a lookup entry, if it has one. Its\n * `reason`, `createdBy` and `createdAt` say why, who and when. An entry with\n * the tag from before reasons were required has no `reason`.\n */\nexport function whiteGloveAnnotation(\n entry: AnnotationLookupEntryDto | undefined,\n): AnnotationDto | undefined {\n return entry?.tags.find(\n (annotation) => annotation.tag?.normalizedName === WHITE_GLOVE_NORMALIZED,\n )\n}\n\n/**\n * Whether a lookup entry carries the white-glove tag.\n *\n * It compares the normalized name, so `White-Glove ` counts. The lookup cuts\n * the tags of one entity at `ANNOTATION_LOOKUP_TAGS_MAX`: an entity with more\n * tags can hide this one, and then this returns false. `tagCount` above\n * `tags.length` shows that case.\n */\nexport function isWhiteGlove(\n entry: AnnotationLookupEntryDto | undefined,\n): boolean {\n return whiteGloveAnnotation(entry) !== undefined\n}\n"],
|
|
5
5
|
"mappings": "AAUA,SAAS,wBAAwB;AAM1B,MAAM,kBAAkB;AAGxB,MAAM,sBACX;AAEF,MAAM,yBAAyB,iBAAiB,eAAe;AAGxD,SAAS,iBAAiB,MAAuB;AACtD,SAAO,iBAAiB,IAAI,MAAM;AACpC;AAOO,SAAS,qBACd,OAC2B;AAC3B,SAAO,OAAO,KAAK;AAAA,IACjB,CAAC,eAAe,WAAW,KAAK,mBAAmB;AAAA,EACrD;AACF;AAUO,SAAS,aACd,OACS;AACT,SAAO,qBAAqB,KAAK,MAAM;AACzC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* one thing.
|
|
14
14
|
*
|
|
15
15
|
* The comparison lives here so that the form of control-frontend, the use case
|
|
16
|
-
* of control-backend and the route of accounts-
|
|
16
|
+
* of control-backend and the route of accounts-ng read "the same value"
|
|
17
17
|
* in one way.
|
|
18
18
|
*/
|
|
19
19
|
/** One value that a request writes, with the value that the asker read. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/approvals/expected-value.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\n/**\n * The guard against a stale approval.\n *\n * Days can pass between the request and the run. A request that says \"set X\n * from 3 to 5\" was approved as a CHANGE from 3. When somebody else set X to 4\n * in the meantime, the run must not write 5 over the 4: the approvers never\n * read that change, and they never agreed to undo it.\n *\n * So a use case that writes a value carries the value that the person who\n * asked READ, as `expected`. The service that owns the value compares it with\n * what it holds when the call ARRIVES, and it refuses the whole change when one\n * value moved. It never applies a part of it: the approvers read the change as\n * one thing.\n *\n * The comparison lives here so that the form of control-frontend, the use case\n * of control-backend and the route of accounts-
|
|
4
|
+
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\n/**\n * The guard against a stale approval.\n *\n * Days can pass between the request and the run. A request that says \"set X\n * from 3 to 5\" was approved as a CHANGE from 3. When somebody else set X to 4\n * in the meantime, the run must not write 5 over the 4: the approvers never\n * read that change, and they never agreed to undo it.\n *\n * So a use case that writes a value carries the value that the person who\n * asked READ, as `expected`. The service that owns the value compares it with\n * what it holds when the call ARRIVES, and it refuses the whole change when one\n * value moved. It never applies a part of it: the approvers read the change as\n * one thing.\n *\n * The comparison lives here so that the form of control-frontend, the use case\n * of control-backend and the route of accounts-ng read \"the same value\"\n * in one way.\n */\n\n/** One value that a request writes, with the value that the asker read. */\nexport interface ApprovalExpectedChange<T = unknown> {\n key: string\n /** The value that the person who asked read. `undefined` for \"not set\". */\n expected?: T\n}\n\n/**\n * Turns a value into the one text that two equal values share.\n *\n * `undefined` and `null` both mean \"not set\", because a JSON body cannot carry\n * `undefined` and a database column reads as `null`. The keys of an object\n * are sorted, because two objects with the same fields in another order are\n * the same value.\n */\nfunction canonical(value: unknown): string {\n if (value === undefined || value === null) {\n return 'null'\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonical).join(',')}]`\n }\n if (typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, inner]) => inner !== undefined)\n .sort(([one], [other]) => (one < other ? -1 : one > other ? 1 : 0))\n .map(([key, inner]) => `${JSON.stringify(key)}:${canonical(inner)}`)\n return `{${entries.join(',')}}`\n }\n return JSON.stringify(value)\n}\n\n/** True when the value that the asker read is the value that the service holds. */\nexport function isSameApprovalValue(\n expected: unknown,\n current: unknown,\n): boolean {\n return canonical(expected) === canonical(current)\n}\n\n/**\n * The keys of a change whose value moved since the person who asked read it.\n *\n * An empty answer means the change can run. Any other answer means none of it\n * can.\n */\nexport function staleApprovalKeys(\n changes: readonly ApprovalExpectedChange[],\n currentOf: (key: string) => unknown,\n): string[] {\n return changes\n .filter(\n (change) => !isSameApprovalValue(change.expected, currentOf(change.key)),\n )\n .map((change) => change.key)\n}\n"],
|
|
5
5
|
"mappings": "AAwCA,SAAS,UAAU,OAAwB;AACzC,MAAI,UAAU,UAAa,UAAU,MAAM;AACzC,WAAO;AAAA,EACT;AACA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,IAAI,MAAM,IAAI,SAAS,EAAE,KAAK,GAAG,CAAC;AAAA,EAC3C;AACA,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,UAAU,OAAO,QAAQ,KAAgC,EAC5D,OAAO,CAAC,CAAC,EAAE,KAAK,MAAM,UAAU,MAAS,EACzC,KAAK,CAAC,CAAC,GAAG,GAAG,CAAC,KAAK,MAAO,MAAM,QAAQ,KAAK,MAAM,QAAQ,IAAI,CAAE,EACjE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,GAAG,KAAK,UAAU,GAAG,CAAC,IAAI,UAAU,KAAK,CAAC,EAAE;AACrE,WAAO,IAAI,QAAQ,KAAK,GAAG,CAAC;AAAA,EAC9B;AACA,SAAO,KAAK,UAAU,KAAK;AAC7B;AAGO,SAAS,oBACd,UACA,SACS;AACT,SAAO,UAAU,QAAQ,MAAM,UAAU,OAAO;AAClD;AAQO,SAAS,kBACd,SACA,WACU;AACV,SAAO,QACJ;AAAA,IACC,CAAC,WAAW,CAAC,oBAAoB,OAAO,UAAU,UAAU,OAAO,GAAG,CAAC;AAAA,EACzE,EACC,IAAI,CAAC,WAAW,OAAO,GAAG;AAC/B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -84,7 +84,7 @@ export declare function isSameActor(identity: {
|
|
|
84
84
|
/**
|
|
85
85
|
* Reports whether this actor carries an address that names a person.
|
|
86
86
|
*
|
|
87
|
-
* A machine-to-machine token carries none: accounts-
|
|
87
|
+
* A machine-to-machine token carries none: accounts-ng builds the
|
|
88
88
|
* permissions of such a token from its `permissions` claim alone, and there is
|
|
89
89
|
* no person behind it. See `creatorEmailRequired` of the use case.
|
|
90
90
|
*/
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/approvals/policy.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport { UNKNOWN_ACTOR_EMAIL } from '../constants/misc.const.js'\nimport type {\n ApprovalJobDto,\n ApprovalOverrideGrantDto,\n ApprovalUseCaseDto,\n} from '../dtos/ApprovalJob.dto.js'\nimport { AccountsPermissions } from '../permissions/accounts.permissions.js'\nimport { ConsolePermissions } from '../permissions/console.permissions.js'\nimport {\n APPROVAL_USE_CASE_TYPES,\n isApprovalOverridable,\n} from './use-cases.const.js'\n\n/**\n * The rules of the approval mechanism, as pure functions.\n *\n * Three consumers run this file: control-backend decides whether to reject a\n * request, control-frontend decides whether to disable a button, and cloudbot\n * decides whether to answer. One copy means the button and the endpoint can\n * never disagree.\n *\n * Two choices in the signatures carry the design:\n *\n * - The actor is an interface with a `has` method. The backend holds an array\n * of Auth0 claims, and `useSession()` in the frontend gives a flat record of\n * booleans. Neither side has to convert to the shape of the other.\n * - `now` is a parameter. The expiry is lazy, so a stored `pending` request can\n * be expired already. A parameter makes a difference between the two clocks\n * an input that a test can set, and not a silent disagreement.\n *\n * No function here does I/O or returns a promise. The browser call site is what\n * enforces that, and it also stops a later use case from turning a list of 50\n * rows into 200 network calls.\n */\n\n/** Who is asking. See the note above on why this is an interface. */\nexport interface ApprovalActorView {\n userId: string\n /**\n * The email of the actor. It is the SECOND identity of the four-eyes rule.\n *\n * `userId` alone is not enough. One person can hold more than one identity in\n * Auth0 \u2014 a connection through SSO and a connection through a database, or an\n * account that was made again \u2014 and each one carries a different `sub`. The\n * same human then opens a request with one identity and approves it with the\n * other, which is the rule defeated.\n *\n * It is optional because a token can carry no email. See\n * `isSameActorEmail` for what that means for the comparison.\n */\n email?: string\n has(permission: string): boolean\n /**\n * True when the actor reads every request that `restrictedRead` does not\n * hide, and has no other right. It is a READ stand-in for `READ_ALL` that\n * `has` does not answer, so a rule that opens or acts on a request never\n * sees it. Only control-backend sets it, for a machine token with\n * `M2M_CONTROL_READ`.\n */\n readsAll?: boolean\n}\n\n/**\n * Builds the `has` of an actor from the permissions that the actor holds.\n *\n * `ConsolePermissions.APPROVALS_ALL_USE_CASES` stands in for every permission\n * that a use case asks for. Both actor builders call this function, the one of\n * control-backend and the one of the browser, so the button and the route\n * agree on it. A rule that reads `actor.has` needs no change for it, and nor\n * does a use case that a later change adds.\n */\nexport function approvalPermissionCheck(\n held: ReadonlySet<string>,\n): (permission: string) => boolean {\n const all = held.has(ConsolePermissions.APPROVALS_ALL_USE_CASES)\n return (permission) => all || held.has(permission)\n}\n\n/**\n * Reports whether two email addresses name one person.\n *\n * Two values that are absent, empty, or `UNKNOWN_ACTOR_EMAIL` are NOT one\n * person. A token with no email would otherwise make every actor equal to\n * every other actor, and the rule would refuse everybody.\n *\n * The comparison removes the spaces and the case. Auth0 gives the address as\n * the identity provider wrote it, so `A.B@camunda.com` and `a.b@camunda.com`\n * are one mailbox and must not pass as two people.\n */\nexport function isSameActorEmail(one?: string, other?: string): boolean {\n const left = comparableActorEmail(one)\n return left.length > 0 && left === comparableActorEmail(other)\n}\n\n/**\n * The address in the one form that a comparison may use.\n *\n * An absent address, an empty one and `UNKNOWN_ACTOR_EMAIL` all become an\n * empty string, because none of the three names a person. The spaces and the\n * case go as well: Auth0 gives the address as the identity provider wrote it.\n */\nfunction comparableActorEmail(value?: string): string {\n const trimmed = value?.trim().toLowerCase() ?? ''\n return trimmed === UNKNOWN_ACTOR_EMAIL ? '' : trimmed\n}\n\n/**\n * Reports whether one identity of a request names the actor.\n *\n * The `sub` of the token OR the email, because one person can hold more than\n * one Auth0 identity. Every rule that asks \"is this the same human?\" reads both\n * through this function, so a rule cannot forget the second half: `canWithdraw`\n * did, and it refused a creator whose browser and whose service resolved the\n * id from two different tokens.\n */\nexport function isSameActor(\n identity: { userId: string; email?: string },\n actor: ApprovalActorView,\n): boolean {\n return (\n identity.userId === actor.userId ||\n isSameActorEmail(identity.email, actor.email)\n )\n}\n\n/**\n * Reports whether this actor carries an address that names a person.\n *\n * A machine-to-machine token carries none: accounts-backend builds the\n * permissions of such a token from its `permissions` claim alone, and there is\n * no person behind it. See `creatorEmailRequired` of the use case.\n */\nexport function hasActorEmail(actor: ApprovalActorView): boolean {\n return comparableActorEmail(actor.email).length > 0\n}\n\n/**\n * Why an action is not allowed.\n *\n * The code is for a program: control-backend maps it to a status, and the\n * frontend can branch on it. The message is for a person, and it is shown as\n * written.\n */\nexport type ApprovalDenialCode =\n | 'forbidden'\n | 'not-pending'\n | 'self-approval'\n | 'self-rejection'\n | 'already-acknowledged'\n | 'expired'\n | 'not-creator'\n | 'not-executable'\n | 'no-reason'\n | 'too-few-acks'\n | 'no-creator-email'\n | 'no-override-grant'\n | 'not-overridable'\n\nexport type ApprovalDecision =\n | { allowed: true }\n | { allowed: false; code: ApprovalDenialCode; message: string }\n\nconst ALLOWED: ApprovalDecision = { allowed: true }\n\nfunction deny(code: ApprovalDenialCode, message: string): ApprovalDecision {\n return { allowed: false, code, message }\n}\n\n/**\n * Reports whether the time to answer a request has passed.\n *\n * Only a `pending` request expires. A request that already reached an end state\n * keeps that state, because \"expired\" would lose the answer that was given.\n */\nexport function isExpired(job: ApprovalJobDto, now: Date): boolean {\n return (\n job.status === 'pending' &&\n new Date(job.expiresAt).getTime() <= now.getTime()\n )\n}\n\n/**\n * Reports the status to show. It is `expired` once the time to answer has\n * passed, or once the run window of an `approved` or `failed` request has\n * ended. control-backend writes both, and this shows them before the write.\n */\nexport function effectiveStatus(\n job: ApprovalJobDto,\n now: Date,\n): ApprovalJobDto['status'] {\n return isExpired(job, now) || isRunWindowClosed(job, now)\n ? 'expired'\n : job.status\n}\n\n/** Reports how many more acknowledgements the request needs. */\nexport function remainingAcks(job: ApprovalJobDto): number {\n return Math.max(0, job.requiredAcks - job.acks.length)\n}\n\n/**\n * Reports whether the actor holds EVERY permission of the set.\n *\n * Every, and not one of them. A payload that raises the guard adds a\n * permission, so \"one of them\" would let the base permission alone carry a\n * request that the extra permission exists to stop.\n *\n * An EMPTY set is held by nobody. That is the opposite of what `Array.every`\n * answers, and it is deliberate: this function guards a privileged action, so\n * the empty case must fail closed. A row with no permissions is not a row that\n * everybody may run \u2014 it is a row that lost its guard, through a migration\n * that did not backfill it or a write that went around the service. Every use\n * case builds a set of at least one, so no real request meets this branch.\n */\nexport function hasEveryPermission(\n actor: ApprovalActorView,\n permissions: string[],\n): boolean {\n if (permissions.length === 0) {\n return false\n }\n return permissions.every((permission) => actor.has(permission))\n}\n\n/**\n * What a person must hold to act on a request.\n *\n * A request carries its own set, because a payload can raise the guard. A use\n * case that never does has a set of one, and it is the base permission.\n */\nexport function requiredPermissionsOf(job: ApprovalJobDto): string[] {\n return job.requiredPermissions\n}\n\n/**\n * True when this actor can read EVERY request of the use case.\n *\n * The actor holds the base permission of the use case, or holds `READ_ALL`\n * (`aara`). `aara` is the baseline read gate of Control, so its holders read\n * the requests of every use case by default. A use case with `restrictedRead`\n * leaves `aara` out. The list filters by this rule in SQL. `canView` adds the\n * requests that the actor opened, and the override grantee.\n */\nexport function canReadUseCase(\n useCase: Pick<ApprovalUseCaseDto, 'requiredPermission' | 'restrictedRead'>,\n actor: ApprovalActorView,\n): boolean {\n return (\n actor.has(useCase.requiredPermission) ||\n (useCase.restrictedRead !== true &&\n (actor.has(AccountsPermissions.READ_ALL) || actor.readsAll === true))\n )\n}\n\n/**\n * Who can READ a request.\n *\n * The person who can act on it, the one who opened it, and a holder of `aara`\n * (see `canReadUseCase`). A Camundi who is none of these has no reason to read\n * which customer somebody proposed to expire, so the list and the detail both\n * hide it.\n *\n * The rule reads the BASE permission of the use case and not the effective set\n * of the request. A payload that raises the guard raises who can APPROVE, and\n * not who can look: a generation update with the yolo flag is visible to\n * everybody who can approve a plain one, and only the yolo permission runs it.\n * The list filters by use case in SQL, which is what makes one page of rows\n * the same page that a person is allowed to read.\n */\nexport function canView(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n useCase: ApprovalUseCaseDto,\n): ApprovalDecision {\n if (\n canReadUseCase(useCase, actor) ||\n isSameActor(job.createdBy, actor) ||\n isOverrideGrantee(job, actor)\n ) {\n return ALLOWED\n }\n return deny('forbidden', 'You cannot see this request.')\n}\n\n/**\n * The person that a request of the two override use cases names, or\n * `undefined` for every other request.\n *\n * Four rules read it. The grantee cannot approve their own grant, also not\n * when they open it (`opensWithOwnApproval`), the grantee can read both\n * requests, and the grantee can end their own grant before its time.\n */\nexport function overrideGranteeOf(\n job: Pick<ApprovalJobDto, 'type' | 'payload'>,\n): { userId: string; email?: string } | undefined {\n if (\n job.type !== APPROVAL_USE_CASE_TYPES.grantApprovalOverride &&\n job.type !== APPROVAL_USE_CASE_TYPES.revokeApprovalOverride\n ) {\n return undefined\n }\n const { granteeUserId, granteeEmail } = job.payload\n if (typeof granteeUserId !== 'string' && typeof granteeEmail !== 'string') {\n return undefined\n }\n return {\n userId: typeof granteeUserId === 'string' ? granteeUserId : '',\n email: typeof granteeEmail === 'string' ? granteeEmail : undefined,\n }\n}\n\nfunction isOverrideGrantee(\n job: Pick<ApprovalJobDto, 'type' | 'payload'>,\n actor: ApprovalActorView,\n): boolean {\n const grantee = overrideGranteeOf(job)\n return grantee !== undefined && isSameActor(grantee, actor)\n}\n\n/**\n * Reports whether an approval override grant lets its holder act now.\n *\n * It fails closed: an absent grant, a revoked one, and a date that does not\n * parse are all inactive. control-backend reads the grant from its table at\n * every call. A token never carries it.\n */\nexport function isOverrideGrantActive(\n grant: Pick<ApprovalOverrideGrantDto, 'expiresAt' | 'revokedAt'> | undefined,\n now: Date,\n): boolean {\n if (!grant || grant.revokedAt) {\n return false\n }\n return new Date(grant.expiresAt).getTime() > now.getTime()\n}\n\n/**\n * The permissions that open a request of this use case. Any one of them is\n * enough. Returns `[]` when the field is absent or empty. `canCreate` tells\n * them apart: absent opens to anybody signed in, empty to nobody.\n */\nexport function createPermissionsOf(\n useCase: Pick<ApprovalUseCaseDto, 'createPermission'>,\n): string[] {\n const { createPermission } = useCase\n if (createPermission === undefined) {\n return []\n }\n return typeof createPermission === 'string'\n ? [createPermission]\n : [...createPermission]\n}\n\n/**\n * Who can OPEN a request, and with what.\n *\n * `createPermission` is what keeps the pool that asks as small as the pool that\n * approves. A use case that leaves it absent says the opposite on purpose: the\n * approvals are the guard, and anybody signed in can propose the action.\n *\n * The two checks after it are about the request and not about the person. A\n * count below the floor of the use case, and a missing reason, are both a 400\n * and not a 403, so the words say which one the caller must repair.\n */\nexport function canCreate(\n actor: ApprovalActorView,\n useCase: ApprovalUseCaseDto,\n request: {\n reason?: string\n requiredAcks?: number\n /**\n * The effective permissions of the payload, from `permissionsFor`.\n *\n * Absent means \"the base permission alone\", which is what most use cases\n * build. Only the permissions ABOVE the base one gate opening a request:\n * see the note in the body.\n */\n requiredPermissions?: string[]\n } = {},\n): ApprovalDecision {\n // The message NAMES the permission. \"You cannot open this request\" is true\n // and useless: a Camundi who reads it cannot tell a missing permission from\n // a rule they never heard of, and the detail page names the permissions of\n // a request in the same way.\n const createPermissions = createPermissionsOf(useCase)\n // An empty list is a mistake of the use case. It must close the request,\n // and not open it to everyone, so it is checked on the DTO and not on the\n // list that `createPermissionsOf` returns.\n if (\n useCase.createPermission !== undefined &&\n !createPermissions.some((permission) => actor.has(permission))\n ) {\n return deny(\n 'forbidden',\n createPermissions.length === 0\n ? 'Nobody can open this request, because its use case lists no permission.'\n : `Opening this request needs ${createPermissions.join(' or ')}, and ${\n createPermissions.length > 1\n ? 'you hold none of them'\n : 'you do not hold it'\n }.`,\n )\n }\n // What the PAYLOAD raised, on top of the base permission of the use case.\n // A bulk generation update with the yolo flag needs the yolo permission, and\n // without this check a person who holds the base permission alone could open\n // one. They could not approve it and could not run it, so it is not an\n // escalation \u2014 it is a request that its own author is not allowed to make,\n // waiting in the queue of the people who are.\n //\n // The BASE permission is deliberately not checked here. `createPermission`\n // above is the only gate on the person, and a use case that leaves it absent\n // means that anybody signed in can propose the action. Checking the base\n // permission too would take that choice away from every use case.\n const raised = (request.requiredPermissions ?? []).filter(\n (permission) => permission !== useCase.requiredPermission,\n )\n if (raised.length > 0 && !hasEveryPermission(actor, raised)) {\n return deny(\n 'forbidden',\n `This payload needs ${raised.join(' and ')}, and you do not hold it.`,\n )\n }\n // A request that needs no approval RUNS when it is opened, so the person who\n // opens it must hold what running it needs. Every other use case leaves this\n // to the approvals, which is why the base permission is not checked above.\n // With a floor of zero there is no approval to leave it to.\n const toRun = request.requiredPermissions ?? [useCase.requiredPermission]\n // A service that opens a request of its own use case holds the\n // `createPermission` checked above, and that is the guard of the run. Without\n // a `createPermission` there is no such guard, so the flag lifts nothing.\n const openedBySystem = useCase.openedBySystem && createPermissions.length > 0\n if (\n resolveRequiredAcks(useCase, request.requiredAcks) === 0 &&\n !useCase.openToEveryone &&\n !openedBySystem &&\n !hasEveryPermission(actor, toRun)\n ) {\n // The message NAMES the permission, and it says why opening needs it. A\n // Camundi who reads \"you cannot open this request\" for an action that\n // needs no approval cannot tell which of the two rules refused them.\n return deny(\n 'forbidden',\n `This request needs no approval, so opening it runs it. That needs ` +\n `${toRun.join(' and ')}, and you do not hold it.`,\n )\n }\n // The action of this use case carries the address of the person who asked,\n // so a caller with no address must be refused HERE. The alternative is a\n // request that looks ordinary, collects its approvals over days, and then\n // fails because the other service cannot find a user called \"unknown\".\n if (useCase.creatorEmailRequired && !hasActorEmail(actor)) {\n return deny(\n 'no-creator-email',\n 'This action needs the email address of the person who asks for it, ' +\n 'and your session carries none. Sign in as a person to open this ' +\n 'request.',\n )\n }\n if (\n needsReason(actor, useCase, {\n requiredAcks: request.requiredAcks,\n requiredPermissions: toRun,\n }) &&\n (request.reason ?? '').trim().length === 0\n ) {\n return deny('no-reason', 'Give a reason to open this request.')\n }\n if (\n request.requiredAcks !== undefined &&\n request.requiredAcks < useCase.minAcks\n ) {\n return deny(\n 'too-few-acks',\n `This action needs at least ${useCase.minAcks} approvals.`,\n )\n }\n return ALLOWED\n}\n\n/**\n * Reports whether the opener approves a new request when it is created.\n *\n * The opener approves when the request needs an approval and the opener holds\n * every run permission of it. `APPROVAL_RULES` counts this approval. A request\n * that needs no approval gets none, so its `approvedBy` stays empty.\n *\n * When `request` is given, the grantee of an approval override grant does not\n * approve the grant that they open for themselves, as `canAcknowledge`\n * refuses their approval later. Every approval of such a request then comes\n * from another person.\n */\nexport function opensWithOwnApproval(\n actor: ApprovalActorView,\n requiredAcks: number,\n requiredPermissions: string[],\n request?: Pick<ApprovalJobDto, 'type' | 'payload'>,\n): boolean {\n if (request !== undefined && isOverrideGrantee(request, actor)) {\n return false\n }\n return requiredAcks > 0 && hasEveryPermission(actor, requiredPermissions)\n}\n\n/**\n * Reports whether a new request needs a reason.\n *\n * A request needs no reason when its opener holds every run permission and\n * needs no second person. Nobody else reads the reason before the action\n * runs, and the audit record names the opener.\n */\nexport function needsReason(\n actor: ApprovalActorView,\n useCase: ApprovalUseCaseDto,\n request: { requiredAcks?: number; requiredPermissions?: string[] } = {},\n): boolean {\n if (!useCase.reasonRequired) {\n return false\n }\n return !(\n resolveRequiredAcks(useCase, request.requiredAcks) <= 1 &&\n hasEveryPermission(\n actor,\n request.requiredPermissions ?? [useCase.requiredPermission],\n )\n )\n}\n\n/**\n * The approvals that a new request asks for.\n *\n * The caller names a number or names none. A number below the floor is refused\n * by `canCreate`, and this function holds the answer inside the range anyway:\n * the two run in the same call, and a floor that only one of them knows is a\n * floor that a later caller can step over.\n */\nexport function resolveRequiredAcks(\n useCase: ApprovalUseCaseDto,\n requested?: number,\n): number {\n if (requested === undefined) {\n return Math.max(useCase.defaultAcks, useCase.minAcks)\n }\n return Math.max(Math.trunc(requested), useCase.minAcks)\n}\n\n/**\n * The four-eyes rule.\n *\n * The bans are in the order a person meets them, and each one has its own\n * message: \"you already approved this\" and \"you cannot approve your own\n * request\" are different mistakes, and one message for both helps nobody.\n *\n * Each of the two bans on a person reads BOTH identities: the `sub` of the\n * token, and the email. See `ApprovalActorView.email` for why one of them is\n * not enough.\n */\nexport function canAcknowledge(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n now: Date,\n): ApprovalDecision {\n if (!hasEveryPermission(actor, job.requiredPermissions)) {\n return deny('forbidden', 'You cannot approve this request.')\n }\n if (isExpired(job, now)) {\n return deny(\n 'expired',\n 'This request expired and can no longer be approved.',\n )\n }\n if (job.status !== 'pending') {\n return deny(\n 'not-pending',\n `This request is ${job.status} and can no longer be approved.`,\n )\n }\n if (isSameActor(job.createdBy, actor)) {\n return deny(\n 'self-approval',\n 'You opened this request, so you cannot approve it.',\n )\n }\n if (isOverrideGrantee(job, actor)) {\n return deny(\n 'self-approval',\n 'This request gives you an override grant, so you cannot approve it.',\n )\n }\n if (job.acks.some((ack) => isSameActor(ack, actor))) {\n return deny('already-acknowledged', 'You already approved this request.')\n }\n return ALLOWED\n}\n\n/**\n * A rejection needs the same permission as an acknowledgement, and a reason.\n *\n * Two people answer a request, and each one has ONE verb. Somebody else\n * approves or rejects it; the person who opened it withdraws it. The creator is\n * refused here for the same reason `canAcknowledge` refuses them: one person\n * must not be both sides of a four-eyes decision. The message names the button\n * that they do have, and the trail loses nothing, because a withdrawal writes\n * its reason into the same field.\n *\n * The ORDER of the checks is the order that a person meets them, and the state\n * of the request comes before the reason. A closed request must answer\n * \"already closed\" whatever the caller typed: with the reason first, a page\n * that had no reason yet read `no-reason` from a rejected request, and the\n * Reject button of control-frontend stayed enabled on a request that nothing\n * could reject any more.\n */\nexport function canReject(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n now: Date,\n reason: string,\n): ApprovalDecision {\n if (!hasEveryPermission(actor, job.requiredPermissions)) {\n return deny('forbidden', 'You cannot reject this request.')\n }\n if (isExpired(job, now)) {\n return deny(\n 'expired',\n 'This request expired and can no longer be rejected.',\n )\n }\n if (job.status !== 'pending') {\n return deny(\n 'not-pending',\n `This request is ${job.status} and can no longer be rejected.`,\n )\n }\n if (isSameActor(job.createdBy, actor)) {\n return deny(\n 'self-rejection',\n 'You opened this request, so withdraw it instead of rejecting it.',\n )\n }\n if (reason.trim().length === 0) {\n return deny('no-reason', 'Give a reason to reject this request.')\n }\n return ALLOWED\n}\n\n/**\n * Only the person who opened a request can take it back.\n *\n * BOTH identities, as every other rule of this file reads them. One person can\n * hold two Auth0 identities with two different `sub` values, and a rule that\n * read the id alone refused the creator their own withdrawal as soon as the\n * browser and the service resolved that id from two different tokens.\n */\nexport function canWithdraw(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n now: Date,\n): ApprovalDecision {\n if (!isSameActor(job.createdBy, actor)) {\n return deny(\n 'not-creator',\n 'Only the person who opened a request can withdraw it.',\n )\n }\n if (isExpired(job, now)) {\n return deny(\n 'expired',\n 'This request expired and can no longer be withdrawn.',\n )\n }\n if (job.status !== 'pending') {\n return deny(\n 'not-pending',\n `This request is ${job.status} and can no longer be withdrawn.`,\n )\n }\n return ALLOWED\n}\n\n/**\n * Runs a request that has its approvals.\n *\n * This is the button of the explicit mode. `failed` is executable again,\n * because a failure is often a problem of the system that is now repaired, and\n * asking for the approvals a second time helps nobody. Both run only inside\n * the run window, see `EXECUTE_WINDOW_DAYS`.\n *\n * ANY holder of the permission may press it, and not only the person who\n * opened the request. The decision was made when the request reached\n * `approved`, when the row got all the approvals that the request asks for.\n * One of them can be the approval of the opener at create (see\n * `opensWithOwnApproval`), and `canAcknowledge` keeps each person to one\n * approval. The button only carries out what these people already agreed to.\n * Holding the button to the creator would let one Camundi\n * on holiday freeze an approved action, and a use case that must not run\n * without its author has `executionMode: 'auto'` instead.\n *\n * Who PRESSED it and who ASKED for it are two different facts, and both are\n * kept: the audit trail of control-backend records the actor of the run, and\n * an action that names a person to another service names the creator. See\n * `onBehalfOf` of `extend-trial`.\n */\nexport function canExecute(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n // A default, because the package is published and a caller from before\n // the run window passes two arguments.\n now: Date = new Date(),\n): ApprovalDecision {\n // The grantee may end their own grant early, with no permission. Ending a\n // grant takes power away, so it needs no second person.\n // A `failed` revoke counts too: the reconciler does not run a failed row\n // again, so the grantee must be able to retry it.\n const endsOwnGrant =\n (job.status === 'scheduled' || job.status === 'failed') &&\n job.type === APPROVAL_USE_CASE_TYPES.revokeApprovalOverride &&\n isOverrideGrantee(job, actor)\n if (!endsOwnGrant && !hasEveryPermission(actor, job.requiredPermissions)) {\n return deny('forbidden', 'You cannot run this request.')\n }\n // The grantee cannot run the request that gives them their grant, as\n // `canAcknowledge` refuses their approval. A retry of a `failed` grant would\n // let them pick the time when the grant starts.\n if (\n job.type === APPROVAL_USE_CASE_TYPES.grantApprovalOverride &&\n isOverrideGrantee(job, actor)\n ) {\n return deny(\n 'self-approval',\n 'This request gives you an override grant, so you cannot run it.',\n )\n }\n // control-backend writes `expired` before it answers a read, so the row\n // that a person sees is usually already `expired` and not past its window.\n if (job.status === 'expired') {\n return deny('expired', 'This request is expired. Open a new request.')\n }\n // A `scheduled` request runs by itself at `runAt`. To run it before that\n // time needs the same permissions as any other run.\n if (\n job.status !== 'approved' &&\n job.status !== 'failed' &&\n job.status !== 'scheduled'\n ) {\n return deny(\n 'not-executable',\n `This request is ${job.status} and cannot be run.`,\n )\n }\n if (isRunWindowClosed(job, now)) {\n return deny(\n 'expired',\n `The approvals of this request are older than ${EXECUTE_WINDOW_DAYS} days. Open a new request.`,\n )\n }\n return ALLOWED\n}\n\n/**\n * Why a request that an override approved can no longer run: the grant that\n * the override used ended. The revoke of a grant writes it as `closedReason`\n * on each such request, and `canRunOverridden` answers it.\n */\nexport const OVERRIDE_GRANT_ENDED_MESSAGE =\n 'The approval override grant that ran this request ended. Open a new request.'\n\n/**\n * Reports whether a request that an override ran can still run.\n *\n * An override of a request in the explicit mode moves it to `approved`, and a\n * person runs it later. A failed run can also run again. The grant is the only\n * thing that stood in for the approvals, so each run needs it to be active\n * still: a revoke or the end of the grant stops the request too.\n *\n * `grant` is the grant that the override used (`job.overrideGrantId`), which\n * the caller reads from the grant table at the run. A later grant of the same\n * person does not count: a revoke ends the requests that its grant ran, and a\n * new grant must not bring them back. A request with no override is not\n * affected. A type that joined `APPROVAL_OVERRIDE_DENYLIST` after the\n * override needs its approvals, as `canOverride` says.\n */\nexport function canRunOverridden(\n job: Pick<ApprovalJobDto, 'type' | 'overriddenBy'>,\n grant: Pick<ApprovalOverrideGrantDto, 'expiresAt' | 'revokedAt'> | undefined,\n now: Date,\n): ApprovalDecision {\n if (!job.overriddenBy) {\n return ALLOWED\n }\n if (!isApprovalOverridable(job.type)) {\n return deny(\n 'not-overridable',\n 'An override cannot run this type of request. It needs its approvals.',\n )\n }\n if (isOverrideGrantActive(grant, now)) {\n return ALLOWED\n }\n return deny('no-override-grant', OVERRIDE_GRANT_ENDED_MESSAGE)\n}\n\n/**\n * Runs a `pending` request with an approval override grant, in place of the\n * approvals that it still needs.\n *\n * `grant` is the active grant of the actor. The caller reads it from the\n * grant table at every call, and never from a token: a token keeps its\n * permissions until it expires, and a revoked grant must stop at once.\n *\n * The creator may override their own request, because that is what a grant\n * is for. The actor still needs the permissions of the request: a grant\n * takes the place of the second person, and not of the permission. A use case\n * in `APPROVAL_OVERRIDE_DENYLIST` always needs its approvals.\n */\nexport function canOverride(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n now: Date,\n args: {\n grant?: Pick<\n ApprovalOverrideGrantDto,\n 'userId' | 'email' | 'expiresAt' | 'revokedAt'\n >\n reason: string\n },\n): ApprovalDecision {\n if (\n !args.grant ||\n !isOverrideGrantActive(args.grant, now) ||\n !isSameActor(args.grant, actor)\n ) {\n return deny(\n 'no-override-grant',\n 'You hold no active approval override grant.',\n )\n }\n if (!isApprovalOverridable(job.type)) {\n return deny(\n 'not-overridable',\n 'An override cannot run this type of request. It needs its approvals.',\n )\n }\n if (!hasEveryPermission(actor, job.requiredPermissions)) {\n return deny('forbidden', 'You cannot run this request.')\n }\n if (isExpired(job, now)) {\n return deny('expired', 'This request expired and can no longer be run.')\n }\n if (job.status !== 'pending') {\n return deny(\n 'not-pending',\n `This request is ${job.status} and cannot be run with an override.`,\n )\n }\n if (args.reason.trim().length === 0) {\n return deny(\n 'no-reason',\n 'Give a reason to run this request with an override.',\n )\n }\n return ALLOWED\n}\n\n/**\n * How many days a request can run after its last approval.\n *\n * The approvers agreed to the request as the world was on that day. Later the\n * facts can change: an organization in trial becomes a paying customer. A\n * request that is older than this window needs new approvals. The rule is here\n * and not in each use case, so a new use case cannot forget it.\n *\n * A `failed` request counts from the same day. A retry is for a problem of the\n * system that is now repaired, not for a run weeks later.\n */\nexport const EXECUTE_WINDOW_DAYS = 7\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\n/**\n * Reports the end of the run window of a request.\n *\n * The window starts at the last decision that let the request run: the last\n * approval, the override (`overriddenAt`), or the time of a `scheduled`\n * request (`runAt`). A use case that needs zero approvals has none of them,\n * so its window starts when the request was opened.\n */\nexport function runWindowEnd(job: ApprovalJobDto): Date {\n const decisions = [\n ...job.acks.map((ack) => ack.date),\n job.overriddenAt,\n job.runAt,\n ]\n const start = decisions.reduce(\n (latest, date) =>\n date === undefined ? latest : Math.max(latest, new Date(date).getTime()),\n new Date(job.createdAt).getTime(),\n )\n return new Date(start + EXECUTE_WINDOW_DAYS * DAY_MS)\n}\n\n/**\n * Reports whether an `approved` or `failed` request is past its run window.\n *\n * It fails closed: a date that does not parse gives NaN, and NaN closes the\n * window. The window guards a privileged action.\n */\nexport function isRunWindowClosed(job: ApprovalJobDto, now: Date): boolean {\n if (job.status !== 'approved' && job.status !== 'failed') {\n return false\n }\n return !(runWindowEnd(job).getTime() > now.getTime())\n}\n\n/**\n * Reports whether a request ran, failed, and will not run again by itself.\n *\n * That is a `failed` request, or a failed request that control-backend then\n * wrote as `expired` at the end of its run window. Only a run raises\n * `attempts`, and an `executed` request never expires.\n */\nexport function hasFailedRun(job: ApprovalJobDto): boolean {\n return (\n job.status === 'failed' || (job.status === 'expired' && job.attempts > 0)\n )\n}\n"],
|
|
4
|
+
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport { UNKNOWN_ACTOR_EMAIL } from '../constants/misc.const.js'\nimport type {\n ApprovalJobDto,\n ApprovalOverrideGrantDto,\n ApprovalUseCaseDto,\n} from '../dtos/ApprovalJob.dto.js'\nimport { AccountsPermissions } from '../permissions/accounts.permissions.js'\nimport { ConsolePermissions } from '../permissions/console.permissions.js'\nimport {\n APPROVAL_USE_CASE_TYPES,\n isApprovalOverridable,\n} from './use-cases.const.js'\n\n/**\n * The rules of the approval mechanism, as pure functions.\n *\n * Three consumers run this file: control-backend decides whether to reject a\n * request, control-frontend decides whether to disable a button, and cloudbot\n * decides whether to answer. One copy means the button and the endpoint can\n * never disagree.\n *\n * Two choices in the signatures carry the design:\n *\n * - The actor is an interface with a `has` method. The backend holds an array\n * of Auth0 claims, and `useSession()` in the frontend gives a flat record of\n * booleans. Neither side has to convert to the shape of the other.\n * - `now` is a parameter. The expiry is lazy, so a stored `pending` request can\n * be expired already. A parameter makes a difference between the two clocks\n * an input that a test can set, and not a silent disagreement.\n *\n * No function here does I/O or returns a promise. The browser call site is what\n * enforces that, and it also stops a later use case from turning a list of 50\n * rows into 200 network calls.\n */\n\n/** Who is asking. See the note above on why this is an interface. */\nexport interface ApprovalActorView {\n userId: string\n /**\n * The email of the actor. It is the SECOND identity of the four-eyes rule.\n *\n * `userId` alone is not enough. One person can hold more than one identity in\n * Auth0 \u2014 a connection through SSO and a connection through a database, or an\n * account that was made again \u2014 and each one carries a different `sub`. The\n * same human then opens a request with one identity and approves it with the\n * other, which is the rule defeated.\n *\n * It is optional because a token can carry no email. See\n * `isSameActorEmail` for what that means for the comparison.\n */\n email?: string\n has(permission: string): boolean\n /**\n * True when the actor reads every request that `restrictedRead` does not\n * hide, and has no other right. It is a READ stand-in for `READ_ALL` that\n * `has` does not answer, so a rule that opens or acts on a request never\n * sees it. Only control-backend sets it, for a machine token with\n * `M2M_CONTROL_READ`.\n */\n readsAll?: boolean\n}\n\n/**\n * Builds the `has` of an actor from the permissions that the actor holds.\n *\n * `ConsolePermissions.APPROVALS_ALL_USE_CASES` stands in for every permission\n * that a use case asks for. Both actor builders call this function, the one of\n * control-backend and the one of the browser, so the button and the route\n * agree on it. A rule that reads `actor.has` needs no change for it, and nor\n * does a use case that a later change adds.\n */\nexport function approvalPermissionCheck(\n held: ReadonlySet<string>,\n): (permission: string) => boolean {\n const all = held.has(ConsolePermissions.APPROVALS_ALL_USE_CASES)\n return (permission) => all || held.has(permission)\n}\n\n/**\n * Reports whether two email addresses name one person.\n *\n * Two values that are absent, empty, or `UNKNOWN_ACTOR_EMAIL` are NOT one\n * person. A token with no email would otherwise make every actor equal to\n * every other actor, and the rule would refuse everybody.\n *\n * The comparison removes the spaces and the case. Auth0 gives the address as\n * the identity provider wrote it, so `A.B@camunda.com` and `a.b@camunda.com`\n * are one mailbox and must not pass as two people.\n */\nexport function isSameActorEmail(one?: string, other?: string): boolean {\n const left = comparableActorEmail(one)\n return left.length > 0 && left === comparableActorEmail(other)\n}\n\n/**\n * The address in the one form that a comparison may use.\n *\n * An absent address, an empty one and `UNKNOWN_ACTOR_EMAIL` all become an\n * empty string, because none of the three names a person. The spaces and the\n * case go as well: Auth0 gives the address as the identity provider wrote it.\n */\nfunction comparableActorEmail(value?: string): string {\n const trimmed = value?.trim().toLowerCase() ?? ''\n return trimmed === UNKNOWN_ACTOR_EMAIL ? '' : trimmed\n}\n\n/**\n * Reports whether one identity of a request names the actor.\n *\n * The `sub` of the token OR the email, because one person can hold more than\n * one Auth0 identity. Every rule that asks \"is this the same human?\" reads both\n * through this function, so a rule cannot forget the second half: `canWithdraw`\n * did, and it refused a creator whose browser and whose service resolved the\n * id from two different tokens.\n */\nexport function isSameActor(\n identity: { userId: string; email?: string },\n actor: ApprovalActorView,\n): boolean {\n return (\n identity.userId === actor.userId ||\n isSameActorEmail(identity.email, actor.email)\n )\n}\n\n/**\n * Reports whether this actor carries an address that names a person.\n *\n * A machine-to-machine token carries none: accounts-ng builds the\n * permissions of such a token from its `permissions` claim alone, and there is\n * no person behind it. See `creatorEmailRequired` of the use case.\n */\nexport function hasActorEmail(actor: ApprovalActorView): boolean {\n return comparableActorEmail(actor.email).length > 0\n}\n\n/**\n * Why an action is not allowed.\n *\n * The code is for a program: control-backend maps it to a status, and the\n * frontend can branch on it. The message is for a person, and it is shown as\n * written.\n */\nexport type ApprovalDenialCode =\n | 'forbidden'\n | 'not-pending'\n | 'self-approval'\n | 'self-rejection'\n | 'already-acknowledged'\n | 'expired'\n | 'not-creator'\n | 'not-executable'\n | 'no-reason'\n | 'too-few-acks'\n | 'no-creator-email'\n | 'no-override-grant'\n | 'not-overridable'\n\nexport type ApprovalDecision =\n | { allowed: true }\n | { allowed: false; code: ApprovalDenialCode; message: string }\n\nconst ALLOWED: ApprovalDecision = { allowed: true }\n\nfunction deny(code: ApprovalDenialCode, message: string): ApprovalDecision {\n return { allowed: false, code, message }\n}\n\n/**\n * Reports whether the time to answer a request has passed.\n *\n * Only a `pending` request expires. A request that already reached an end state\n * keeps that state, because \"expired\" would lose the answer that was given.\n */\nexport function isExpired(job: ApprovalJobDto, now: Date): boolean {\n return (\n job.status === 'pending' &&\n new Date(job.expiresAt).getTime() <= now.getTime()\n )\n}\n\n/**\n * Reports the status to show. It is `expired` once the time to answer has\n * passed, or once the run window of an `approved` or `failed` request has\n * ended. control-backend writes both, and this shows them before the write.\n */\nexport function effectiveStatus(\n job: ApprovalJobDto,\n now: Date,\n): ApprovalJobDto['status'] {\n return isExpired(job, now) || isRunWindowClosed(job, now)\n ? 'expired'\n : job.status\n}\n\n/** Reports how many more acknowledgements the request needs. */\nexport function remainingAcks(job: ApprovalJobDto): number {\n return Math.max(0, job.requiredAcks - job.acks.length)\n}\n\n/**\n * Reports whether the actor holds EVERY permission of the set.\n *\n * Every, and not one of them. A payload that raises the guard adds a\n * permission, so \"one of them\" would let the base permission alone carry a\n * request that the extra permission exists to stop.\n *\n * An EMPTY set is held by nobody. That is the opposite of what `Array.every`\n * answers, and it is deliberate: this function guards a privileged action, so\n * the empty case must fail closed. A row with no permissions is not a row that\n * everybody may run \u2014 it is a row that lost its guard, through a migration\n * that did not backfill it or a write that went around the service. Every use\n * case builds a set of at least one, so no real request meets this branch.\n */\nexport function hasEveryPermission(\n actor: ApprovalActorView,\n permissions: string[],\n): boolean {\n if (permissions.length === 0) {\n return false\n }\n return permissions.every((permission) => actor.has(permission))\n}\n\n/**\n * What a person must hold to act on a request.\n *\n * A request carries its own set, because a payload can raise the guard. A use\n * case that never does has a set of one, and it is the base permission.\n */\nexport function requiredPermissionsOf(job: ApprovalJobDto): string[] {\n return job.requiredPermissions\n}\n\n/**\n * True when this actor can read EVERY request of the use case.\n *\n * The actor holds the base permission of the use case, or holds `READ_ALL`\n * (`aara`). `aara` is the baseline read gate of Control, so its holders read\n * the requests of every use case by default. A use case with `restrictedRead`\n * leaves `aara` out. The list filters by this rule in SQL. `canView` adds the\n * requests that the actor opened, and the override grantee.\n */\nexport function canReadUseCase(\n useCase: Pick<ApprovalUseCaseDto, 'requiredPermission' | 'restrictedRead'>,\n actor: ApprovalActorView,\n): boolean {\n return (\n actor.has(useCase.requiredPermission) ||\n (useCase.restrictedRead !== true &&\n (actor.has(AccountsPermissions.READ_ALL) || actor.readsAll === true))\n )\n}\n\n/**\n * Who can READ a request.\n *\n * The person who can act on it, the one who opened it, and a holder of `aara`\n * (see `canReadUseCase`). A Camundi who is none of these has no reason to read\n * which customer somebody proposed to expire, so the list and the detail both\n * hide it.\n *\n * The rule reads the BASE permission of the use case and not the effective set\n * of the request. A payload that raises the guard raises who can APPROVE, and\n * not who can look: a generation update with the yolo flag is visible to\n * everybody who can approve a plain one, and only the yolo permission runs it.\n * The list filters by use case in SQL, which is what makes one page of rows\n * the same page that a person is allowed to read.\n */\nexport function canView(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n useCase: ApprovalUseCaseDto,\n): ApprovalDecision {\n if (\n canReadUseCase(useCase, actor) ||\n isSameActor(job.createdBy, actor) ||\n isOverrideGrantee(job, actor)\n ) {\n return ALLOWED\n }\n return deny('forbidden', 'You cannot see this request.')\n}\n\n/**\n * The person that a request of the two override use cases names, or\n * `undefined` for every other request.\n *\n * Four rules read it. The grantee cannot approve their own grant, also not\n * when they open it (`opensWithOwnApproval`), the grantee can read both\n * requests, and the grantee can end their own grant before its time.\n */\nexport function overrideGranteeOf(\n job: Pick<ApprovalJobDto, 'type' | 'payload'>,\n): { userId: string; email?: string } | undefined {\n if (\n job.type !== APPROVAL_USE_CASE_TYPES.grantApprovalOverride &&\n job.type !== APPROVAL_USE_CASE_TYPES.revokeApprovalOverride\n ) {\n return undefined\n }\n const { granteeUserId, granteeEmail } = job.payload\n if (typeof granteeUserId !== 'string' && typeof granteeEmail !== 'string') {\n return undefined\n }\n return {\n userId: typeof granteeUserId === 'string' ? granteeUserId : '',\n email: typeof granteeEmail === 'string' ? granteeEmail : undefined,\n }\n}\n\nfunction isOverrideGrantee(\n job: Pick<ApprovalJobDto, 'type' | 'payload'>,\n actor: ApprovalActorView,\n): boolean {\n const grantee = overrideGranteeOf(job)\n return grantee !== undefined && isSameActor(grantee, actor)\n}\n\n/**\n * Reports whether an approval override grant lets its holder act now.\n *\n * It fails closed: an absent grant, a revoked one, and a date that does not\n * parse are all inactive. control-backend reads the grant from its table at\n * every call. A token never carries it.\n */\nexport function isOverrideGrantActive(\n grant: Pick<ApprovalOverrideGrantDto, 'expiresAt' | 'revokedAt'> | undefined,\n now: Date,\n): boolean {\n if (!grant || grant.revokedAt) {\n return false\n }\n return new Date(grant.expiresAt).getTime() > now.getTime()\n}\n\n/**\n * The permissions that open a request of this use case. Any one of them is\n * enough. Returns `[]` when the field is absent or empty. `canCreate` tells\n * them apart: absent opens to anybody signed in, empty to nobody.\n */\nexport function createPermissionsOf(\n useCase: Pick<ApprovalUseCaseDto, 'createPermission'>,\n): string[] {\n const { createPermission } = useCase\n if (createPermission === undefined) {\n return []\n }\n return typeof createPermission === 'string'\n ? [createPermission]\n : [...createPermission]\n}\n\n/**\n * Who can OPEN a request, and with what.\n *\n * `createPermission` is what keeps the pool that asks as small as the pool that\n * approves. A use case that leaves it absent says the opposite on purpose: the\n * approvals are the guard, and anybody signed in can propose the action.\n *\n * The two checks after it are about the request and not about the person. A\n * count below the floor of the use case, and a missing reason, are both a 400\n * and not a 403, so the words say which one the caller must repair.\n */\nexport function canCreate(\n actor: ApprovalActorView,\n useCase: ApprovalUseCaseDto,\n request: {\n reason?: string\n requiredAcks?: number\n /**\n * The effective permissions of the payload, from `permissionsFor`.\n *\n * Absent means \"the base permission alone\", which is what most use cases\n * build. Only the permissions ABOVE the base one gate opening a request:\n * see the note in the body.\n */\n requiredPermissions?: string[]\n } = {},\n): ApprovalDecision {\n // The message NAMES the permission. \"You cannot open this request\" is true\n // and useless: a Camundi who reads it cannot tell a missing permission from\n // a rule they never heard of, and the detail page names the permissions of\n // a request in the same way.\n const createPermissions = createPermissionsOf(useCase)\n // An empty list is a mistake of the use case. It must close the request,\n // and not open it to everyone, so it is checked on the DTO and not on the\n // list that `createPermissionsOf` returns.\n if (\n useCase.createPermission !== undefined &&\n !createPermissions.some((permission) => actor.has(permission))\n ) {\n return deny(\n 'forbidden',\n createPermissions.length === 0\n ? 'Nobody can open this request, because its use case lists no permission.'\n : `Opening this request needs ${createPermissions.join(' or ')}, and ${\n createPermissions.length > 1\n ? 'you hold none of them'\n : 'you do not hold it'\n }.`,\n )\n }\n // What the PAYLOAD raised, on top of the base permission of the use case.\n // A bulk generation update with the yolo flag needs the yolo permission, and\n // without this check a person who holds the base permission alone could open\n // one. They could not approve it and could not run it, so it is not an\n // escalation \u2014 it is a request that its own author is not allowed to make,\n // waiting in the queue of the people who are.\n //\n // The BASE permission is deliberately not checked here. `createPermission`\n // above is the only gate on the person, and a use case that leaves it absent\n // means that anybody signed in can propose the action. Checking the base\n // permission too would take that choice away from every use case.\n const raised = (request.requiredPermissions ?? []).filter(\n (permission) => permission !== useCase.requiredPermission,\n )\n if (raised.length > 0 && !hasEveryPermission(actor, raised)) {\n return deny(\n 'forbidden',\n `This payload needs ${raised.join(' and ')}, and you do not hold it.`,\n )\n }\n // A request that needs no approval RUNS when it is opened, so the person who\n // opens it must hold what running it needs. Every other use case leaves this\n // to the approvals, which is why the base permission is not checked above.\n // With a floor of zero there is no approval to leave it to.\n const toRun = request.requiredPermissions ?? [useCase.requiredPermission]\n // A service that opens a request of its own use case holds the\n // `createPermission` checked above, and that is the guard of the run. Without\n // a `createPermission` there is no such guard, so the flag lifts nothing.\n const openedBySystem = useCase.openedBySystem && createPermissions.length > 0\n if (\n resolveRequiredAcks(useCase, request.requiredAcks) === 0 &&\n !useCase.openToEveryone &&\n !openedBySystem &&\n !hasEveryPermission(actor, toRun)\n ) {\n // The message NAMES the permission, and it says why opening needs it. A\n // Camundi who reads \"you cannot open this request\" for an action that\n // needs no approval cannot tell which of the two rules refused them.\n return deny(\n 'forbidden',\n `This request needs no approval, so opening it runs it. That needs ` +\n `${toRun.join(' and ')}, and you do not hold it.`,\n )\n }\n // The action of this use case carries the address of the person who asked,\n // so a caller with no address must be refused HERE. The alternative is a\n // request that looks ordinary, collects its approvals over days, and then\n // fails because the other service cannot find a user called \"unknown\".\n if (useCase.creatorEmailRequired && !hasActorEmail(actor)) {\n return deny(\n 'no-creator-email',\n 'This action needs the email address of the person who asks for it, ' +\n 'and your session carries none. Sign in as a person to open this ' +\n 'request.',\n )\n }\n if (\n needsReason(actor, useCase, {\n requiredAcks: request.requiredAcks,\n requiredPermissions: toRun,\n }) &&\n (request.reason ?? '').trim().length === 0\n ) {\n return deny('no-reason', 'Give a reason to open this request.')\n }\n if (\n request.requiredAcks !== undefined &&\n request.requiredAcks < useCase.minAcks\n ) {\n return deny(\n 'too-few-acks',\n `This action needs at least ${useCase.minAcks} approvals.`,\n )\n }\n return ALLOWED\n}\n\n/**\n * Reports whether the opener approves a new request when it is created.\n *\n * The opener approves when the request needs an approval and the opener holds\n * every run permission of it. `APPROVAL_RULES` counts this approval. A request\n * that needs no approval gets none, so its `approvedBy` stays empty.\n *\n * When `request` is given, the grantee of an approval override grant does not\n * approve the grant that they open for themselves, as `canAcknowledge`\n * refuses their approval later. Every approval of such a request then comes\n * from another person.\n */\nexport function opensWithOwnApproval(\n actor: ApprovalActorView,\n requiredAcks: number,\n requiredPermissions: string[],\n request?: Pick<ApprovalJobDto, 'type' | 'payload'>,\n): boolean {\n if (request !== undefined && isOverrideGrantee(request, actor)) {\n return false\n }\n return requiredAcks > 0 && hasEveryPermission(actor, requiredPermissions)\n}\n\n/**\n * Reports whether a new request needs a reason.\n *\n * A request needs no reason when its opener holds every run permission and\n * needs no second person. Nobody else reads the reason before the action\n * runs, and the audit record names the opener.\n */\nexport function needsReason(\n actor: ApprovalActorView,\n useCase: ApprovalUseCaseDto,\n request: { requiredAcks?: number; requiredPermissions?: string[] } = {},\n): boolean {\n if (!useCase.reasonRequired) {\n return false\n }\n return !(\n resolveRequiredAcks(useCase, request.requiredAcks) <= 1 &&\n hasEveryPermission(\n actor,\n request.requiredPermissions ?? [useCase.requiredPermission],\n )\n )\n}\n\n/**\n * The approvals that a new request asks for.\n *\n * The caller names a number or names none. A number below the floor is refused\n * by `canCreate`, and this function holds the answer inside the range anyway:\n * the two run in the same call, and a floor that only one of them knows is a\n * floor that a later caller can step over.\n */\nexport function resolveRequiredAcks(\n useCase: ApprovalUseCaseDto,\n requested?: number,\n): number {\n if (requested === undefined) {\n return Math.max(useCase.defaultAcks, useCase.minAcks)\n }\n return Math.max(Math.trunc(requested), useCase.minAcks)\n}\n\n/**\n * The four-eyes rule.\n *\n * The bans are in the order a person meets them, and each one has its own\n * message: \"you already approved this\" and \"you cannot approve your own\n * request\" are different mistakes, and one message for both helps nobody.\n *\n * Each of the two bans on a person reads BOTH identities: the `sub` of the\n * token, and the email. See `ApprovalActorView.email` for why one of them is\n * not enough.\n */\nexport function canAcknowledge(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n now: Date,\n): ApprovalDecision {\n if (!hasEveryPermission(actor, job.requiredPermissions)) {\n return deny('forbidden', 'You cannot approve this request.')\n }\n if (isExpired(job, now)) {\n return deny(\n 'expired',\n 'This request expired and can no longer be approved.',\n )\n }\n if (job.status !== 'pending') {\n return deny(\n 'not-pending',\n `This request is ${job.status} and can no longer be approved.`,\n )\n }\n if (isSameActor(job.createdBy, actor)) {\n return deny(\n 'self-approval',\n 'You opened this request, so you cannot approve it.',\n )\n }\n if (isOverrideGrantee(job, actor)) {\n return deny(\n 'self-approval',\n 'This request gives you an override grant, so you cannot approve it.',\n )\n }\n if (job.acks.some((ack) => isSameActor(ack, actor))) {\n return deny('already-acknowledged', 'You already approved this request.')\n }\n return ALLOWED\n}\n\n/**\n * A rejection needs the same permission as an acknowledgement, and a reason.\n *\n * Two people answer a request, and each one has ONE verb. Somebody else\n * approves or rejects it; the person who opened it withdraws it. The creator is\n * refused here for the same reason `canAcknowledge` refuses them: one person\n * must not be both sides of a four-eyes decision. The message names the button\n * that they do have, and the trail loses nothing, because a withdrawal writes\n * its reason into the same field.\n *\n * The ORDER of the checks is the order that a person meets them, and the state\n * of the request comes before the reason. A closed request must answer\n * \"already closed\" whatever the caller typed: with the reason first, a page\n * that had no reason yet read `no-reason` from a rejected request, and the\n * Reject button of control-frontend stayed enabled on a request that nothing\n * could reject any more.\n */\nexport function canReject(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n now: Date,\n reason: string,\n): ApprovalDecision {\n if (!hasEveryPermission(actor, job.requiredPermissions)) {\n return deny('forbidden', 'You cannot reject this request.')\n }\n if (isExpired(job, now)) {\n return deny(\n 'expired',\n 'This request expired and can no longer be rejected.',\n )\n }\n if (job.status !== 'pending') {\n return deny(\n 'not-pending',\n `This request is ${job.status} and can no longer be rejected.`,\n )\n }\n if (isSameActor(job.createdBy, actor)) {\n return deny(\n 'self-rejection',\n 'You opened this request, so withdraw it instead of rejecting it.',\n )\n }\n if (reason.trim().length === 0) {\n return deny('no-reason', 'Give a reason to reject this request.')\n }\n return ALLOWED\n}\n\n/**\n * Only the person who opened a request can take it back.\n *\n * BOTH identities, as every other rule of this file reads them. One person can\n * hold two Auth0 identities with two different `sub` values, and a rule that\n * read the id alone refused the creator their own withdrawal as soon as the\n * browser and the service resolved that id from two different tokens.\n */\nexport function canWithdraw(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n now: Date,\n): ApprovalDecision {\n if (!isSameActor(job.createdBy, actor)) {\n return deny(\n 'not-creator',\n 'Only the person who opened a request can withdraw it.',\n )\n }\n if (isExpired(job, now)) {\n return deny(\n 'expired',\n 'This request expired and can no longer be withdrawn.',\n )\n }\n if (job.status !== 'pending') {\n return deny(\n 'not-pending',\n `This request is ${job.status} and can no longer be withdrawn.`,\n )\n }\n return ALLOWED\n}\n\n/**\n * Runs a request that has its approvals.\n *\n * This is the button of the explicit mode. `failed` is executable again,\n * because a failure is often a problem of the system that is now repaired, and\n * asking for the approvals a second time helps nobody. Both run only inside\n * the run window, see `EXECUTE_WINDOW_DAYS`.\n *\n * ANY holder of the permission may press it, and not only the person who\n * opened the request. The decision was made when the request reached\n * `approved`, when the row got all the approvals that the request asks for.\n * One of them can be the approval of the opener at create (see\n * `opensWithOwnApproval`), and `canAcknowledge` keeps each person to one\n * approval. The button only carries out what these people already agreed to.\n * Holding the button to the creator would let one Camundi\n * on holiday freeze an approved action, and a use case that must not run\n * without its author has `executionMode: 'auto'` instead.\n *\n * Who PRESSED it and who ASKED for it are two different facts, and both are\n * kept: the audit trail of control-backend records the actor of the run, and\n * an action that names a person to another service names the creator. See\n * `onBehalfOf` of `extend-trial`.\n */\nexport function canExecute(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n // A default, because the package is published and a caller from before\n // the run window passes two arguments.\n now: Date = new Date(),\n): ApprovalDecision {\n // The grantee may end their own grant early, with no permission. Ending a\n // grant takes power away, so it needs no second person.\n // A `failed` revoke counts too: the reconciler does not run a failed row\n // again, so the grantee must be able to retry it.\n const endsOwnGrant =\n (job.status === 'scheduled' || job.status === 'failed') &&\n job.type === APPROVAL_USE_CASE_TYPES.revokeApprovalOverride &&\n isOverrideGrantee(job, actor)\n if (!endsOwnGrant && !hasEveryPermission(actor, job.requiredPermissions)) {\n return deny('forbidden', 'You cannot run this request.')\n }\n // The grantee cannot run the request that gives them their grant, as\n // `canAcknowledge` refuses their approval. A retry of a `failed` grant would\n // let them pick the time when the grant starts.\n if (\n job.type === APPROVAL_USE_CASE_TYPES.grantApprovalOverride &&\n isOverrideGrantee(job, actor)\n ) {\n return deny(\n 'self-approval',\n 'This request gives you an override grant, so you cannot run it.',\n )\n }\n // control-backend writes `expired` before it answers a read, so the row\n // that a person sees is usually already `expired` and not past its window.\n if (job.status === 'expired') {\n return deny('expired', 'This request is expired. Open a new request.')\n }\n // A `scheduled` request runs by itself at `runAt`. To run it before that\n // time needs the same permissions as any other run.\n if (\n job.status !== 'approved' &&\n job.status !== 'failed' &&\n job.status !== 'scheduled'\n ) {\n return deny(\n 'not-executable',\n `This request is ${job.status} and cannot be run.`,\n )\n }\n if (isRunWindowClosed(job, now)) {\n return deny(\n 'expired',\n `The approvals of this request are older than ${EXECUTE_WINDOW_DAYS} days. Open a new request.`,\n )\n }\n return ALLOWED\n}\n\n/**\n * Why a request that an override approved can no longer run: the grant that\n * the override used ended. The revoke of a grant writes it as `closedReason`\n * on each such request, and `canRunOverridden` answers it.\n */\nexport const OVERRIDE_GRANT_ENDED_MESSAGE =\n 'The approval override grant that ran this request ended. Open a new request.'\n\n/**\n * Reports whether a request that an override ran can still run.\n *\n * An override of a request in the explicit mode moves it to `approved`, and a\n * person runs it later. A failed run can also run again. The grant is the only\n * thing that stood in for the approvals, so each run needs it to be active\n * still: a revoke or the end of the grant stops the request too.\n *\n * `grant` is the grant that the override used (`job.overrideGrantId`), which\n * the caller reads from the grant table at the run. A later grant of the same\n * person does not count: a revoke ends the requests that its grant ran, and a\n * new grant must not bring them back. A request with no override is not\n * affected. A type that joined `APPROVAL_OVERRIDE_DENYLIST` after the\n * override needs its approvals, as `canOverride` says.\n */\nexport function canRunOverridden(\n job: Pick<ApprovalJobDto, 'type' | 'overriddenBy'>,\n grant: Pick<ApprovalOverrideGrantDto, 'expiresAt' | 'revokedAt'> | undefined,\n now: Date,\n): ApprovalDecision {\n if (!job.overriddenBy) {\n return ALLOWED\n }\n if (!isApprovalOverridable(job.type)) {\n return deny(\n 'not-overridable',\n 'An override cannot run this type of request. It needs its approvals.',\n )\n }\n if (isOverrideGrantActive(grant, now)) {\n return ALLOWED\n }\n return deny('no-override-grant', OVERRIDE_GRANT_ENDED_MESSAGE)\n}\n\n/**\n * Runs a `pending` request with an approval override grant, in place of the\n * approvals that it still needs.\n *\n * `grant` is the active grant of the actor. The caller reads it from the\n * grant table at every call, and never from a token: a token keeps its\n * permissions until it expires, and a revoked grant must stop at once.\n *\n * The creator may override their own request, because that is what a grant\n * is for. The actor still needs the permissions of the request: a grant\n * takes the place of the second person, and not of the permission. A use case\n * in `APPROVAL_OVERRIDE_DENYLIST` always needs its approvals.\n */\nexport function canOverride(\n job: ApprovalJobDto,\n actor: ApprovalActorView,\n now: Date,\n args: {\n grant?: Pick<\n ApprovalOverrideGrantDto,\n 'userId' | 'email' | 'expiresAt' | 'revokedAt'\n >\n reason: string\n },\n): ApprovalDecision {\n if (\n !args.grant ||\n !isOverrideGrantActive(args.grant, now) ||\n !isSameActor(args.grant, actor)\n ) {\n return deny(\n 'no-override-grant',\n 'You hold no active approval override grant.',\n )\n }\n if (!isApprovalOverridable(job.type)) {\n return deny(\n 'not-overridable',\n 'An override cannot run this type of request. It needs its approvals.',\n )\n }\n if (!hasEveryPermission(actor, job.requiredPermissions)) {\n return deny('forbidden', 'You cannot run this request.')\n }\n if (isExpired(job, now)) {\n return deny('expired', 'This request expired and can no longer be run.')\n }\n if (job.status !== 'pending') {\n return deny(\n 'not-pending',\n `This request is ${job.status} and cannot be run with an override.`,\n )\n }\n if (args.reason.trim().length === 0) {\n return deny(\n 'no-reason',\n 'Give a reason to run this request with an override.',\n )\n }\n return ALLOWED\n}\n\n/**\n * How many days a request can run after its last approval.\n *\n * The approvers agreed to the request as the world was on that day. Later the\n * facts can change: an organization in trial becomes a paying customer. A\n * request that is older than this window needs new approvals. The rule is here\n * and not in each use case, so a new use case cannot forget it.\n *\n * A `failed` request counts from the same day. A retry is for a problem of the\n * system that is now repaired, not for a run weeks later.\n */\nexport const EXECUTE_WINDOW_DAYS = 7\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\n/**\n * Reports the end of the run window of a request.\n *\n * The window starts at the last decision that let the request run: the last\n * approval, the override (`overriddenAt`), or the time of a `scheduled`\n * request (`runAt`). A use case that needs zero approvals has none of them,\n * so its window starts when the request was opened.\n */\nexport function runWindowEnd(job: ApprovalJobDto): Date {\n const decisions = [\n ...job.acks.map((ack) => ack.date),\n job.overriddenAt,\n job.runAt,\n ]\n const start = decisions.reduce(\n (latest, date) =>\n date === undefined ? latest : Math.max(latest, new Date(date).getTime()),\n new Date(job.createdAt).getTime(),\n )\n return new Date(start + EXECUTE_WINDOW_DAYS * DAY_MS)\n}\n\n/**\n * Reports whether an `approved` or `failed` request is past its run window.\n *\n * It fails closed: a date that does not parse gives NaN, and NaN closes the\n * window. The window guards a privileged action.\n */\nexport function isRunWindowClosed(job: ApprovalJobDto, now: Date): boolean {\n if (job.status !== 'approved' && job.status !== 'failed') {\n return false\n }\n return !(runWindowEnd(job).getTime() > now.getTime())\n}\n\n/**\n * Reports whether a request ran, failed, and will not run again by itself.\n *\n * That is a `failed` request, or a failed request that control-backend then\n * wrote as `expired` at the end of its run window. Only a run raises\n * `attempts`, and an `executed` request never expires.\n */\nexport function hasFailedRun(job: ApprovalJobDto): boolean {\n return (\n job.status === 'failed' || (job.status === 'expired' && job.attempts > 0)\n )\n}\n"],
|
|
5
5
|
"mappings": "AAMA,SAAS,2BAA2B;AAMpC,SAAS,2BAA2B;AACpC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AA4DA,SAAS,wBACd,MACiC;AACjC,QAAM,MAAM,KAAK,IAAI,mBAAmB,uBAAuB;AAC/D,SAAO,CAAC,eAAe,OAAO,KAAK,IAAI,UAAU;AACnD;AAaO,SAAS,iBAAiB,KAAc,OAAyB;AACtE,QAAM,OAAO,qBAAqB,GAAG;AACrC,SAAO,KAAK,SAAS,KAAK,SAAS,qBAAqB,KAAK;AAC/D;AASA,SAAS,qBAAqB,OAAwB;AACpD,QAAM,UAAU,OAAO,KAAK,EAAE,YAAY,KAAK;AAC/C,SAAO,YAAY,sBAAsB,KAAK;AAChD;AAWO,SAAS,YACd,UACA,OACS;AACT,SACE,SAAS,WAAW,MAAM,UAC1B,iBAAiB,SAAS,OAAO,MAAM,KAAK;AAEhD;AASO,SAAS,cAAc,OAAmC;AAC/D,SAAO,qBAAqB,MAAM,KAAK,EAAE,SAAS;AACpD;AA4BA,MAAM,UAA4B,EAAE,SAAS,KAAK;AAElD,SAAS,KAAK,MAA0B,SAAmC;AACzE,SAAO,EAAE,SAAS,OAAO,MAAM,QAAQ;AACzC;AAQO,SAAS,UAAU,KAAqB,KAAoB;AACjE,SACE,IAAI,WAAW,aACf,IAAI,KAAK,IAAI,SAAS,EAAE,QAAQ,KAAK,IAAI,QAAQ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zD,SACE,IAAI,WAAW,YAAa,IAAI,WAAW,aAAa,IAAI,WAAW;AAE3E;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -86,7 +86,7 @@ export declare const APPROVAL_OVERRIDE_DEFAULT_HOURS = 24;
|
|
|
86
86
|
*
|
|
87
87
|
* The list fails open: a use case that is not here IS overridable. Thus a new
|
|
88
88
|
* use case that deletes or that changes access must be added here. Its route
|
|
89
|
-
* in accounts-
|
|
89
|
+
* in accounts-ng or console-backend then refuses `overriddenBy` by
|
|
90
90
|
* itself: `approvalActorSchemaFor` of their `AdminApprovalsRouter.ts` reads
|
|
91
91
|
* this list.
|
|
92
92
|
*/
|
|
@@ -107,7 +107,7 @@ export declare const PERSONAL_ORGANIZATION_NAME_MIN_LENGTH = 3;
|
|
|
107
107
|
export declare const PERSONAL_ORGANIZATION_NAME_MAX_LENGTH = 100;
|
|
108
108
|
export type ApprovalUseCaseType = (typeof APPROVAL_USE_CASE_TYPES)[keyof typeof APPROVAL_USE_CASE_TYPES];
|
|
109
109
|
/**
|
|
110
|
-
* The shortest extension that accounts-
|
|
110
|
+
* The shortest extension that accounts-ng accepts.
|
|
111
111
|
*
|
|
112
112
|
* `POST /:orgId/extendtrial` refuses a date that is less than 14 days away
|
|
113
113
|
* when the body carries `onBehalfOf`, and it measures those 14 days when the
|
|
@@ -121,7 +121,7 @@ export type ApprovalUseCaseType = (typeof APPROVAL_USE_CASE_TYPES)[keyof typeof
|
|
|
121
121
|
*/
|
|
122
122
|
export declare const EXTEND_TRIAL_MIN_DAYS = 15;
|
|
123
123
|
/**
|
|
124
|
-
* The longest extension that accounts-
|
|
124
|
+
* The longest extension that accounts-ng accepts.
|
|
125
125
|
*
|
|
126
126
|
* The same route refuses a date more than 62 days away. 61 keeps the same
|
|
127
127
|
* margin as the floor above.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/approvals/use-cases.const.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport { AccountsPermissions } from '../permissions/accounts.permissions.js'\n\n/**\n * The names and the value ranges of the registered use cases.\n *\n * control-backend owns the registry, and a frontend reads it at run time\n * (`GET /api/approvals/use-cases`). Two things cannot wait for that answer:\n *\n * - **The identifier**, because a caller must NAME a use case to find it in the\n * registry, and to open a request of it.\n * - **The range of a payload field**, because a form holds the value before any\n * call goes out.\n *\n * Both live here, so the schema of the service and the form of the browser can\n * never hold different numbers.\n */\n\n/** The identifier of each use case, on the wire and in the table. */\nexport const APPROVAL_USE_CASE_TYPES = {\n sendToExpiredTrial: 'send-to-expired-trial',\n extendTrial: 'extend-trial',\n moveClusterOrg: 'move-cluster-org',\n // One use case for each type of a cluster bulk operation. The types need\n // different permissions and different approval counts, and a use case holds\n // one of each. See `cluster-bulk-operation.ts` beside this file.\n clusterBulkGenerationUpdate: 'cluster-bulk-generation-update',\n clusterBulkPlanUpdate: 'cluster-bulk-plan-update',\n clusterBulkPlanTypeUpdate: 'cluster-bulk-plan-type-update',\n clusterBulkSleepWakeup: 'cluster-bulk-sleep-wakeup',\n clusterBulkDeletion: 'cluster-bulk-deletion',\n clusterBulkSpecUpdate: 'cluster-bulk-spec-update',\n // The second group, behind `control.camundiApprovalFlow`.\n changePlatformRoles: 'change-platform-roles',\n deleteInternalBackup: 'delete-internal-backup',\n changeOrgLimits: 'change-org-limits',\n // The cluster reservations of one organization, behind\n // `control.camundiApprovalFlow`. It is not the enterprise contract: a\n // reservation change and a contract change are two requests. See\n // `change-org-reservations.ts` in control-backend.\n changeOrgReservations: 'change-org-reservations',\n deleteSsoConnection: 'delete-sso-connection',\n createSsoConnection: 'create-sso-connection',\n updateSsoConnection: 'update-sso-connection',\n changeSalesPlan: 'change-sales-plan',\n llmBudgetTopUp: 'llm-budget-top-up',\n requestInNegotiation: 'request-in-negotiation',\n // Behind its own flag `control.removeOrgMember`, and not\n // `control.camundiApprovalFlow`. See `REMOVE_ORG_MEMBER_FLAG`.\n removeOrgMember: 'remove-org-member',\n // The third group, behind `control.camundiApprovalFlow`.\n deleteOrganization: 'delete-organization',\n // Many organizations in one request. Behind `control.camundiApprovalFlow`\n // and its own flag `control.orgBulkDeletion`. See `org-bulk-deletion.ts`\n // beside this file.\n orgBulkDeletion: 'org-bulk-deletion',\n deleteUser: 'delete-user',\n changeUserEmail: 'change-user-email',\n purgeUsers: 'purge-users',\n updateUserMetadata: 'update-user-metadata',\n // A change of the feature flag table, on a stage where\n // `isFeatureFlagApprovalRequired` is true.\n changeFeatureFlag: 'change-feature-flag',\n // Turns one flag off, and nothing else. A rollback needs fewer approvals\n // than a change.\n disableFeatureFlag: 'disable-feature-flag',\n // Engages one kill switch: the action that it guards stops for everybody,\n // or for the items of the lists of the request. To release a switch with\n // lists, empty the lists with a `change-feature-flag` request. To release\n // any other switch, use a `disable-feature-flag` request.\n engageKillSwitch: 'engage-kill-switch',\n // The publish and the rollback of a release-train generation. See\n // `release-train.ts` beside this file.\n releaseTrainPublish: 'release-train-publish',\n releaseTrainRollback: 'release-train-rollback',\n // Open to every Camundi, and it needs no approval on any stage.\n createPersonalOrganisation: 'create-personal-organisation',\n // Open to the owner of a trial organization, who must be a Camundi. It needs\n // no approval on any stage and moves the organization to the internal plan.\n convertTrialToInternal: 'convert-trial-to-internal',\n // Open to the owner of an internal or trial organization, who must be a\n // Camundi. It needs no approval on any stage and deletes the organization.\n deleteOwnTestOrg: 'delete-own-test-org',\n // Open to every Camundi, runs on dev only, and needs no approval. The two\n // use cases of custom hardware sizing.\n createCustomHardwareSizing: 'create-custom-hardware-sizing',\n removeCustomHardwareSizing: 'remove-custom-hardware-sizing',\n // The mutable versions of one or more generations, behind\n // `control.camundiApprovalFlow`. Console restarts every cluster of\n // each generation, which is why the write needs a second Camundi.\n changeGenerationVersions: 'change-generation-versions',\n // The name and the env vars of one generation, behind\n // `control.camundiApprovalFlow`. Console sends a new spec to every cluster of\n // the generation, which is why the write needs a second Camundi.\n editGeneration: 'edit-generation',\n // A new enterprise customer: a production and a development organization\n // in one step, behind `control.camundiApprovalFlow`. See\n // `automated-enterprise-onboarding.ts` in control-backend.\n automatedEnterpriseOnboarding: 'automated-enterprise-onboarding',\n // Open to every Camundi, runs on dev only, and needs no approval. The two\n // use cases of custom generations.\n createCustomGeneration: 'create-custom-generation',\n removeCustomGeneration: 'remove-custom-generation',\n // Open to org owners, runs on dev only, and needs no approval. It applies\n // or deactivates a cluster modification config of one cluster.\n selfServiceClusterModification: 'self-service-cluster-modification',\n // The enterprise onboarding of one organization, behind\n // `control.camundiApprovalFlow`: the contract, the plan type of\n // each cluster, and the reservations, in one request.\n onboardToEnterprise: 'onboard-to-enterprise',\n // The term, the start date and the included value metrics of the contract\n // of one enterprise organization, behind `control.camundiApprovalFlow`. See\n // `change-enterprise-contract.ts` in control-backend.\n changeEnterpriseContract: 'change-enterprise-contract',\n // The plan type and the hardware packages of ONE cluster, behind\n // `control.camundiApprovalFlow`. The bulk plan type update beside it also\n // checks the reservations and moves the cluster plan, but each cluster\n // keeps its packages there. This one can change the packages, and it has a\n // stale guard. See `change-cluster-plan-type.ts` in control-backend.\n changeClusterPlanType: 'change-cluster-plan-type',\n // The deletion of one cluster whose TTL ran out. Only the delete cron of\n // console-backend opens it, and it needs no approval. It is a record of the\n // deletion. See `cluster-ttl-deletion.ts` in control-backend.\n clusterTtlDeletion: 'cluster-ttl-deletion',\n // The deletion of the DB corpses or of the Kubernetes corpses that console\n // finds, behind `control.camundiApprovalFlow`. See\n // `delete-cluster-corpses.ts` in control-backend.\n deleteClusterCorpses: 'delete-cluster-corpses',\n // The force delete of a cluster plan type and of every cluster on it,\n // behind `control.camundiApprovalFlow`. See\n // `force-delete-cluster-plan-type.ts` in control-backend.\n forceDeleteClusterPlanType: 'force-delete-cluster-plan-type',\n // A change of the data retention limits of a cluster plan type, which\n // console sends to every cluster of the type. Behind\n // `control.camundiApprovalFlow`. See\n // `change-plan-type-retention-limits.ts` in control-backend.\n changePlanTypeRetentionLimits: 'change-plan-type-retention-limits',\n // The generation upgrade of one cluster with `--yolo` or with the upgrade\n // gate ignored, behind `control.camundiApprovalFlow`. A plain upgrade stays\n // a direct call. See `force-generation-upgrade.ts` in control-backend.\n forceGenerationUpgrade: 'force-generation-upgrade',\n // The deletion of one Console API client of an organization. See\n // `delete-api-client.ts` in control-backend.\n deleteApiClient: 'delete-api-client',\n // The licensing model of one enterprise organization, behind\n // `control.camundiApprovalFlow`. See `change-licensing-model.ts` in\n // control-backend.\n changeLicensingModel: 'change-licensing-model',\n // A time-limited grant that lets one Camundi run a pending request with no\n // approval, and the scheduled request that ends it. Behind\n // `control.approvalOverride`. See `approval-override.ts` in control-backend.\n grantApprovalOverride: 'grant-approval-override',\n revokeApprovalOverride: 'revoke-approval-override',\n // The deletion of the managed LLM tenant of one organization: the tenant,\n // the key and the spend history. Behind `control.camundiApprovalFlow`. See\n // `delete-managed-llm-tenant.ts` in control-backend.\n deleteManagedLlmTenant: 'delete-managed-llm-tenant',\n // The signup spam patterns of accounts, behind `control.camundiApprovalFlow`.\n changeSignupSpamPatterns: 'change-signup-spam-patterns',\n} as const\n\n/** The longest approval override grant, in hours: 14 days. */\nexport const APPROVAL_OVERRIDE_MAX_HOURS = 14 * 24\n\n/** The duration that the form of control-frontend offers first: one day. */\nexport const APPROVAL_OVERRIDE_DEFAULT_HOURS = 24\n\n/**\n * The use cases that an approval override grant can NOT run.\n *\n * Every other use case is overridable. These change who holds a permission,\n * the override mechanism itself, the feature flags of a stage, the address\n * that a person signs in with, or delete customer data, a backup, a sign-in\n * path, or a whole fleet of clusters. None of them is an emergency that one\n * Camundi must fix alone.\n *\n * The list fails open: a use case that is not here IS overridable. Thus a new\n * use case that deletes or that changes access must be added here. Its route\n * in accounts-backend or console-backend then refuses `overriddenBy` by\n * itself: `approvalActorSchemaFor` of their `AdminApprovalsRouter.ts` reads\n * this list.\n */\nexport const APPROVAL_OVERRIDE_DENYLIST: readonly string[] = [\n APPROVAL_USE_CASE_TYPES.changePlatformRoles,\n APPROVAL_USE_CASE_TYPES.grantApprovalOverride,\n APPROVAL_USE_CASE_TYPES.revokeApprovalOverride,\n APPROVAL_USE_CASE_TYPES.changeFeatureFlag,\n APPROVAL_USE_CASE_TYPES.disableFeatureFlag,\n APPROVAL_USE_CASE_TYPES.engageKillSwitch,\n APPROVAL_USE_CASE_TYPES.purgeUsers,\n APPROVAL_USE_CASE_TYPES.deleteUser,\n APPROVAL_USE_CASE_TYPES.deleteOrganization,\n APPROVAL_USE_CASE_TYPES.orgBulkDeletion,\n APPROVAL_USE_CASE_TYPES.clusterBulkDeletion,\n APPROVAL_USE_CASE_TYPES.forceDeleteClusterPlanType,\n APPROVAL_USE_CASE_TYPES.releaseTrainPublish,\n APPROVAL_USE_CASE_TYPES.releaseTrainRollback,\n APPROVAL_USE_CASE_TYPES.deleteSsoConnection,\n APPROVAL_USE_CASE_TYPES.changeUserEmail,\n APPROVAL_USE_CASE_TYPES.deleteInternalBackup,\n APPROVAL_USE_CASE_TYPES.deleteApiClient,\n APPROVAL_USE_CASE_TYPES.removeOrgMember,\n APPROVAL_USE_CASE_TYPES.deleteManagedLlmTenant,\n]\n\n/** isApprovalOverridable reports whether a grant can run a request of this type. */\nexport const isApprovalOverridable = (type: string): boolean =>\n !APPROVAL_OVERRIDE_DENYLIST.includes(type)\n\n/**\n * The most personal organizations that one Camundi can request.\n *\n * The request runs with no approval, so this cap is the only guard against a\n * loop that creates organizations without end. It counts the requests that a\n * Camundi opened, and a person who needs more asks a Camundi who holds\n * `AccountsPermissions.CREATE_ORG`.\n */\nexport const PERSONAL_ORGANIZATION_MAX_PER_REQUESTER = 10\n\n/** The shortest and longest name of a personal organization. */\nexport const PERSONAL_ORGANIZATION_NAME_MIN_LENGTH = 3\nexport const PERSONAL_ORGANIZATION_NAME_MAX_LENGTH = 100\n\nexport type ApprovalUseCaseType =\n (typeof APPROVAL_USE_CASE_TYPES)[keyof typeof APPROVAL_USE_CASE_TYPES]\n\n/**\n * The shortest extension that accounts-backend accepts.\n *\n * `POST /:orgId/extendtrial` refuses a date that is less than 14 days away\n * when the body carries `onBehalfOf`, and it measures those 14 days when the\n * CALL arrives. The floor here is 15 and not 14, for two reasons:\n *\n * - The two clocks are not the same instant. Accounts builds its own \"14 days\n * from now\" a few milliseconds after control-backend builds the date, so a\n * date of exactly 14 days is already in the past for the comparison.\n * - Accounts counts with `setDate`, which is calendar arithmetic. A change of\n * the daylight saving time moves its limit by an hour.\n */\nexport const EXTEND_TRIAL_MIN_DAYS = 15\n\n/**\n * The longest extension that accounts-backend accepts.\n *\n * The same route refuses a date more than 62 days away. 61 keeps the same\n * margin as the floor above.\n */\nexport const EXTEND_TRIAL_MAX_DAYS = 61\n\n/**\n * The most roles that one change-platform-roles request adds, or removes.\n *\n * The form of control-frontend offers every platform role, and a person who\n * gives a Camundi a new position rarely changes more than a few. A request with\n * more roles than this is a request that nobody reads before they approve it.\n */\nexport const PLATFORM_ROLE_CHANGE_MAX_ROLES = 10\n\n/**\n * The bounds of one change-signup-spam-patterns request. A pattern set is a\n * map from a signup field (`first`, `last`) to the text that blocks a signup.\n * The bounds keep a request readable for the person who approves it, and keep\n * a typo from writing a set that nobody can review. The limits allow about\n * 2 MB (20 \u00D7 500 \u00D7 200 characters). A request body over 1 MiB, `previous`\n * included, gets a 413 from control-backend. A real set is far smaller.\n */\nexport const SIGNUP_SPAM_PATTERNS_MAX_FIELDS = 20\nexport const SIGNUP_SPAM_PATTERNS_MAX_PER_FIELD = 500\nexport const SIGNUP_SPAM_PATTERN_MAX_LENGTH = 200\n\n/**\n * The longest text value that one change-org-limits request writes.\n *\n * A text limit holds a short value, such as a list of regions. The bound keeps\n * a request readable for the person who approves it.\n */\nexport const ORG_LIMIT_TEXT_MAX_LENGTH = 2000\n\n/**\n * LLM_BUDGET_TOP_UP_THRESHOLD is the share of the budget that the spend of a\n * managed LLM key must reach before a top-up is the normal case.\n *\n * A request below it is still possible, but the person who asks must confirm\n * it, and the request says so to the approver. Accounts refuses a top-up\n * below it that does not carry that confirmation.\n */\nexport const LLM_BUDGET_TOP_UP_THRESHOLD = 0.9\n\n/**\n * isLlmSpendBelowTopUpThreshold reports whether a top-up of a managed LLM key\n * needs the explicit confirmation of `LLM_BUDGET_TOP_UP_THRESHOLD`.\n */\nexport const isLlmSpendBelowTopUpThreshold = (\n spend: number,\n maxBudget: number,\n): boolean => spend < maxBudget * LLM_BUDGET_TOP_UP_THRESHOLD\n\n/**\n * The most users that one purge-users request deletes.\n *\n * The God Mode purge deletes one user after the other, and Auth0 limits how\n * fast that goes. A list longer than this is also a list that no approver\n * reads before they agree.\n */\nexport const PURGE_USERS_MAX_USERS = 1000\n\n/**\n * What a person must hold to open or to approve a purge-users request.\n *\n * The purge route of accounts, `DELETE /api/users/:userId/purge`, needs both\n * of the caller. The approval route of accounts checks both of the person who\n * asked, when control-backend sends `purge: true`. The use case of\n * control-backend returns this list from `permissionsFor`, and the form passes\n * it to `canCreate`, so the button and the server never disagree.\n */\nexport const PURGE_USERS_REQUIRED_PERMISSIONS: readonly string[] = [\n AccountsPermissions.GOD_PURGE_USERS,\n AccountsPermissions.DELETE_USER,\n]\n\n/**\n * The flag that opens the create route of remove-org-member. It is its own\n * flag, so the removal of an owner can go live on a stage where\n * `control.camundiApprovalFlow` is off.\n */\nexport const REMOVE_ORG_MEMBER_FLAG = 'control.removeOrgMember'\n\n/**\n * What a person must hold to open or to approve a remove-org-member request,\n * with or without a new owner. CS holds it through the Camundi permission\n * rules. Accounts checks the same list for the person who asked.\n */\nexport const REMOVE_ORG_MEMBER_REQUIRED_PERMISSIONS: readonly string[] = [\n AccountsPermissions.REMOVE_FROM_ORG_WITH_APPROVAL,\n]\n\n/**\n * The largest metadata object that one update-user-metadata request writes,\n * in characters of its JSON text.\n *\n * This is a bound of the product, and not the limit of Auth0, which is far\n * larger. The approvers read the whole object before they agree, and an\n * object that is longer than this is an object that nobody reads.\n */\nexport const USER_METADATA_MAX_LENGTH = 16_000\n\n/**\n * The largest metadata object that a request carries as the object that the\n * person who asked READ.\n *\n * It is larger than `USER_METADATA_MAX_LENGTH`, so a user whose metadata grew\n * past that bound can still get an edit that makes it smaller. It still has a\n * bound, because the request keeps the copy in its row.\n */\nexport const USER_METADATA_EXPECTED_MAX_LENGTH = 500_000\n\n/**\n * The bounds of an automated-enterprise-onboarding request.\n *\n * The accounts wizard holds the first four, and the schema of control-backend\n * and the form of control-frontend read them here, so the form never sends\n * what the service refuses.\n */\nexport const ENTERPRISE_ONBOARDING_NAME_MAX_LENGTH = 50\nexport const ENTERPRISE_ONBOARDING_SFDC_ID_MAX_LENGTH = 50\nexport const ENTERPRISE_ONBOARDING_TERM_MIN_MONTHS = 1\nexport const ENTERPRISE_ONBOARDING_TERM_MAX_MONTHS = 60\n/** The most of one value metric that a contract includes. */\nexport const ENTERPRISE_ONBOARDING_METRIC_MAX = 1_000_000_000_000\n/**\n * The most clusters of one plan type that an onboarding reserves: the cap of\n * the accounts wizard. Accounts checks the limit of the plan only when it\n * reserves, after it created the two organizations, so the request must not\n * carry a count that the plan refuses.\n */\nexport const ENTERPRISE_ONBOARDING_RESERVATION_MAX = 20\n\n/**\n * The most clusters of one plan type that a change-org-reservations request\n * reserves. The approval route of accounts-ng has the same bound.\n * `PATCH /api/salesplans/reserved` has no bound. A request with `force`\n * skips the maximum of the sales plan, thus this bound is its only bound.\n */\nexport const ORG_RESERVATION_MAX = 1000\n\n/**\n * Whether a string is a calendar day, `YYYY-MM-DD`, that exists.\n *\n * The shape alone is not enough: `Date` rolls `2026-02-30` to March 2 with\n * no error, and `2026-13-45` becomes an invalid date that a database refuses\n * only at the write. A request carries the day for days before it runs, so\n * the check is at the open, and in the form.\n */\nexport const isCalendarDay = (value: string): boolean =>\n /^\\d{4}-\\d{2}-\\d{2}$/.test(value) &&\n !Number.isNaN(Date.parse(value)) &&\n new Date(value).toISOString().startsWith(value)\n\n/**\n * What a person must hold to open or to approve a change-enterprise-contract\n * request.\n *\n * `PATCH /:orgId/enterprise` of accounts needs `ENTERPRISE_ORG_MODIFY`, and\n * also `ENTERPRISE_ORG_MODIFY_START_DATE` for a new start date. The approval\n * route of accounts checks the same list for the person who asked. The use\n * case of control-backend returns this list from `permissionsFor`, and the\n * form passes it to `canCreate`, so the button and the server never disagree.\n */\nexport const enterpriseContractChangePermissions = (\n changesStartDate: boolean,\n): string[] =>\n changesStartDate\n ? [\n AccountsPermissions.ENTERPRISE_ORG_MODIFY,\n AccountsPermissions.ENTERPRISE_ORG_MODIFY_START_DATE,\n ]\n : [AccountsPermissions.ENTERPRISE_ORG_MODIFY]\n\n/** The longest email address that a change-user-email request carries. */\nexport const APPROVAL_EMAIL_MAX_LENGTH = 320\n\n/**\n * The email addresses that a change-user-email request accepts.\n *\n * It is the email pattern of zod 4.6. The pattern is here, so the schema of\n * control-backend and the form of control-frontend accept the same addresses,\n * and a form never sends an address that the service refuses.\n */\nexport const APPROVAL_EMAIL_PATTERN =\n // biome-ignore lint/complexity/noUselessEscapeInRegex: the same source as zod, character for character\n /^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/\n\n/**\n * The most generations that one change-generation-versions request changes.\n *\n * Each generation restarts every cluster on it. A request over more\n * generations than this is a request that no approver reads to the end.\n *\n * The two bounds of this use case also keep a request under the body limit\n * of control-backend (1 MiB, `server-options.ts` of the shared Fastify\n * layer): 20 generations, each with the expected value of the 2 image\n * versions of 2000 characters, is 80 000 characters before the rest of the\n * payload.\n */\nexport const GENERATION_VERSIONS_MAX_GENERATIONS = 20\n\n/**\n * The longest value of one mutable version of a generation.\n *\n * An image reference is short, and only the two image versions go through\n * the use case (`GENERATION_IMAGE_VERSION_KEYS`). The bound keeps a request\n * readable for the approver. See `GENERATION_VERSIONS_MAX_GENERATIONS` for\n * the sum.\n */\nexport const GENERATION_VERSION_VALUE_MAX_LENGTH = 2000\n"],
|
|
4
|
+
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport { AccountsPermissions } from '../permissions/accounts.permissions.js'\n\n/**\n * The names and the value ranges of the registered use cases.\n *\n * control-backend owns the registry, and a frontend reads it at run time\n * (`GET /api/approvals/use-cases`). Two things cannot wait for that answer:\n *\n * - **The identifier**, because a caller must NAME a use case to find it in the\n * registry, and to open a request of it.\n * - **The range of a payload field**, because a form holds the value before any\n * call goes out.\n *\n * Both live here, so the schema of the service and the form of the browser can\n * never hold different numbers.\n */\n\n/** The identifier of each use case, on the wire and in the table. */\nexport const APPROVAL_USE_CASE_TYPES = {\n sendToExpiredTrial: 'send-to-expired-trial',\n extendTrial: 'extend-trial',\n moveClusterOrg: 'move-cluster-org',\n // One use case for each type of a cluster bulk operation. The types need\n // different permissions and different approval counts, and a use case holds\n // one of each. See `cluster-bulk-operation.ts` beside this file.\n clusterBulkGenerationUpdate: 'cluster-bulk-generation-update',\n clusterBulkPlanUpdate: 'cluster-bulk-plan-update',\n clusterBulkPlanTypeUpdate: 'cluster-bulk-plan-type-update',\n clusterBulkSleepWakeup: 'cluster-bulk-sleep-wakeup',\n clusterBulkDeletion: 'cluster-bulk-deletion',\n clusterBulkSpecUpdate: 'cluster-bulk-spec-update',\n // The second group, behind `control.camundiApprovalFlow`.\n changePlatformRoles: 'change-platform-roles',\n deleteInternalBackup: 'delete-internal-backup',\n changeOrgLimits: 'change-org-limits',\n // The cluster reservations of one organization, behind\n // `control.camundiApprovalFlow`. It is not the enterprise contract: a\n // reservation change and a contract change are two requests. See\n // `change-org-reservations.ts` in control-backend.\n changeOrgReservations: 'change-org-reservations',\n deleteSsoConnection: 'delete-sso-connection',\n createSsoConnection: 'create-sso-connection',\n updateSsoConnection: 'update-sso-connection',\n changeSalesPlan: 'change-sales-plan',\n llmBudgetTopUp: 'llm-budget-top-up',\n requestInNegotiation: 'request-in-negotiation',\n // Behind its own flag `control.removeOrgMember`, and not\n // `control.camundiApprovalFlow`. See `REMOVE_ORG_MEMBER_FLAG`.\n removeOrgMember: 'remove-org-member',\n // The third group, behind `control.camundiApprovalFlow`.\n deleteOrganization: 'delete-organization',\n // Many organizations in one request. Behind `control.camundiApprovalFlow`\n // and its own flag `control.orgBulkDeletion`. See `org-bulk-deletion.ts`\n // beside this file.\n orgBulkDeletion: 'org-bulk-deletion',\n deleteUser: 'delete-user',\n changeUserEmail: 'change-user-email',\n purgeUsers: 'purge-users',\n updateUserMetadata: 'update-user-metadata',\n // A change of the feature flag table, on a stage where\n // `isFeatureFlagApprovalRequired` is true.\n changeFeatureFlag: 'change-feature-flag',\n // Turns one flag off, and nothing else. A rollback needs fewer approvals\n // than a change.\n disableFeatureFlag: 'disable-feature-flag',\n // Engages one kill switch: the action that it guards stops for everybody,\n // or for the items of the lists of the request. To release a switch with\n // lists, empty the lists with a `change-feature-flag` request. To release\n // any other switch, use a `disable-feature-flag` request.\n engageKillSwitch: 'engage-kill-switch',\n // The publish and the rollback of a release-train generation. See\n // `release-train.ts` beside this file.\n releaseTrainPublish: 'release-train-publish',\n releaseTrainRollback: 'release-train-rollback',\n // Open to every Camundi, and it needs no approval on any stage.\n createPersonalOrganisation: 'create-personal-organisation',\n // Open to the owner of a trial organization, who must be a Camundi. It needs\n // no approval on any stage and moves the organization to the internal plan.\n convertTrialToInternal: 'convert-trial-to-internal',\n // Open to the owner of an internal or trial organization, who must be a\n // Camundi. It needs no approval on any stage and deletes the organization.\n deleteOwnTestOrg: 'delete-own-test-org',\n // Open to every Camundi, runs on dev only, and needs no approval. The two\n // use cases of custom hardware sizing.\n createCustomHardwareSizing: 'create-custom-hardware-sizing',\n removeCustomHardwareSizing: 'remove-custom-hardware-sizing',\n // The mutable versions of one or more generations, behind\n // `control.camundiApprovalFlow`. Console restarts every cluster of\n // each generation, which is why the write needs a second Camundi.\n changeGenerationVersions: 'change-generation-versions',\n // The name and the env vars of one generation, behind\n // `control.camundiApprovalFlow`. Console sends a new spec to every cluster of\n // the generation, which is why the write needs a second Camundi.\n editGeneration: 'edit-generation',\n // A new enterprise customer: a production and a development organization\n // in one step, behind `control.camundiApprovalFlow`. See\n // `automated-enterprise-onboarding.ts` in control-backend.\n automatedEnterpriseOnboarding: 'automated-enterprise-onboarding',\n // Open to every Camundi, runs on dev only, and needs no approval. The two\n // use cases of custom generations.\n createCustomGeneration: 'create-custom-generation',\n removeCustomGeneration: 'remove-custom-generation',\n // Open to org owners, runs on dev only, and needs no approval. It applies\n // or deactivates a cluster modification config of one cluster.\n selfServiceClusterModification: 'self-service-cluster-modification',\n // The enterprise onboarding of one organization, behind\n // `control.camundiApprovalFlow`: the contract, the plan type of\n // each cluster, and the reservations, in one request.\n onboardToEnterprise: 'onboard-to-enterprise',\n // The term, the start date and the included value metrics of the contract\n // of one enterprise organization, behind `control.camundiApprovalFlow`. See\n // `change-enterprise-contract.ts` in control-backend.\n changeEnterpriseContract: 'change-enterprise-contract',\n // The plan type and the hardware packages of ONE cluster, behind\n // `control.camundiApprovalFlow`. The bulk plan type update beside it also\n // checks the reservations and moves the cluster plan, but each cluster\n // keeps its packages there. This one can change the packages, and it has a\n // stale guard. See `change-cluster-plan-type.ts` in control-backend.\n changeClusterPlanType: 'change-cluster-plan-type',\n // The deletion of one cluster whose TTL ran out. Only the delete cron of\n // console-backend opens it, and it needs no approval. It is a record of the\n // deletion. See `cluster-ttl-deletion.ts` in control-backend.\n clusterTtlDeletion: 'cluster-ttl-deletion',\n // The deletion of the DB corpses or of the Kubernetes corpses that console\n // finds, behind `control.camundiApprovalFlow`. See\n // `delete-cluster-corpses.ts` in control-backend.\n deleteClusterCorpses: 'delete-cluster-corpses',\n // The force delete of a cluster plan type and of every cluster on it,\n // behind `control.camundiApprovalFlow`. See\n // `force-delete-cluster-plan-type.ts` in control-backend.\n forceDeleteClusterPlanType: 'force-delete-cluster-plan-type',\n // A change of the data retention limits of a cluster plan type, which\n // console sends to every cluster of the type. Behind\n // `control.camundiApprovalFlow`. See\n // `change-plan-type-retention-limits.ts` in control-backend.\n changePlanTypeRetentionLimits: 'change-plan-type-retention-limits',\n // The generation upgrade of one cluster with `--yolo` or with the upgrade\n // gate ignored, behind `control.camundiApprovalFlow`. A plain upgrade stays\n // a direct call. See `force-generation-upgrade.ts` in control-backend.\n forceGenerationUpgrade: 'force-generation-upgrade',\n // The deletion of one Console API client of an organization. See\n // `delete-api-client.ts` in control-backend.\n deleteApiClient: 'delete-api-client',\n // The licensing model of one enterprise organization, behind\n // `control.camundiApprovalFlow`. See `change-licensing-model.ts` in\n // control-backend.\n changeLicensingModel: 'change-licensing-model',\n // A time-limited grant that lets one Camundi run a pending request with no\n // approval, and the scheduled request that ends it. Behind\n // `control.approvalOverride`. See `approval-override.ts` in control-backend.\n grantApprovalOverride: 'grant-approval-override',\n revokeApprovalOverride: 'revoke-approval-override',\n // The deletion of the managed LLM tenant of one organization: the tenant,\n // the key and the spend history. Behind `control.camundiApprovalFlow`. See\n // `delete-managed-llm-tenant.ts` in control-backend.\n deleteManagedLlmTenant: 'delete-managed-llm-tenant',\n // The signup spam patterns of accounts, behind `control.camundiApprovalFlow`.\n changeSignupSpamPatterns: 'change-signup-spam-patterns',\n} as const\n\n/** The longest approval override grant, in hours: 14 days. */\nexport const APPROVAL_OVERRIDE_MAX_HOURS = 14 * 24\n\n/** The duration that the form of control-frontend offers first: one day. */\nexport const APPROVAL_OVERRIDE_DEFAULT_HOURS = 24\n\n/**\n * The use cases that an approval override grant can NOT run.\n *\n * Every other use case is overridable. These change who holds a permission,\n * the override mechanism itself, the feature flags of a stage, the address\n * that a person signs in with, or delete customer data, a backup, a sign-in\n * path, or a whole fleet of clusters. None of them is an emergency that one\n * Camundi must fix alone.\n *\n * The list fails open: a use case that is not here IS overridable. Thus a new\n * use case that deletes or that changes access must be added here. Its route\n * in accounts-ng or console-backend then refuses `overriddenBy` by\n * itself: `approvalActorSchemaFor` of their `AdminApprovalsRouter.ts` reads\n * this list.\n */\nexport const APPROVAL_OVERRIDE_DENYLIST: readonly string[] = [\n APPROVAL_USE_CASE_TYPES.changePlatformRoles,\n APPROVAL_USE_CASE_TYPES.grantApprovalOverride,\n APPROVAL_USE_CASE_TYPES.revokeApprovalOverride,\n APPROVAL_USE_CASE_TYPES.changeFeatureFlag,\n APPROVAL_USE_CASE_TYPES.disableFeatureFlag,\n APPROVAL_USE_CASE_TYPES.engageKillSwitch,\n APPROVAL_USE_CASE_TYPES.purgeUsers,\n APPROVAL_USE_CASE_TYPES.deleteUser,\n APPROVAL_USE_CASE_TYPES.deleteOrganization,\n APPROVAL_USE_CASE_TYPES.orgBulkDeletion,\n APPROVAL_USE_CASE_TYPES.clusterBulkDeletion,\n APPROVAL_USE_CASE_TYPES.forceDeleteClusterPlanType,\n APPROVAL_USE_CASE_TYPES.releaseTrainPublish,\n APPROVAL_USE_CASE_TYPES.releaseTrainRollback,\n APPROVAL_USE_CASE_TYPES.deleteSsoConnection,\n APPROVAL_USE_CASE_TYPES.changeUserEmail,\n APPROVAL_USE_CASE_TYPES.deleteInternalBackup,\n APPROVAL_USE_CASE_TYPES.deleteApiClient,\n APPROVAL_USE_CASE_TYPES.removeOrgMember,\n APPROVAL_USE_CASE_TYPES.deleteManagedLlmTenant,\n]\n\n/** isApprovalOverridable reports whether a grant can run a request of this type. */\nexport const isApprovalOverridable = (type: string): boolean =>\n !APPROVAL_OVERRIDE_DENYLIST.includes(type)\n\n/**\n * The most personal organizations that one Camundi can request.\n *\n * The request runs with no approval, so this cap is the only guard against a\n * loop that creates organizations without end. It counts the requests that a\n * Camundi opened, and a person who needs more asks a Camundi who holds\n * `AccountsPermissions.CREATE_ORG`.\n */\nexport const PERSONAL_ORGANIZATION_MAX_PER_REQUESTER = 10\n\n/** The shortest and longest name of a personal organization. */\nexport const PERSONAL_ORGANIZATION_NAME_MIN_LENGTH = 3\nexport const PERSONAL_ORGANIZATION_NAME_MAX_LENGTH = 100\n\nexport type ApprovalUseCaseType =\n (typeof APPROVAL_USE_CASE_TYPES)[keyof typeof APPROVAL_USE_CASE_TYPES]\n\n/**\n * The shortest extension that accounts-ng accepts.\n *\n * `POST /:orgId/extendtrial` refuses a date that is less than 14 days away\n * when the body carries `onBehalfOf`, and it measures those 14 days when the\n * CALL arrives. The floor here is 15 and not 14, for two reasons:\n *\n * - The two clocks are not the same instant. Accounts builds its own \"14 days\n * from now\" a few milliseconds after control-backend builds the date, so a\n * date of exactly 14 days is already in the past for the comparison.\n * - Accounts counts with `setDate`, which is calendar arithmetic. A change of\n * the daylight saving time moves its limit by an hour.\n */\nexport const EXTEND_TRIAL_MIN_DAYS = 15\n\n/**\n * The longest extension that accounts-ng accepts.\n *\n * The same route refuses a date more than 62 days away. 61 keeps the same\n * margin as the floor above.\n */\nexport const EXTEND_TRIAL_MAX_DAYS = 61\n\n/**\n * The most roles that one change-platform-roles request adds, or removes.\n *\n * The form of control-frontend offers every platform role, and a person who\n * gives a Camundi a new position rarely changes more than a few. A request with\n * more roles than this is a request that nobody reads before they approve it.\n */\nexport const PLATFORM_ROLE_CHANGE_MAX_ROLES = 10\n\n/**\n * The bounds of one change-signup-spam-patterns request. A pattern set is a\n * map from a signup field (`first`, `last`) to the text that blocks a signup.\n * The bounds keep a request readable for the person who approves it, and keep\n * a typo from writing a set that nobody can review. The limits allow about\n * 2 MB (20 \u00D7 500 \u00D7 200 characters). A request body over 1 MiB, `previous`\n * included, gets a 413 from control-backend. A real set is far smaller.\n */\nexport const SIGNUP_SPAM_PATTERNS_MAX_FIELDS = 20\nexport const SIGNUP_SPAM_PATTERNS_MAX_PER_FIELD = 500\nexport const SIGNUP_SPAM_PATTERN_MAX_LENGTH = 200\n\n/**\n * The longest text value that one change-org-limits request writes.\n *\n * A text limit holds a short value, such as a list of regions. The bound keeps\n * a request readable for the person who approves it.\n */\nexport const ORG_LIMIT_TEXT_MAX_LENGTH = 2000\n\n/**\n * LLM_BUDGET_TOP_UP_THRESHOLD is the share of the budget that the spend of a\n * managed LLM key must reach before a top-up is the normal case.\n *\n * A request below it is still possible, but the person who asks must confirm\n * it, and the request says so to the approver. Accounts refuses a top-up\n * below it that does not carry that confirmation.\n */\nexport const LLM_BUDGET_TOP_UP_THRESHOLD = 0.9\n\n/**\n * isLlmSpendBelowTopUpThreshold reports whether a top-up of a managed LLM key\n * needs the explicit confirmation of `LLM_BUDGET_TOP_UP_THRESHOLD`.\n */\nexport const isLlmSpendBelowTopUpThreshold = (\n spend: number,\n maxBudget: number,\n): boolean => spend < maxBudget * LLM_BUDGET_TOP_UP_THRESHOLD\n\n/**\n * The most users that one purge-users request deletes.\n *\n * The God Mode purge deletes one user after the other, and Auth0 limits how\n * fast that goes. A list longer than this is also a list that no approver\n * reads before they agree.\n */\nexport const PURGE_USERS_MAX_USERS = 1000\n\n/**\n * What a person must hold to open or to approve a purge-users request.\n *\n * The purge route of accounts, `DELETE /api/users/:userId/purge`, needs both\n * of the caller. The approval route of accounts checks both of the person who\n * asked, when control-backend sends `purge: true`. The use case of\n * control-backend returns this list from `permissionsFor`, and the form passes\n * it to `canCreate`, so the button and the server never disagree.\n */\nexport const PURGE_USERS_REQUIRED_PERMISSIONS: readonly string[] = [\n AccountsPermissions.GOD_PURGE_USERS,\n AccountsPermissions.DELETE_USER,\n]\n\n/**\n * The flag that opens the create route of remove-org-member. It is its own\n * flag, so the removal of an owner can go live on a stage where\n * `control.camundiApprovalFlow` is off.\n */\nexport const REMOVE_ORG_MEMBER_FLAG = 'control.removeOrgMember'\n\n/**\n * What a person must hold to open or to approve a remove-org-member request,\n * with or without a new owner. CS holds it through the Camundi permission\n * rules. Accounts checks the same list for the person who asked.\n */\nexport const REMOVE_ORG_MEMBER_REQUIRED_PERMISSIONS: readonly string[] = [\n AccountsPermissions.REMOVE_FROM_ORG_WITH_APPROVAL,\n]\n\n/**\n * The largest metadata object that one update-user-metadata request writes,\n * in characters of its JSON text.\n *\n * This is a bound of the product, and not the limit of Auth0, which is far\n * larger. The approvers read the whole object before they agree, and an\n * object that is longer than this is an object that nobody reads.\n */\nexport const USER_METADATA_MAX_LENGTH = 16_000\n\n/**\n * The largest metadata object that a request carries as the object that the\n * person who asked READ.\n *\n * It is larger than `USER_METADATA_MAX_LENGTH`, so a user whose metadata grew\n * past that bound can still get an edit that makes it smaller. It still has a\n * bound, because the request keeps the copy in its row.\n */\nexport const USER_METADATA_EXPECTED_MAX_LENGTH = 500_000\n\n/**\n * The bounds of an automated-enterprise-onboarding request.\n *\n * The accounts wizard holds the first four, and the schema of control-backend\n * and the form of control-frontend read them here, so the form never sends\n * what the service refuses.\n */\nexport const ENTERPRISE_ONBOARDING_NAME_MAX_LENGTH = 50\nexport const ENTERPRISE_ONBOARDING_SFDC_ID_MAX_LENGTH = 50\nexport const ENTERPRISE_ONBOARDING_TERM_MIN_MONTHS = 1\nexport const ENTERPRISE_ONBOARDING_TERM_MAX_MONTHS = 60\n/** The most of one value metric that a contract includes. */\nexport const ENTERPRISE_ONBOARDING_METRIC_MAX = 1_000_000_000_000\n/**\n * The most clusters of one plan type that an onboarding reserves: the cap of\n * the accounts wizard. Accounts checks the limit of the plan only when it\n * reserves, after it created the two organizations, so the request must not\n * carry a count that the plan refuses.\n */\nexport const ENTERPRISE_ONBOARDING_RESERVATION_MAX = 20\n\n/**\n * The most clusters of one plan type that a change-org-reservations request\n * reserves. The approval route of accounts-ng has the same bound.\n * `PATCH /api/salesplans/reserved` has no bound. A request with `force`\n * skips the maximum of the sales plan, thus this bound is its only bound.\n */\nexport const ORG_RESERVATION_MAX = 1000\n\n/**\n * Whether a string is a calendar day, `YYYY-MM-DD`, that exists.\n *\n * The shape alone is not enough: `Date` rolls `2026-02-30` to March 2 with\n * no error, and `2026-13-45` becomes an invalid date that a database refuses\n * only at the write. A request carries the day for days before it runs, so\n * the check is at the open, and in the form.\n */\nexport const isCalendarDay = (value: string): boolean =>\n /^\\d{4}-\\d{2}-\\d{2}$/.test(value) &&\n !Number.isNaN(Date.parse(value)) &&\n new Date(value).toISOString().startsWith(value)\n\n/**\n * What a person must hold to open or to approve a change-enterprise-contract\n * request.\n *\n * `PATCH /:orgId/enterprise` of accounts needs `ENTERPRISE_ORG_MODIFY`, and\n * also `ENTERPRISE_ORG_MODIFY_START_DATE` for a new start date. The approval\n * route of accounts checks the same list for the person who asked. The use\n * case of control-backend returns this list from `permissionsFor`, and the\n * form passes it to `canCreate`, so the button and the server never disagree.\n */\nexport const enterpriseContractChangePermissions = (\n changesStartDate: boolean,\n): string[] =>\n changesStartDate\n ? [\n AccountsPermissions.ENTERPRISE_ORG_MODIFY,\n AccountsPermissions.ENTERPRISE_ORG_MODIFY_START_DATE,\n ]\n : [AccountsPermissions.ENTERPRISE_ORG_MODIFY]\n\n/** The longest email address that a change-user-email request carries. */\nexport const APPROVAL_EMAIL_MAX_LENGTH = 320\n\n/**\n * The email addresses that a change-user-email request accepts.\n *\n * It is the email pattern of zod 4.6. The pattern is here, so the schema of\n * control-backend and the form of control-frontend accept the same addresses,\n * and a form never sends an address that the service refuses.\n */\nexport const APPROVAL_EMAIL_PATTERN =\n // biome-ignore lint/complexity/noUselessEscapeInRegex: the same source as zod, character for character\n /^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/\n\n/**\n * The most generations that one change-generation-versions request changes.\n *\n * Each generation restarts every cluster on it. A request over more\n * generations than this is a request that no approver reads to the end.\n *\n * The two bounds of this use case also keep a request under the body limit\n * of control-backend (1 MiB, `server-options.ts` of the shared Fastify\n * layer): 20 generations, each with the expected value of the 2 image\n * versions of 2000 characters, is 80 000 characters before the rest of the\n * payload.\n */\nexport const GENERATION_VERSIONS_MAX_GENERATIONS = 20\n\n/**\n * The longest value of one mutable version of a generation.\n *\n * An image reference is short, and only the two image versions go through\n * the use case (`GENERATION_IMAGE_VERSION_KEYS`). The bound keeps a request\n * readable for the approver. See `GENERATION_VERSIONS_MAX_GENERATIONS` for\n * the sum.\n */\nexport const GENERATION_VERSION_VALUE_MAX_LENGTH = 2000\n"],
|
|
5
5
|
"mappings": "AAMA,SAAS,2BAA2B;AAkB7B,MAAM,0BAA0B;AAAA,EACrC,oBAAoB;AAAA,EACpB,aAAa;AAAA,EACb,gBAAgB;AAAA;AAAA;AAAA;AAAA,EAIhB,6BAA6B;AAAA,EAC7B,uBAAuB;AAAA,EACvB,2BAA2B;AAAA,EAC3B,wBAAwB;AAAA,EACxB,qBAAqB;AAAA,EACrB,uBAAuB;AAAA;AAAA,EAEvB,qBAAqB;AAAA,EACrB,sBAAsB;AAAA,EACtB,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKjB,uBAAuB;AAAA,EACvB,qBAAqB;AAAA,EACrB,qBAAqB;AAAA,EACrB,qBAAqB;AAAA,EACrB,iBAAiB;AAAA,EACjB,gBAAgB;AAAA,EAChB,sBAAsB;AAAA;AAAA;AAAA,EAGtB,iBAAiB;AAAA;AAAA,EAEjB,oBAAoB;AAAA;AAAA;AAAA;AAAA,EAIpB,iBAAiB;AAAA,EACjB,YAAY;AAAA,EACZ,iBAAiB;AAAA,EACjB,YAAY;AAAA,EACZ,oBAAoB;AAAA;AAAA;AAAA,EAGpB,mBAAmB;AAAA;AAAA;AAAA,EAGnB,oBAAoB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKpB,kBAAkB;AAAA;AAAA;AAAA,EAGlB,qBAAqB;AAAA,EACrB,sBAAsB;AAAA;AAAA,EAEtB,4BAA4B;AAAA;AAAA;AAAA,EAG5B,wBAAwB;AAAA;AAAA;AAAA,EAGxB,kBAAkB;AAAA;AAAA;AAAA,EAGlB,4BAA4B;AAAA,EAC5B,4BAA4B;AAAA;AAAA;AAAA;AAAA,EAI5B,0BAA0B;AAAA;AAAA;AAAA;AAAA,EAI1B,gBAAgB;AA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C;AAGhD,MAAM,wCAAwC;AAC9C,MAAM,wCAAwC;AAkB9C,MAAM,wBAAwB;AAQ9B,MAAM,wBAAwB;AAS9B,MAAM,iCAAiC;AAUvC,MAAM,kCAAkC;AACxC,MAAM,qCAAqC;AAC3C,MAAM,iCAAiC;AAQvC,MAAM,4BAA4B;AAUlC,MAAM,8BAA8B;AAMpC,MAAM,gCAAgC,CAC3C,OACA,cACY,QAAQ,YAAY;AAS3B,MAAM,wBAAwB;AAW9B,MAAM,mCAAsD;AAAA,EACjE,oBAAoB;AAAA,EACpB,oBAAoB;AACtB;AAOO,MAAM,yBAAyB;AAO/B,MAAM,yCAA4D;AAAA,EACvE,oBAAoB;AACtB;AAUO,MAAM,2BAA2B;AAUjC,MAAM,oCAAoC;AAS1C,MAAM,wCAAwC;AAC9C,MAAM,2CAA2C;AACjD,MAAM,wCAAwC;AAC9C,MAAM,wCAAwC;AAE9C,MAAM,mCAAmC;AAOzC,MAAM,wCAAwC;AAQ9C,MAAM,sBAAsB;AAU5B,MAAM,gBAAgB,CAAC,UAC5B,sBAAsB,KAAK,KAAK,KAChC,CAAC,OAAO,MAAM,KAAK,MAAM,KAAK,CAAC,KAC/B,IAAI,KAAK,KAAK,EAAE,YAAY,EAAE,WAAW,KAAK;AAYzC,MAAM,sCAAsC,CACjD,qBAEA,mBACI;AAAA,EACE,oBAAoB;AAAA,EACpB,oBAAoB;AACtB,IACA,CAAC,oBAAoB,qBAAqB;AAGzC,MAAM,4BAA4B;AASlC,MAAM;AAAA;AAAA,EAEX;AAAA;AAcK,MAAM,sCAAsC;AAU5C,MAAM,sCAAsC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/charts/chart-metrics.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport type { SearchFieldSpec } from '../search/fields.js'\nimport type { ChartGrain, ChartUnit } from './chart-spec.js'\n\n// ============================================================================\n// The metric catalogue of the chart tiles, without SQL.\n//\n// The frontend reads it for autocomplete, help and validation as you type.\n// accounts-
|
|
4
|
+
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport type { SearchFieldSpec } from '../search/fields.js'\nimport type { ChartGrain, ChartUnit } from './chart-spec.js'\n\n// ============================================================================\n// The metric catalogue of the chart tiles, without SQL.\n//\n// The frontend reads it for autocomplete, help and validation as you type.\n// accounts-ng pairs each entry with its SQL (`hdp-data.charts.controller`),\n// and a test there makes sure that the two have the same ids.\n// ============================================================================\n\nexport interface ChartDimensionSpec {\n /** As typed after `by`. */\n id: string\n label: string\n description: string\n}\n\nexport interface ChartMetricSpec {\n /** As typed at the start of a query. */\n id: string\n label: string\n description: string\n unit: ChartUnit\n dimensions: readonly ChartDimensionSpec[]\n /** The fields that `where` can use. */\n filters: readonly SearchFieldSpec[]\n grains: readonly ChartGrain[]\n /** The longest window, in days. */\n maxWindowDays: number\n /**\n * How one number comes from a chart, for the `stat` render: first over the\n * series of a bucket, then over the buckets of the window. A counter sums\n * both. A gauge must not: a sum of daily load percentages means nothing.\n */\n stat: { series: 'sum' | 'mean'; window: 'sum' | 'max' | 'mean' }\n}\n\nconst CLUSTER_DIMENSION: ChartDimensionSpec = {\n id: 'cluster',\n label: 'Cluster',\n description: 'The cluster id.',\n}\n\nconst ORG_DIMENSION: ChartDimensionSpec = {\n id: 'org',\n label: 'Organization',\n description: 'The organization id.',\n}\n\n/**\n * The name of the organization of the cluster. It comes from the clusters\n * table of HDP, which holds the prod clusters only, so on another stage every\n * series is `(unknown)`.\n */\nconst ORG_NAME_DIMENSION: ChartDimensionSpec = {\n id: 'orgName',\n label: 'Organization name',\n description:\n 'The name of the organization of the cluster. Prod clusters only: on other stages it is (unknown).',\n}\n\nconst ORG_ID_FILTER: SearchFieldSpec = {\n field: 'orgId',\n label: 'Organization id',\n description: 'Exact organization id.',\n type: 'string',\n capabilities: ['match'],\n example: 'orgId:3f2c\u2026',\n}\n\nconst CLUSTER_ID_FILTER: SearchFieldSpec = {\n field: 'clusterId',\n label: 'Cluster id',\n description: 'Exact cluster id.',\n type: 'string',\n capabilities: ['match'],\n example: 'clusterId:9a1b\u2026',\n}\n\nconst VALUE_METRIC_DIMENSIONS: readonly ChartDimensionSpec[] = [\n CLUSTER_DIMENSION,\n ORG_DIMENSION,\n ORG_NAME_DIMENSION,\n {\n id: 'salesPlan',\n label: 'Sales plan',\n description: 'The sales plan of the organization on that day.',\n },\n {\n id: 'env',\n label: 'Environment',\n description: 'Production or development cluster.',\n },\n]\n\nconst VALUE_METRIC_FILTERS: readonly SearchFieldSpec[] = [\n ORG_ID_FILTER,\n CLUSTER_ID_FILTER,\n {\n field: 'salesPlan',\n label: 'Sales plan',\n description: 'Sales plan name, case-insensitive. Use * as a wildcard.',\n type: 'string',\n capabilities: ['match'],\n example: 'salesPlan:enterprise*',\n },\n {\n field: 'env',\n label: 'Environment',\n description: 'Production or development cluster.',\n type: 'enum',\n capabilities: ['match'],\n enumValues: ['production', 'development'],\n example: 'env:production',\n },\n]\n\nconst ALL_GRAINS: readonly ChartGrain[] = ['day', 'week', 'month']\nconst VALUE_METRIC_GRAINS = ALL_GRAINS\n\n/**\n * About one year, for a metric on a large table: the cluster gauges, which\n * are scraped about once a minute, and the change events of every backend\n * and stage. `over 12m every month` starts on the 1st of a month and reads up\n * to 396 days, so the limit holds that query.\n */\nconst LARGE_TABLE_MAX_WINDOW_DAYS = 400\n\n/** A gauge of the clusters, from the Prometheus metrics in HDP. */\nconst gaugeMetric = (\n id: string,\n label: string,\n unit: ChartMetricSpec['unit'],\n stat: ChartMetricSpec['stat'],\n description: string,\n): ChartMetricSpec => ({\n id,\n label,\n description,\n unit,\n dimensions: [CLUSTER_DIMENSION, ORG_DIMENSION, ORG_NAME_DIMENSION],\n filters: [ORG_ID_FILTER, CLUSTER_ID_FILTER],\n grains: ALL_GRAINS,\n maxWindowDays: LARGE_TABLE_MAX_WINDOW_DAYS,\n stat,\n})\n\n/**\n * About two years. The table holds one row for each cluster, day and metric.\n * `over 24m every month` starts on the 1st of a month and reads up to 761\n * days, so the limit holds that query.\n */\nconst VALUE_METRIC_MAX_WINDOW_DAYS = 762\n\nconst valueMetric = (\n id: string,\n label: string,\n description: string,\n): ChartMetricSpec => ({\n id,\n label,\n description,\n unit: 'count',\n dimensions: VALUE_METRIC_DIMENSIONS,\n filters: VALUE_METRIC_FILTERS,\n grains: VALUE_METRIC_GRAINS,\n maxWindowDays: VALUE_METRIC_MAX_WINDOW_DAYS,\n stat: { series: 'sum', window: 'sum' },\n})\n\nexport const CHART_METRICS: readonly ChartMetricSpec[] = [\n valueMetric(\n 'processInstances',\n 'Process instances',\n 'Process instances that started, from the HDP value metrics. The sum over each bucket.',\n ),\n valueMetric(\n 'decisionInstances',\n 'Decision instances',\n 'Decision instances that ran, from the HDP value metrics. The sum over each bucket.',\n ),\n valueMetric(\n 'taskUsers',\n 'Task users',\n 'Task users, from the HDP value metrics. The sum of the daily values over each bucket, as on the Value metrics tab.',\n ),\n gaugeMetric(\n 'activeTenants',\n 'Active tenants',\n 'count',\n { series: 'sum', window: 'max' },\n 'Active tenants: the peak of each cluster on a day, summed over the clusters. A week or a month shows its highest day. The table holds every stage.',\n ),\n gaugeMetric(\n 'clusterLoad',\n 'Cluster load',\n 'percent',\n { series: 'mean', window: 'mean' },\n 'The load of a cluster, in percent: the mean of a day, then the mean over the clusters and the days of a bucket. The table holds every stage.',\n ),\n gaugeMetric(\n 'diskUsedBytes',\n 'Elasticsearch disk used',\n 'bytes',\n { series: 'sum', window: 'max' },\n 'The used Elasticsearch disk: the peak of each cluster on a day, summed over the clusters. A week or a month shows its highest day. The table holds every stage.',\n ),\n {\n id: 'hostingCost',\n label: 'Hosting cost',\n description:\n 'The total gross hosting cost of the clusters that HDP tracks, in US dollars, before AWS credits. The sum over each bucket. The table holds every stage.',\n unit: 'usd',\n dimensions: [CLUSTER_DIMENSION, ORG_DIMENSION, ORG_NAME_DIMENSION],\n filters: [ORG_ID_FILTER, CLUSTER_ID_FILTER],\n grains: ALL_GRAINS,\n maxWindowDays: VALUE_METRIC_MAX_WINDOW_DAYS,\n stat: { series: 'sum', window: 'sum' },\n },\n {\n id: 'changeEvents',\n label: 'Change events',\n description:\n 'The change events that the backends of this stage sent to HDP: one for each insert, update or delete of an entity. The count over each bucket.',\n unit: 'count',\n dimensions: [\n { id: 'entity', label: 'Entity', description: 'For example cluster.' },\n {\n id: 'operation',\n label: 'Operation',\n description: 'insert, update or delete.',\n },\n ],\n filters: [\n {\n field: 'entity',\n label: 'Entity',\n description: 'The entity, case-insensitive. Use * as a wildcard.',\n type: 'string',\n capabilities: ['match'],\n example: 'entity:cluster',\n },\n {\n field: 'operation',\n label: 'Operation',\n description: 'The operation.',\n type: 'enum',\n capabilities: ['match'],\n enumValues: ['insert', 'update', 'delete'],\n example: 'operation:delete',\n },\n ],\n grains: ALL_GRAINS,\n maxWindowDays: LARGE_TABLE_MAX_WINDOW_DAYS,\n stat: { series: 'sum', window: 'sum' },\n },\n]\n\n/** Case-insensitive. */\nexport const findChartMetric = (\n id: string,\n metrics: readonly ChartMetricSpec[] = CHART_METRICS,\n): ChartMetricSpec | undefined =>\n metrics.find((metric) => metric.id.toLowerCase() === id.toLowerCase())\n\n/** Case-insensitive. */\nexport const findChartDimension = (\n metric: ChartMetricSpec,\n id: string,\n): ChartDimensionSpec | undefined =>\n metric.dimensions.find(\n (dimension) => dimension.id.toLowerCase() === id.toLowerCase(),\n )\n"],
|
|
5
5
|
"mappings": "AA4CA,MAAM,oBAAwC;AAAA,EAC5C,IAAI;AAAA,EACJ,OAAO;AAAA,EACP,aAAa;AACf;AAEA,MAAM,gBAAoC;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uB;AAAA,MACrE;AAAA,QACE,IAAI;AAAA,QACJ,OAAO;AAAA,QACP,aAAa;AAAA,MACf;AAAA,IACF;AAAA,IACA,SAAS;AAAA,MACP;AAAA,QACE,OAAO;AAAA,QACP,OAAO;AAAA,QACP,aAAa;AAAA,QACb,MAAM;AAAA,QACN,cAAc,CAAC,OAAO;AAAA,QACtB,SAAS;AAAA,MACX;AAAA,MACA;AAAA,QACE,OAAO;AAAA,QACP,OAAO;AAAA,QACP,aAAa;AAAA,QACb,MAAM;AAAA,QACN,cAAc,CAAC,OAAO;AAAA,QACtB,YAAY,CAAC,UAAU,UAAU,QAAQ;AAAA,QACzC,SAAS;AAAA,MACX;AAAA,IACF;AAAA,IACA,QAAQ;AAAA,IACR,eAAe;AAAA,IACf,MAAM,EAAE,QAAQ,OAAO,QAAQ,MAAM;AAAA,EACvC;AACF;AAGO,MAAM,kBAAkB,CAC7B,IACA,UAAsC,kBAEtC,QAAQ,KAAK,CAAC,WAAW,OAAO,GAAG,YAAY,MAAM,GAAG,YAAY,CAAC;AAGhE,MAAM,qBAAqB,CAChC,QACA,OAEA,OAAO,WAAW;AAAA,EAChB,CAAC,cAAc,UAAU,GAAG,YAAY,MAAM,GAAG,YAAY;AAC/D;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/charts/chart-spec.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport { LUCENE_QUERY_MAX_LENGTH } from '../search/parser.js'\n\n// ============================================================================\n// The chart query of a dashboard tile, and the result that the chart route of\n// accounts-
|
|
4
|
+
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport { LUCENE_QUERY_MAX_LENGTH } from '../search/parser.js'\n\n// ============================================================================\n// The chart query of a dashboard tile, and the result that the chart route of\n// accounts-ng gives for it. See\n// docs/superpowers/specs/2026-10-02-dashboard-chart-tiles-design.md.\n// ============================================================================\n\n/** The time buckets of a chart. A week starts on Monday (ISO). */\nexport const CHART_GRAINS = ['day', 'week', 'month'] as const\nexport type ChartGrain = (typeof CHART_GRAINS)[number]\n\n/** `d` is days, `w` is weeks and `m` is calendar months. */\nexport const CHART_WINDOW_UNITS = ['d', 'w', 'm'] as const\nexport type ChartWindowUnit = (typeof CHART_WINDOW_UNITS)[number]\n\n/** A window that ends today (UTC). \"The last 90 days\" is `{ amount: 90, unit: 'd' }`. */\nexport interface ChartWindow {\n amount: number\n unit: ChartWindowUnit\n}\n\n/**\n * One chart query. A tile stores this and never the data, so the chart\n * follows the window as the days go by.\n */\nexport interface ChartSpec {\n /** A metric id of `CHART_METRICS`. */\n metric: string\n /** A dimension id of the metric. Each value of it is one series. */\n by?: string\n grain: ChartGrain\n window: ChartWindow\n /** Lucene source text over the filter fields of the metric. */\n filter?: string\n /** The number of series to show. Only with `by`. */\n top?: number\n}\n\nexport const CHART_GRAIN_DEFAULT: ChartGrain = 'day'\nexport const CHART_WINDOW_DEFAULT: ChartWindow = { amount: 30, unit: 'd' }\nexport const CHART_TOP_DEFAULT = 10\nexport const CHART_TOP_MAX = 20\n\n/** The longest window, in days, for `every day`. */\nexport const CHART_DAY_GRAIN_MAX_DAYS = 366\n\n/**\n * The longest text of a whole chart query. The filter has its own limit,\n * `CHART_FILTER_MAX_LENGTH`.\n */\nexport const CHART_QUERY_MAX_LENGTH = 700\n\n/**\n * The longest filter of a chart query. It is the limit of the Lucene parser,\n * which checks every filter on every run.\n */\nexport const CHART_FILTER_MAX_LENGTH = LUCENE_QUERY_MAX_LENGTH\n\n/** The longest metric id or dimension id that a stored chart query holds. */\nexport const CHART_ID_MAX_LENGTH = 64\n\n/** The largest amount of a window, in its unit. */\nexport const CHART_WINDOW_AMOUNT_MAX = 9999\n\n/**\n * The series key of the sum of every series that is not in the top N. When a\n * real value of the dimension has this key, the key gets a `*`, so the keys\n * of a result stay unique.\n */\nexport const CHART_OTHER_SERIES_KEY = '(other)'\n\n/**\n * The series key of the rows with no value for the `by` dimension. It gets a\n * `*` the same way as `CHART_OTHER_SERIES_KEY`.\n */\nexport const CHART_UNKNOWN_SERIES_KEY = '(unknown)'\n\nexport interface ChartPoint {\n /** The first day of the bucket, `YYYY-MM-DD`. */\n ts: string\n value: number\n}\n\nexport interface ChartSeries {\n key: string\n points: ChartPoint[]\n}\n\n/** `percent` is 0 to 100. */\nexport type ChartUnit = 'count' | 'bytes' | 'usd' | 'percent'\n\n/** The answer of `POST /api/hdp/charts/query`. */\nexport interface ChartResult {\n metric: string\n unit: ChartUnit\n grain: ChartGrain\n /** The first day that the query reads, `YYYY-MM-DD`, inclusive. */\n from: string\n /** The last day that the query reads, `YYYY-MM-DD`, inclusive. */\n to: string\n /**\n * Sorted by the total of the series, the largest first. `(other)` is last.\n * The keys are unique.\n */\n series: ChartSeries[]\n /** True when the top N left out series. Their sum is the `(other)` series. */\n truncated: boolean\n bytesProcessed: number\n /** When the result came from the cache: the time of the query, ISO. */\n cachedAt?: string\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\nconst toDay = (date: Date): string => date.toISOString().slice(0, 10)\n\nconst parseDay = (day: string): Date => new Date(`${day}T00:00:00Z`)\n\nconst addDays = (day: string, delta: number): string =>\n toDay(new Date(parseDay(day).getTime() + delta * DAY_MS))\n\n/** The first day of the bucket of `day`, as BigQuery's `DATE_TRUNC` gives it. */\nexport const chartBucketStart = (day: string, grain: ChartGrain): string => {\n const date = parseDay(day)\n switch (grain) {\n case 'day':\n return day\n case 'week': {\n // getUTCDay: Sunday is 0. Monday starts the week.\n const sinceMonday = (date.getUTCDay() + 6) % 7\n return addDays(day, -sinceMonday)\n }\n case 'month':\n return `${day.slice(0, 7)}-01`\n }\n}\n\n/**\n * The days that a chart reads. The window ends on `today` and goes back by its\n * amount. The start moves back to the start of its bucket, so the first\n * bucket of the chart is complete.\n */\nexport const chartWindowRange = (\n window: ChartWindow,\n grain: ChartGrain,\n today: string,\n): { from: string; to: string; days: number } => {\n let start: string\n switch (window.unit) {\n case 'd':\n start = addDays(today, -(window.amount - 1))\n break\n case 'w':\n start = addDays(today, -(7 * window.amount - 1))\n break\n case 'm': {\n const date = parseDay(today)\n // Day 0 of a month is the last day of the month before. Thus a short\n // month clamps the day, and 03-31 minus one month gives 02-28.\n const shifted = new Date(\n Date.UTC(date.getUTCFullYear(), date.getUTCMonth() - window.amount, 1),\n )\n const lastDay = new Date(\n Date.UTC(shifted.getUTCFullYear(), shifted.getUTCMonth() + 1, 0),\n ).getUTCDate()\n shifted.setUTCDate(Math.min(date.getUTCDate(), lastDay))\n start = addDays(toDay(shifted), 1)\n break\n }\n }\n const from = chartBucketStart(start, grain)\n const days =\n Math.round(\n (parseDay(today).getTime() - parseDay(from).getTime()) / DAY_MS,\n ) + 1\n return { from, to: today, days }\n}\n\n/** Today in UTC, `YYYY-MM-DD`. */\nexport const chartToday = (now: Date = new Date()): string => toDay(now)\n"],
|
|
5
5
|
"mappings": "AAMA,SAAS,+BAA+B;AASjC,MAAM,eAAe,CAAC,OAAO,QAAQ,OAAO;AAI5C,MAAM,qBAAqB,CAAC,KAAK,KAAK,GAAG;AA0BzC,MAAM,sBAAkC;AACxC,MAAM,uBAAoC,EAAE,QAAQ,IAAI,MAAM,IAAI;AAClE,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AAGtB,MAAM,2BAA2B;AAMjC,MAAM,yBAAyB;AAM/B,MAAM,0BAA0B;AAGhC,MAAM,sBAAsB;AAG5B,MAAM,0BAA0B;AAOhC,MAAM,yBAAyB;AAM/B,MAAM,2BAA2B;AAqCxC,MAAM,SAAS,KAAK,KAAK,KAAK;AAE9B,MAAM,QAAQ,CAAC,SAAuB,KA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