@coffre/ui 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/chunks/{audit-sentence-C_wMpAqr.js → audit-sentence-JrQIUq6j.js} +2 -2
  2. package/dist/chunks/audit-sentence-JrQIUq6j.js.map +1 -0
  3. package/dist/chunks/{connected-apps-Bn5rEoV2.js → connected-apps-Dr8UgjK7.js} +2 -2
  4. package/dist/chunks/{connected-apps-Bn5rEoV2.js.map → connected-apps-Dr8UgjK7.js.map} +1 -1
  5. package/dist/chunks/{directory-BQNOdze_.js → directory-XcSbDRJv.js} +2 -2
  6. package/dist/chunks/{directory-BQNOdze_.js.map → directory-XcSbDRJv.js.map} +1 -1
  7. package/dist/chunks/{grants-CJIBrkod.js → grants-CmdZjKYU.js} +2 -2
  8. package/dist/chunks/{grants-CJIBrkod.js.map → grants-CmdZjKYU.js.map} +1 -1
  9. package/dist/chunks/{personal-tokens-B8rkT-DI.js → personal-tokens-Dvl1FktE.js} +2 -2
  10. package/dist/chunks/{personal-tokens-B8rkT-DI.js.map → personal-tokens-Dvl1FktE.js.map} +1 -1
  11. package/dist/chunks/{principal-page-Cv5PheS9.js → principal-page-bOaEYWJB.js} +6 -6
  12. package/dist/chunks/{principal-page-Cv5PheS9.js.map → principal-page-bOaEYWJB.js.map} +1 -1
  13. package/dist/chunks/{use-change-CQyDpCqw.js → use-change-BY6KPmnJ.js} +52 -4
  14. package/dist/chunks/use-change-BY6KPmnJ.js.map +1 -0
  15. package/dist/index.d.ts +1 -0
  16. package/dist/pages/account.js +4 -4
  17. package/dist/pages/audit.js +1 -1
  18. package/dist/pages/environment.js +108 -38
  19. package/dist/pages/environment.js.map +1 -1
  20. package/dist/pages/project-access.js +3 -3
  21. package/dist/pages/project-environments.js +1 -1
  22. package/dist/pages/projects.js +1 -1
  23. package/dist/pages/service-account.js +2 -2
  24. package/dist/pages/service-accounts.js +1 -1
  25. package/dist/pages/user.js +3 -3
  26. package/dist/pages/users.js +1 -1
  27. package/package.json +3 -3
  28. package/src/lib/audit-sentences.ts +5 -2
  29. package/src/lib/changes.ts +6 -2
  30. package/src/lib/secret-edit-batch.ts +49 -4
  31. package/src/pages/environment.tsx +87 -16
  32. package/src/styles/globals.css +28 -0
  33. package/dist/chunks/audit-sentence-C_wMpAqr.js.map +0 -1
  34. package/dist/chunks/use-change-CQyDpCqw.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"audit-sentence-C_wMpAqr.js","names":[],"sources":["../../src/lib/audit-sentences.ts","../../src/components/audit-sentence.tsx"],"sourcesContent":["/**\n * The audit log in sentences: who did what, to what. One entry is one\n * human action, named for it (`secret.read`, `access.grant`, …); a batch of\n * them, one reveal of twelve secrets, shares an operation and reads as one\n * line, \"ran market/prod: 12 secrets\".\n *\n * A sentence is parts rather than a string, so the page can make the people\n * and places in it links. `plain` flattens it, for tests and titles.\n */\nimport { shownMember, type AuditEntryView } from '@coffre/client';\nimport { INSTANCE_ROLES, isInstanceRole, isScope, scopeInWords, type Scope } from '@coffre/core/access';\n\n/** What a sentence is made from: an entry of the log, as `GET /api/audit` gives it. */\nexport type AuditEntry = Pick<\n AuditEntryView,\n | 'seq'\n | 'author'\n | 'actorType'\n | 'actorId'\n | 'action'\n | 'decision'\n | 'reason'\n | 'detail'\n | 'subject'\n | 'project'\n | 'environment'\n | 'key'\n | 'version'\n | 'secrets'\n | 'operationId'\n | 'metadata'\n>;\n\n/**\n * Text, a place (`market`, `market/prod`, `market/prod/KEY`), or a member,\n * as the log stores it (`user:…`, `token:…`): `shownMember` says it as people\n * read it, `service:…`, where it is shown.\n */\nexport type Part = string | { place: string } | { member: string };\n\nexport type Sentence = { parts: Part[]; refused: boolean };\n\n/** What one template needs: the line's leading entry, its batch, and how it was decided. */\ntype Facts = {\n entry: AuditEntry;\n /** Every entry of the batch, the lead included, a read of several once per secret (`perSecret`). */\n batch: AuditEntry[];\n /** Secrets the batch was about. */\n count: number;\n refused: boolean;\n};\n\ntype Template = {\n /** What they did: \"revealed\". */\n did: string | ((facts: Facts) => string);\n /** What they tried, after \"tried to\": \"reveal\". */\n tried: string | ((facts: Facts) => string);\n /** To what: \"market/prod/API_KEY\". */\n what: (facts: Facts) => Part[];\n /** Said only of what happened: \", now version 5\". */\n then?: (facts: Facts) => Part[];\n};\n\n// --- the pieces of a sentence ---------------------------------------------------\n\nconst text = (value: unknown): string | null => (typeof value === 'string' && value !== '' ? value : null);\nconst number = (value: unknown): number | null => (typeof value === 'number' ? value : null);\n\n/** The entry's place, as deep as it goes. */\nfunction place({ project, environment, key }: AuditEntry): Part[] {\n const path = [project, environment, key].filter((part): part is string => part !== null);\n return path.length === 0 ? ['coffre'] : [{ place: path.join('/') }];\n}\n\nfunction environmentOf({ project, environment }: AuditEntry): Part[] {\n return place({ project, environment, key: null } as AuditEntry);\n}\n\n/** The member an entry is about: its subject, or the principal a token entry names. */\nfunction subject(entry: AuditEntry): Part[] {\n if (entry.subject !== null) return [{ member: entry.subject }];\n const id = text(entry.metadata.principalId);\n if (id === null) return ['someone'];\n return [{ member: `${entry.metadata.principalType === 'service' ? 'token' : 'user'}:${id}` }];\n}\n\n/** Whether a token entry is about a personal token, which acts as its person, rather than a service account's. */\nfunction personal(entry: AuditEntry): boolean {\n return entry.metadata.kind === 'personal';\n}\n\n/** A personal token's label, as it was made: ` \"cursor-agent\"`. */\nfunction labelled(entry: AuditEntry): Part[] {\n const label = text(entry.metadata.label);\n return label === null ? [] : [` “${label}”`];\n}\n\n/** Why the vault made someone an Owner itself, said after it. */\nfunction owned(entry: AuditEntry): Part[] {\n return entry.metadata.reason === 'owners' ? [': the deployment names them one'] : [];\n}\n\n/** An MCP client, by the name it connected under. */\nfunction app(entry: AuditEntry): Part[] {\n return [text(entry.metadata.clientName) ?? 'an app'];\n}\n\n/** A tool's call: its name, and what it named. */\nfunction tool(entry: AuditEntry): Part[] {\n const names = Array.isArray(entry.metadata.names) ? entry.metadata.names.filter((name): name is string => typeof name === 'string') : [];\n return [text(entry.metadata.tool) ?? 'a tool', ...(names.length === 0 ? [] : [` on ${names.join(', ')}`])];\n}\n\n/** The client a request came through, said after what it did: \"via Claude\". */\nfunction via(entry: AuditEntry): Part[] {\n const client = (entry.metadata.via as { clientName?: unknown } | undefined)?.clientName;\n return typeof client === 'string' ? [` via ${client}`] : [];\n}\n\n/** Why coffre itself ended a connection, said after it. */\nconst DISCONNECTED: Record<string, string> = {\n code_reused: ': its sign-in code was used twice',\n refresh_reused: ': a refresh token it had replaced was used again',\n revocation_endpoint: ', at its own request',\n superseded: ': a connection with more scopes replaced it',\n};\n\nfunction plural(count: number, one: string, many = `${one}s`): string {\n return `${count} ${count === 1 ? one : many}`;\n}\n\n/** A batch reads as its environment and a count; one entry as its secret. */\n/**\n * The secrets a read or write was about. A read through a reference is a\n * read of its source, \"market/prod/DATABASE_URL through\n * billing/prod/DATABASE_URL\"; a run that read some that way is a run of\n * the environment that holds them. A value a fork inherits is its parent's,\n * read in the fork: \"market/prod/STRIPE_KEY in market/prod-eu\".\n */\nfunction secrets(facts: Facts): Part[] {\n const through = (entry: AuditEntry) => text((entry.metadata.via as { path?: unknown } | undefined)?.path);\n // The fork a value was inherited in, by path: in its parent's project, which holds the reference a read went through.\n const forkOf = (entry: AuditEntry) => {\n const slug = text((entry.metadata.through as { slug?: unknown } | undefined)?.slug);\n const project = through(entry)?.split('/')[0] ?? entry.project;\n return slug === null || project === null ? null : `${project}/${slug}`;\n };\n if (facts.batch.length === 1) {\n const [held, fork] = [through(facts.entry), forkOf(facts.entry)];\n return [...place(facts.entry), ...(held === null ? [] : [' through ', { place: held }]), ...(fork === null ? [] : [' in ', { place: fork }])];\n }\n const fork = facts.batch.map(forkOf).find((path) => path !== null);\n const own = facts.batch.find((entry) => through(entry) === null && forkOf(entry) === null);\n const held = facts.batch.map(through).filter((path): path is string => path !== null);\n const inherited = facts.batch.filter((entry) => forkOf(entry) !== null).length;\n const where = fork !== undefined && fork !== null\n ? [{ place: fork }]\n : own !== undefined ? environmentOf(own) : [{ place: held[0]!.split('/').slice(0, 2).join('/') }];\n return [\n ...where,\n facts.refused ? ', ' : ': ',\n plural(facts.count, 'secret'),\n ...(held.length === 0 ? [] : [`, ${held.length} through ${held.length === 1 ? 'a reference' : 'references'}`]),\n ...(inherited === 0 ? [] : [`, ${inherited} inherited`]),\n ];\n}\n\n/** \"market/prod/OLD\", or \"OLD and STALE in market/prod\" for an archive of several keys refused. */\nfunction archivedKeys(entry: AuditEntry): Part[] {\n const keys = Array.isArray(entry.metadata.keys) ? entry.metadata.keys.filter((key): key is string => text(key) !== null) : [];\n if (entry.key !== null || keys.length === 0) return place(entry);\n return [keys.length === 1 ? keys[0]! : `${keys.slice(0, -1).join(', ')} and ${keys.at(-1)!}`, ' in ', ...environmentOf(entry)];\n}\n\n/** \"SENTRY_DSN in market/dev\", or \"3 keys in market/dev\" for a Dismiss all. */\nfunction missingKeys(facts: Facts): Part[] {\n const key = text(facts.entry.metadata.key);\n return [facts.batch.length === 1 && key !== null ? key : plural(facts.count, 'key'), ' in ', ...environmentOf(facts.entry)];\n}\n\n/** \"billing/prod/DATABASE_URL a reference to market/prod/DATABASE_URL\", from either author's entry. */\nfunction referenceTo(entry: AuditEntry): Part[] {\n const holder = text(entry.metadata.subject);\n const key = text(entry.metadata.key);\n const source = text(entry.metadata.source) ?? text((entry.metadata.source as { path?: unknown } | undefined)?.path);\n return [\n ...(holder !== null ? [{ place: holder }] : key !== null ? place(entry) : environmentOf(entry)),\n ...(source === null ? [] : [' a reference to ', { place: source }]),\n ];\n}\n\nconst READ_VERBS: Record<string, [did: string, tried: string]> = {\n reveal: ['revealed', 'reveal'],\n run: ['ran', 'run'],\n compare: ['compared', 'compare'],\n copy: ['copied', 'copy'],\n // The credential proxy's: a value injected into a request for its person, or one handed to their app.\n use: ['used', 'use'],\n expose: ['was given', 'be given'],\n};\n\nfunction readVerb({ entry }: Facts): [string, string] {\n return READ_VERBS[text(entry.metadata.purpose) ?? 'reveal'] ?? READ_VERBS.reveal!;\n}\n\nconst placeTemplates = (kind: 'project' | 'environment'): Record<string, Template> => {\n // A personal config by what it is a config of, `market/dev`: its own slug is generated, and shown nowhere else.\n const of = (entry: AuditEntry): string | null => {\n const parent = text(entry.metadata.personal) ?? text(entry.metadata.with);\n return parent === null || entry.project === null ? null : `${entry.project}/${parent}`;\n };\n const what = (facts: Facts): Part[] => {\n const personal = kind === 'environment' ? of(facts.entry) : null;\n if (personal !== null) return ['a personal config of ', { place: personal }];\n if (kind === 'environment' && facts.entry.metadata.personal === true) return [`a personal config, ${text(facts.entry.metadata.path) ?? ''}`];\n return [`${kind} `, ...(kind === 'project' ? place({ ...facts.entry, environment: null, key: null }) : environmentOf(facts.entry))];\n };\n return {\n [`${kind}.create`]: {\n did: 'created',\n tried: 'create',\n what,\n // A fork names the environment it copied.\n then: ({ entry }) =>\n text(entry.metadata.inherits) !== null\n ? [`, inheriting from ${text(entry.metadata.inherits)}`]\n : text(entry.metadata.from) === null\n ? []\n : [`, a fork of ${text(entry.metadata.from)}`],\n },\n [`${kind}.update`]: { did: 'changed', tried: 'change', what },\n [`${kind}.archive`]: { did: 'archived', tried: 'archive', what },\n [`${kind}.restore`]: { did: 'restored', tried: 'restore', what },\n // Named by its tombstone from then on, `market~deleted-2026-10-05`, as every entry about it is.\n [`${kind}.delete`]: { did: 'deleted', tried: 'delete', what },\n };\n};\n\n// --- one template per action ----------------------------------------------------\n\nconst TEMPLATES: Record<string, Template> = {\n 'secret.read': {\n did: (facts) => readVerb(facts)[0],\n tried: (facts) => readVerb(facts)[1],\n what: secrets,\n },\n 'secret.write': {\n // New secrets are added, others changed; a batch of both is written.\n did: ({ batch }) => {\n const firsts = batch.filter((entry) => entry.version === 1).length;\n return firsts === batch.length ? 'added' : firsts === 0 ? 'changed' : 'wrote';\n },\n tried: 'change',\n what: secrets,\n then: ({ entry, batch }) =>\n batch.length > 1 || entry.version === null || entry.version === 1 ? [] : [`, now version ${entry.version}`],\n },\n // The credential proxy's own entry beside the vault's read: which credential the keys went into, and where.\n 'credential.use': {\n did: ({ entry }) => (entry.metadata.purpose === 'expose' ? 'was given the values of' : 'used the credential'),\n tried: ({ entry }) => (entry.metadata.purpose === 'expose' ? 'be given the values of' : 'use the credential'),\n what: ({ entry }) => [text(entry.metadata.credential) ?? '', ...(text(entry.metadata.host) === null ? [] : [` on ${text(entry.metadata.host)}`])],\n },\n 'secret.restore': {\n did: 'restored',\n tried: 'restore',\n what: ({ entry }) => [...place(entry), ...(number(entry.metadata.from) === null ? [] : [` to version ${number(entry.metadata.from)}`])],\n then: ({ entry }) => (entry.version === null ? [] : [`, now ${entry.version}`]),\n },\n 'secret.rename': {\n did: 'renamed',\n tried: 'rename',\n what: ({ entry }) => [...place(entry), ...(text(entry.metadata.nextKey) === null ? [] : [` to ${text(entry.metadata.nextKey)}`])],\n // In a fork, carried down from a rename in its parent.\n then: ({ entry }) => (text(entry.metadata.parent) === null ? [] : [`, as ${text(entry.metadata.parent)} did`]),\n },\n 'secret.archive': { did: 'archived', tried: 'archive', what: ({ entry }) => archivedKeys(entry) },\n // In a fork: its own value set aside, kept, for its parent's.\n 'secret.reset': {\n did: 'reset',\n tried: 'reset',\n what: ({ entry }) => place(entry),\n then: ({ entry }) => (text(entry.metadata.from) === null ? [] : [` to ${text(entry.metadata.from)}'s value`]),\n },\n 'missing.dismiss': {\n did: 'dismissed',\n tried: 'dismiss',\n what: (facts) => missingKeys(facts),\n then: () => [' as not needed'],\n },\n 'missing.restore': { did: 'restored', tried: 'restore', what: (facts) => missingKeys(facts), then: () => [' to the missing keys'] },\n 'secret.reference': { did: 'made', tried: 'make', what: ({ entry }) => referenceTo(entry) },\n 'reference.create': { did: 'made', tried: 'make', what: ({ entry }) => referenceTo(entry) },\n 'reference.end': {\n did: ({ entry }) => (entry.metadata.reason === 'replaced' ? 'gave a value of its own to' : entry.metadata.reason === 'abandoned' ? 'abandoned' : 'broke'),\n tried: ({ entry }) => (entry.metadata.reason === 'replaced' ? 'replace' : entry.metadata.reason === 'abandoned' ? 'abandon' : 'break'),\n what: ({ entry }) => {\n const source = text((entry.metadata.source as { path?: unknown } | undefined)?.path);\n const holder = text(entry.metadata.subject);\n if (entry.metadata.reason === 'replaced') return [...(holder === null ? ['a reference'] : [{ place: holder }]), ...(source === null ? [] : [', no longer a reference to ', { place: source }])];\n return ['the reference ', ...(holder === null ? [] : [{ place: holder }]), ...(source === null ? [] : [' to ', { place: source }])];\n },\n then: ({ entry }) => (entry.metadata.reason === 'abandoned' ? [', which its write never stored'] : []),\n },\n 'secret.unarchive': { did: 'brought back', tried: 'bring back', what: (facts) => place(facts.entry) },\n 'secret.move': { did: 'moved', tried: 'move', what: (facts) => place(facts.entry), then: ({ entry }) => intoFolder(entry) },\n ...placeTemplates('project'),\n 'project.move': {\n did: 'moved',\n tried: 'move',\n what: ({ entry }) => ['project ', ...place({ ...entry, environment: null, key: null })],\n then: ({ entry }) => intoFolder(entry),\n },\n ...placeTemplates('environment'),\n 'environment.fork': {\n did: 'forked',\n tried: 'fork',\n what: ({ entry }) => [...environmentOf(entry), ...(text(entry.metadata.slug) === null ? [] : [` into ${text(entry.metadata.slug)}`])],\n },\n 'access.grant': {\n did: 'gave',\n tried: 'give',\n what: ({ entry }) => [...subject(entry), ` ${text(entry.metadata.role) ?? 'a role'} on `, ...placeOnly(entry)],\n then: ({ entry }) => [\n ...(text(entry.metadata.previousRole) === null ? [] : [`, was ${text(entry.metadata.previousRole)}`]),\n ...(text(entry.metadata.expiresAt) === null ? [] : [`, until ${text(entry.metadata.expiresAt)!.slice(0, 10)}`]),\n ...(entry.metadata.reason === 'every-project' ? [', for a grant on every project'] : []),\n ],\n },\n 'access.revoke': {\n did: 'took',\n tried: 'take',\n what: ({ entry }) => [\n ...(text(entry.metadata.previousRole ?? entry.metadata.role) === null ? ['access to '] : [`${text(entry.metadata.previousRole ?? entry.metadata.role)} on `]),\n ...placeOnly(entry),\n ' from ',\n ...subject(entry),\n ],\n // The vault replacing a grant on every project of 0.4: by what, an instance role or project grants.\n then: ({ entry }) => {\n const by = entry.metadata.replacedBy as { role?: unknown } | undefined;\n if (by === undefined) return [];\n const role = typeof by.role === 'string' ? roleName(by.role) : null;\n return [role === null || role === 'Member' ? ', replaced by project grants' : `, replaced by the instance role ${role}`];\n },\n },\n 'member.add': {\n did: 'added',\n tried: 'add',\n what: ({ entry }) => [\n ...subject(entry),\n ...(entry.metadata.rootAdmin === true ? [' as a root admin'] : entry.metadata.owner === true ? [' as an owner'] : asRole(entry)),\n ],\n then: ({ entry }) => owned(entry),\n },\n 'member.remove': {\n did: 'removed',\n tried: 'remove',\n what: (facts) => subject(facts.entry),\n then: ({ entry }) => (number(entry.metadata.revoked) === null ? [] : [`, who held ${plural(number(entry.metadata.revoked)!, 'grant')}`]),\n },\n 'member.restore': {\n did: 'brought back',\n tried: 'bring back',\n what: ({ entry }) => [...subject(entry), ...asRole(entry)],\n then: ({ entry }) => owned(entry),\n },\n 'member.role': {\n did: 'made',\n tried: 'make',\n what: ({ entry }) => [...subject(entry), ` ${article(roleName(text(entry.metadata.role) ?? 'member') ?? 'Member')}`, ...scoped(entry)],\n then: ({ entry }) => {\n const before = roleName(text(entry.metadata.previousRole) ?? '');\n return [\n ...(before === null ? [] : [`, was ${before}`]),\n ...(entry.metadata.reason === 'every-project' ? [', for their grants on every project'] : []),\n ...owned(entry),\n ];\n },\n },\n 'member.owner': {\n did: ({ entry }) => (entry.metadata.owner === false ? 'took owner from' : 'made'),\n tried: ({ entry }) => (entry.metadata.owner === false ? 'take owner from' : 'make'),\n what: ({ entry }) => [...subject(entry), ...(entry.metadata.owner === false ? [] : [' an owner'])],\n },\n // Where people set up service accounts themselves, which those who run the instance set.\n 'settings.change': {\n did: 'set',\n tried: 'set',\n what: ({ entry }) => ['where people set up service accounts', ...setting(entry.metadata.serviceAccounts).map((words) => `: ${words}`)],\n then: ({ entry }) => {\n const previous = (entry.metadata.previous as { serviceAccounts?: unknown } | undefined)?.serviceAccounts;\n return setting(previous).map((words) => `, was ${words}`);\n },\n },\n // A binding trusts CI runs to sign in as a service; removing one is its tombstone.\n 'token.bind': {\n did: 'trusted CI runs to sign in as',\n tried: 'trust CI runs to sign in as',\n what: (facts) => subject(facts.entry),\n then: ({ entry }) => [...inGitHubEnvironment(entry), ...reaching(entry)],\n },\n // The tokens and bindings 0.4 made, given their own scope when 0.5 first checked a credential: what their account held then.\n 'token.seal': {\n did: 'sealed',\n tried: 'seal',\n what: ({ entry }) => [`${sealedOf(entry)} of `, ...subject(entry)],\n then: ({ entry }) => reaching(entry, ', reaching nothing'),\n },\n 'token.unbind': {\n did: 'stopped trusting CI runs to sign in as',\n tried: 'stop trusting CI runs to sign in as',\n what: (facts) => subject(facts.entry),\n },\n 'vault.tampered': {\n did: 'found',\n tried: 'check',\n what: ({ entry }) => [\n ...(entry.subject === null ? ['an entry'] : [...subject(entry), \"'s record\"]),\n ` tampered with: ${TAMPERING[entry.reason ?? ''] ?? 'it fails its seal'}`,\n ],\n },\n 'key.rotate': { did: 'rotated its key', tried: 'rotate its key', what: () => [] },\n // An MCP client a person connected, such as Claude: named as the consent page showed it.\n 'mcp.connect': { did: 'connected', tried: 'connect', what: ({ entry }) => app(entry) },\n // A tool an MCP client called, by its name, and the places it named.\n 'mcp.call': { did: 'used', tried: 'use', what: ({ entry }) => tool(entry), then: ({ entry }) => via(entry) },\n // A person's decision, on coffre's page, on a change an MCP client asked for; the change's own entries follow, via the client.\n 'mcp.approve': { did: 'approved', tried: 'approve', what: ({ entry }) => tool(entry), then: ({ entry }) => [` for ${text(entry.metadata.clientName) ?? 'an app'}`] },\n 'mcp.deny': { did: 'turned down', tried: 'turn down', what: ({ entry }) => tool(entry), then: ({ entry }) => [` for ${text(entry.metadata.clientName) ?? 'an app'}`] },\n 'mcp.view': { did: 'opened an approval', tried: 'open an approval', what: () => [] },\n // The app's prompt declined, which cancels the approval it would have opened.\n 'mcp.cancel': { did: 'cancelled', tried: 'cancel', what: ({ entry }) => tool(entry), then: ({ entry }) => via(entry) },\n 'mcp.disconnect': {\n did: 'disconnected',\n tried: 'disconnect',\n what: ({ entry }) => [...app(entry), ...(entry.metadata.principalId === undefined ? [] : [' of ', ...subject(entry)])],\n then: ({ entry }) => [DISCONNECTED[text(entry.metadata.reason) ?? ''] ?? ''],\n },\n\n // Detail, hidden unless asked for.\n sign_in: {\n did: ({ entry }) => (entry.metadata.kind === 'cli' ? 'signed in to the CLI' : 'signed in'),\n tried: 'sign in',\n what: ({ entry }) => (text(entry.metadata.provider) === null ? [] : [`with ${text(entry.metadata.provider)}`]),\n },\n sign_out: { did: 'signed out', tried: 'sign out', what: () => [] },\n // A personal token is its person's own, and named by its label; a bearer token is a service account's.\n 'token.create': {\n did: ({ entry }) => (entry.metadata.kind === 'handle' ? 'made a handle' : personal(entry) ? 'made a personal token' : 'issued a bearer token to'),\n tried: ({ entry }) => (entry.metadata.kind === 'handle' ? 'make a handle' : personal(entry) ? 'make a personal token' : 'issue a bearer token to'),\n what: ({ entry }) => (personal(entry) ? labelled(entry) : subject(entry)),\n then: ({ entry }) => reaching(entry),\n },\n 'token.revoke': {\n did: ({ entry }) => (personal(entry) ? 'revoked a personal token of' : 'revoked a bearer token of'),\n tried: ({ entry }) => (personal(entry) ? 'revoke a personal token of' : 'revoke a bearer token of'),\n what: (facts) => subject(facts.entry),\n },\n // A personal token refused a route only its person reaches: the route, as the API names it.\n 'token.use': {\n did: 'used a personal token for',\n tried: 'use a personal token for',\n what: ({ entry }) => [text(entry.metadata.route) ?? 'something'],\n },\n 'device.approve': { did: 'approved a CLI sign-in', tried: 'approve a CLI sign-in', what: () => [] },\n 'device.deny': { did: 'turned down a CLI sign-in', tried: 'turn down a CLI sign-in', what: () => [] },\n 'mcp.read': { did: 'used', tried: 'use', what: ({ entry }) => tool(entry), then: ({ entry }) => via(entry) },\n 'mcp.token': {\n did: ({ entry }) => (entry.metadata.grant === 'refresh_token' ? 'refreshed the tokens of' : 'gave its first tokens to'),\n tried: 'give tokens to',\n what: ({ entry }) => app(entry),\n },\n 'account.link': {\n did: 'linked',\n tried: 'link',\n what: ({ entry }) => [`a ${text(entry.metadata.provider) ?? 'sign-in'} account`],\n },\n 'account.unlink': {\n did: 'unlinked',\n tried: 'unlink',\n what: ({ entry }) => [`a ${text(entry.metadata.provider) ?? 'sign-in'} account`],\n },\n 'key.wrap': { did: 'sealed the key of', tried: 'seal the key of', what: (facts) => versioned(facts.entry) },\n 'key.rewrap': { did: 'resealed the key of', tried: 'reseal the key of', what: (facts) => versioned(facts.entry) },\n 'key.intent': { did: 'asked KMS about', tried: 'ask KMS about', what: (facts) => secrets(facts) },\n 'key.check': {\n did: 'recorded the check value of',\n tried: 'check',\n what: ({ entry }) => [['the', text(entry.metadata.kekProvider) === 'local' ? null : text(entry.metadata.kekProvider), 'vault key', text(entry.metadata.kekId)].filter((word) => word !== null).join(' ')],\n },\n 'audit.heartbeat': { did: 'checked in', tried: 'check in', what: () => [] },\n 'audit.checkpoint': {\n did: 'signed the log',\n tried: 'sign the log',\n what: ({ entry }) => (number(entry.metadata.seq) === null ? [] : [`through entry ${number(entry.metadata.seq)}`]),\n },\n\n // Only ever refused: a read of a list, which is not logged when allowed.\n 'secret.list': { did: 'listed', tried: 'list', what: ({ entry }) => environmentOf(entry) },\n 'secret.history': { did: 'read the history of', tried: 'read the history of', what: (facts) => place(facts.entry) },\n 'secret.update': { did: 'changed', tried: 'change', what: (facts) => place(facts.entry) },\n};\n\n/** \" to the folder stripe\", or \" out of its folder\". */\nfunction intoFolder(entry: AuditEntry): Part[] {\n const folder = text(entry.metadata.to);\n return [folder === null ? ' out of its folder' : ` to the folder ${folder}`];\n}\n\n/** An instance role's name, from its slug; null for none it knows. */\nfunction roleName(role: string): string | null {\n return isInstanceRole(role) ? INSTANCE_ROLES[role].name : null;\n}\n\nfunction article(name: string): string {\n return `${/^[AEIOU]/.test(name) ? 'an' : 'a'} ${name}`;\n}\n\n/** Whether an entry's scope narrows the role; its projects are ids, which a sentence cannot name. */\nfunction scoped(entry: AuditEntry): Part[] {\n const scope = entry.metadata.scope as { projects?: unknown; environments?: unknown } | undefined;\n return scope === undefined || (scope.projects === 'all' && scope.environments === 'all') ? [] : [', with a scope'];\n}\n\n/**\n * What a token or binding reaches, its scope, each role with the places it\n * holds, counted, as the log names them by id: `, reaching developer on 2 places`.\n */\nfunction reaching(entry: AuditEntry, none = ''): Part[] {\n const scope = entry.metadata.scope;\n if (!Array.isArray(scope)) return [];\n if (scope.length === 0) return none === '' ? [] : [none];\n const byRole = new Map<string, number>();\n for (const grant of scope as { role?: unknown }[]) {\n const role = text(grant.role);\n if (role !== null) byRole.set(role, (byRole.get(role) ?? 0) + 1);\n }\n return [`, reaching ${[...byRole].map(([role, count]) => `${role} on ${plural(count, 'place')}`).join(', ')}`];\n}\n\n/** The GitHub environment a binding takes its runs from, when it names one. */\nfunction inGitHubEnvironment(entry: AuditEntry): Part[] {\n const environment = text((entry.metadata.claims as Record<string, unknown> | undefined)?.environment);\n return environment === null || !String(entry.metadata.profile).startsWith('github') ? [] : [`, in GitHub environment ${environment}`];\n}\n\n/** The tokens and trust bindings a `token.seal` names, counted: `2 tokens and a trust binding`. */\nfunction sealedOf(entry: AuditEntry): string {\n const count = (key: string) => (Array.isArray(entry.metadata[key]) ? (entry.metadata[key] as unknown[]).length : 0);\n const parts = [[count('tokens'), 'token'], [count('bindings'), 'trust binding']] as const;\n return parts.filter(([n]) => n > 0).map(([n, one]) => plural(n, one)).join(' and ') || 'nothing';\n}\n\n/**\n * The setting of where people set up service accounts, in words: its\n * projects counted, as the log names them by id, its environments by name.\n *\n * All projects · all but prod 2 projects · dev only\n */\nfunction setting(scope: unknown): string[] {\n if (!isScope(scope)) return [];\n const { projects } = scope;\n const counted: Scope = projects === 'all'\n ? scope\n : { ...scope, projects: 'only' in projects ? { only: [plural(projects.only.length, 'project')] } : { except: [plural(projects.except.length, 'project')] } };\n return [scopeInWords(counted)];\n}\n\n/** The role a member is added or brought back with, said when it is more than Member. */\nfunction asRole(entry: AuditEntry): Part[] {\n const role = roleName(text(entry.metadata.role) ?? '');\n return role === null || role === 'Member' ? [] : [` as ${article(role)}`, ...scoped(entry)];\n}\n\nfunction placeOnly(entry: AuditEntry): Part[] {\n // A grant on every project names no project: its place is a path in its payload, `*` or `*/dev`.\n const everywhere = entry.project === null ? text(entry.metadata.place) : null;\n if (everywhere !== null) return [everywhere === '*' ? 'every project' : `${everywhere.slice('*/'.length)} in every project`];\n return place({ ...entry, key: null });\n}\n\nfunction versioned(entry: AuditEntry): Part[] {\n return [...place(entry), ...(entry.version === null ? [] : [`, version ${entry.version}`])];\n}\n\nconst TAMPERING: Record<string, string> = {\n mac: \"it does not carry the vault's seal\",\n stale: 'an older copy was put back',\n forged_entry: 'the vault did not write it',\n};\n\n/** Why something was refused, in words. Codes from the vault and the app. */\nconst REASONS: Record<string, string> = {\n no_grant: 'no grant',\n bulk_limit: 'bulk limit',\n stand_ins: 'people get stand-ins',\n expired: 'grant expired',\n removed: 'removed from coffre',\n not_a_member: 'not a member',\n not_registered: 'not invited',\n tampered: 'their record was tampered with',\n bad_claim: 'the key did not match the secret',\n deleted: 'the place was deleted',\n not_allowed: 'not allowed',\n root_admin: 'root admins are set by the deployment',\n last_owner: 'they are the last Owner of the whole instance',\n requires_instance_admin: 'requires an admin or owner of the whole instance',\n requires_instance_owner: 'requires an instance owner',\n own_role: 'nobody changes their own role',\n own_grant: 'nobody grants themselves a role',\n service_cannot_hold_role: 'service accounts hold project grants only',\n not_service_manager: 'they hold less than the service account, or than they gave it',\n unknown_environment: 'no such environment',\n unknown_secret: 'no such secret',\n no_value: 'it holds no value',\n unknown_project: 'no such project',\n not_archived: 'it was not archived',\n referenced: 'references read it',\n kms_unavailable: 'KMS did not answer',\n wrong_kek: \"the vault's key is not the one that wrapped the data\",\n person_denied: 'they said no',\n too_many_connections: 'too many connected apps',\n unknown_connection: 'no such connected app',\n not_yours: \"it was someone else's\",\n too_many_approvals: 'too many changes waiting for approval',\n request_state: 'its retry did not match its call',\n changed: 'the change was not the one shown',\n replaced: 'what it replaces changed since it was shown',\n unconfirmed: 'what it replaces could not be read',\n disconnected: 'the app was disconnected',\n personal_token: 'only its person can, signed in as themselves',\n beyond_holder: 'more than they hold',\n};\n\n/** What a missing permission meant, from the app's `missing_<permission>`. */\nconst MISSING: Record<string, string> = {\n secret_read: 'no grant to read it',\n secret_write: 'no grant to write',\n secret_archive: 'no grant to archive',\n audit_read: 'no grant to read the audit log',\n environment_manage: 'no grant to manage environments',\n grant_manage: 'no grant to manage access',\n project_manage: 'no grant to manage the project',\n};\n\nexport function reasonInWords(reason: string | null): string {\n if (reason === null) return 'refused';\n if (reason.startsWith('missing_')) return MISSING[reason.slice('missing_'.length)] ?? 'no grant';\n return REASONS[reason] ?? reason.replace(/_/g, ' ');\n}\n\n// --- lines ----------------------------------------------------------------------\n\n/** In a batch of mixed actions, the one the line is named for: a write, not its reads. */\nconst LEAD = ['secret.write', 'secret.read'];\n\nexport function leadOf(batch: AuditEntry[]): AuditEntry {\n for (const action of LEAD) {\n const found = batch.find((entry) => entry.action === action);\n if (found !== undefined) return found;\n }\n return batch[0]!;\n}\n\n/**\n * A read of several secrets, logged once for its place, as the entries it\n * would be about one secret each: its key and version, and what its own\n * part of the metadata says, such as the reference it went through. Any\n * other entry as it is.\n */\nexport function perSecret<T extends AuditEntry>(entry: T): T[] {\n const listed = entry.metadata.secrets;\n // One whose list was emptied or mangled, which verification would flag, still reads as itself.\n if (entry.secrets === null || entry.secrets.length === 0 || !Array.isArray(listed)) return [entry];\n return entry.secrets.map(({ key, version }, i) => {\n const own = listed[i];\n return {\n ...entry,\n key,\n version,\n secrets: null,\n metadata: { ...entry.metadata, secrets: undefined, ...(typeof own === 'object' && own !== null && !Array.isArray(own) ? own : {}) },\n };\n });\n}\n\n/** What a line says: one entry, or a batch that shares an operation. */\nexport function describe(batch: AuditEntry[]): Sentence {\n const entry = perSecret(leadOf(batch))[0]!;\n const same = batch.filter((other) => other.action === entry.action).flatMap(perSecret);\n const denied = same.filter((other) => other.decision === 'deny');\n const refused = denied.length === same.length;\n const facts: Facts = {\n entry,\n batch: same,\n count: new Set(same.map((other) => `${other.project}/${other.environment}/${other.key}`)).size,\n refused,\n };\n const template = TEMPLATES[entry.action];\n if (template === undefined) return { parts: [entry.action, ' ', ...place(entry)], refused };\n const say = (verb: Template['did']) => (typeof verb === 'string' ? verb : verb(facts));\n const what = template.what(facts);\n const gap = what.length === 0 ? [] : [' '];\n if (refused) {\n const reason = reasonInWords((denied[0] ?? entry).reason);\n return { parts: ['tried to ', say(template.tried), ...gap, ...what, `: ${reason}`], refused };\n }\n const partly = denied.length === 0 ? [] : [`, ${denied.length} refused: ${reasonInWords(denied[0]!.reason)}`];\n return { parts: [say(template.did), ...gap, ...what, ...(template.then?.(facts) ?? []), ...partly], refused };\n}\n\n/** Who acted, as a part: a member links to their page; coffre itself is text. */\nexport function who(entry: Pick<AuditEntry, 'actorType' | 'actorId'>): string | { member: string } {\n if (entry.actorType === 'user') return { member: `user:${entry.actorId}` };\n if (entry.actorType === 'service') return { member: `token:${entry.actorId}` };\n return SYSTEM[entry.actorId] ?? entry.actorId;\n}\n\nconst SYSTEM: Record<string, string> = {\n scheduler: 'the scheduler',\n cron: 'the scheduler',\n vault: 'the vault',\n app: 'coffre',\n};\n\n/** Which components wrote the line, the vault first: \"vault\", \"app\", \"vault, app\". */\nexport function decidedBy(batch: Pick<AuditEntry, 'author'>[]): string {\n return (['vault', 'app'] as const).filter((author) => batch.some((entry) => entry.author === author)).join(', ');\n}\n\n/**\n * Entries in the order the page shows them, newest first, each batch as one\n * line at its newest entry. The server leaves detail out unless asked.\n */\nexport function lines<T extends AuditEntry>(entries: T[]): T[][] {\n const shown: T[][] = [];\n const batches = new Map<string, T[]>();\n for (const entry of entries) {\n const batch = entry.operationId === null ? undefined : batches.get(entry.operationId);\n if (batch !== undefined) {\n batch.push(entry);\n continue;\n }\n const fresh = [entry];\n if (entry.operationId !== null) batches.set(entry.operationId, fresh);\n shown.push(fresh);\n }\n return shown;\n}\n\n/** A sentence as text. */\nexport function plain(parts: Part[]): string {\n return parts\n .map((part) =>\n typeof part === 'string' ? part : 'place' in part ? part.place : part.member.startsWith('user:') ? part.member.slice(5) : shownMember(part.member),\n )\n .join('');\n}\n\n/**\n * The CI run an entry was written for, as its issuer stated it at the\n * exchange: `acme/api run 7001 at 3f2a9c1`, a GitLab pipeline, or the\n * token's subject. Null for an entry no trust binding's credential wrote.\n */\nexport function runLabel(run: { claims: Record<string, string | number> } | null): string | null {\n if (run === null) return null;\n const { claims } = run;\n const text = (name: string) => (typeof claims[name] === 'string' || typeof claims[name] === 'number' ? String(claims[name]) : null);\n const at = text('sha') === null ? '' : ` at ${text('sha')!.slice(0, 7)}`;\n if (text('repository') !== null && text('run_id') !== null) return `${text('repository')} run ${text('run_id')}${at}`;\n if (text('project_path') !== null && text('pipeline_id') !== null) return `${text('project_path')} pipeline ${text('pipeline_id')}${at}`;\n return text('sub') === null ? 'a CI run' : `CI run ${text('sub')}`;\n}\n","import { serviceName, shownMember } from '@coffre/client';\nimport { Fragment } from 'react';\nimport { Link } from '@tanstack/react-router';\nimport type { Part } from '../lib/audit-sentences';\nimport { breakAfterUnderscores } from './ui';\n\n/** A sentence, its people and places links to their pages. */\nexport function Sentence({ parts }: { parts: Part[] }) {\n return (\n <>\n {parts.map((part, index) => (\n <Fragment key={index}>\n {typeof part === 'string' ? (\n part\n ) : 'place' in part ? (\n <PlaceLink path={part.place} />\n ) : (\n <MemberLink member={part.member} />\n )}\n </Fragment>\n ))}\n </>\n );\n}\n\nfunction PlaceLink({ path }: { path: string }) {\n const [project, environment] = path.split('/') as [string, string | undefined];\n const text = <span className=\"mono\">{breakAfterUnderscores(path)}</span>;\n return environment === undefined ? (\n <Link to=\"/projects/$project\" params={{ project }}>\n {text}\n </Link>\n ) : (\n <Link to=\"/projects/$project/$environment\" params={{ project, environment }}>\n {text}\n </Link>\n );\n}\n\n/** A member from the log, which keeps `token:<name>`, shown as people read it: `service:<name>`, to its page. */\nfunction MemberLink({ member }: { member: string }) {\n return member.startsWith('token:') ? (\n <Link to=\"/service-accounts/$account\" params={{ account: serviceName(member) }}>\n {shownMember(member)}\n </Link>\n ) : (\n <Link to=\"/users/$user\" params={{ user: memberName(member) }}>\n {memberName(member)}\n </Link>\n );\n}\n\nexport function memberName(member: string): string {\n return member.startsWith('user:') ? member.slice('user:'.length) : shownMember(member);\n}\n"],"mappings":";;;;;;;AAiEA,IAAM,QAAQ,UAAmC,OAAO,UAAU,YAAY,UAAU,KAAK,QAAQ;AACrG,IAAM,UAAU,UAAmC,OAAO,UAAU,WAAW,QAAQ;;AAGvF,SAAS,MAAM,EAAE,SAAS,aAAa,OAA2B;CAChE,MAAM,OAAO;EAAC;EAAS;EAAa;CAAG,CAAC,CAAC,QAAQ,SAAyB,SAAS,IAAI;CACvF,OAAO,KAAK,WAAW,IAAI,CAAC,QAAQ,IAAI,CAAC,EAAE,OAAO,KAAK,KAAK,GAAG,EAAE,CAAC;AACpE;AAEA,SAAS,cAAc,EAAE,SAAS,eAAmC;CACnE,OAAO,MAAM;EAAE;EAAS;EAAa,KAAK;CAAK,CAAe;AAChE;;AAGA,SAAS,QAAQ,OAA2B;CAC1C,IAAI,MAAM,YAAY,MAAM,OAAO,CAAC,EAAE,QAAQ,MAAM,QAAQ,CAAC;CAC7D,MAAM,KAAK,KAAK,MAAM,SAAS,WAAW;CAC1C,IAAI,OAAO,MAAM,OAAO,CAAC,SAAS;CAClC,OAAO,CAAC,EAAE,QAAQ,GAAG,MAAM,SAAS,kBAAkB,YAAY,UAAU,OAAO,GAAG,KAAK,CAAC;AAC9F;;AAGA,SAAS,SAAS,OAA4B;CAC5C,OAAO,MAAM,SAAS,SAAS;AACjC;;AAGA,SAAS,SAAS,OAA2B;CAC3C,MAAM,QAAQ,KAAK,MAAM,SAAS,KAAK;CACvC,OAAO,UAAU,OAAO,CAAC,IAAI,CAAC,KAAK,MAAM,EAAE;AAC7C;;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AAM,IAAG;EAAe,QAAQ,EAAE,MAAM,WAAW,MAAM,EAAE;YACxD,WAAW,MAAM;CACd,CAAA;AAEV;AAEA,SAAgB,WAAW,QAAwB;CACjD,OAAO,OAAO,WAAW,OAAO,IAAI,OAAO,MAAM,CAAc,IAAI,YAAY,MAAM;AACvF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"use-change-CQyDpCqw.js","names":[],"sources":["../../src/lib/project-access.ts","../../src/lib/recipes.ts","../../src/lib/secret-edit-batch.ts","../../src/lib/changes.ts","../../src/lib/optimistic.ts","../../src/lib/use-change.ts"],"sourcesContent":["import { ROLES, type Role } from '@coffre/core/access';\n\nimport type { GrantRow, ProjectSummary, RoleRow } from '../shared/models';\n\n/** The roles the project's access picker offers, a product choice; others show by their names. */\nexport type ProjectAccessRole = Extract<Role, 'owner' | 'viewer' | 'developer'>;\n\nexport type ProjectAccessOption = {\n value: string;\n role: ProjectAccessRole;\n environmentSlug: string | null;\n label: string;\n};\n\nexport function projectAccessOptions(\n environments: ProjectSummary['environments'],\n): ProjectAccessOption[] {\n const options: ProjectAccessOption[] = [\n {\n value: 'owner:',\n role: 'owner',\n environmentSlug: null,\n label: ROLES.owner.name,\n },\n ];\n\n for (const role of ['viewer', 'developer'] as const) {\n options.push({\n value: `${role}:`,\n role,\n environmentSlug: null,\n label: `${ROLES[role].name}: all`,\n });\n }\n\n for (const environment of environments) {\n if (environment.details === null || environment.details.archivedAt !== null) continue;\n for (const role of ['viewer', 'developer'] as const) {\n options.push({\n value: `${role}:${environment.slug}`,\n role,\n environmentSlug: environment.slug,\n label: `${ROLES[role].name}: ${environment.slug}`,\n });\n }\n }\n\n return options;\n}\n\nexport function parseProjectAccess(value: string): {\n role: ProjectAccessRole;\n environmentSlug: string | null;\n} {\n const [role, environmentSlug = ''] = value.split(':', 2);\n if (role !== 'owner' && role !== 'viewer' && role !== 'developer') {\n throw new Error('unknown project access level');\n }\n return { role, environmentSlug: environmentSlug || null };\n}\n\n/** \"Owner\", \"Viewer: all\" or \"Developer: prod\": a grant by its role's name, and where. */\nexport function projectAccessLabel(\n grant: Pick<GrantRow, 'role' | 'roleName' | 'environmentSlug'>,\n): string {\n const name = Object.hasOwn(ROLES, grant.role) ? ROLES[grant.role as Role].name : grant.roleName;\n if (grant.role === 'owner') return name;\n return `${name}: ${grant.environmentSlug ?? 'all'}`;\n}\n\nexport function projectAccessRoles(\n roles: RoleRow[],\n environmentSlug: string | null,\n currentRole?: string,\n): RoleRow[] {\n const allowed = new Set(\n environmentSlug === null\n ? ['owner', 'viewer', 'developer']\n : ['viewer', 'developer'],\n );\n if (currentRole) allowed.add(currentRole);\n return roles.filter((role) => allowed.has(role.slug));\n}\n\n/** A project on someone's Access tab: their grants there, or why those could not be read. */\nexport type ProjectAccess = { project: ProjectSummary; grants: GrantRow[]; grantsError: string | null };\n\n/** A row of the Access tab: one of their grants, or a project whose grants could not be read. */\nexport type AccessRow =\n | { project: ProjectSummary; grant: GrantRow; error: null }\n | { project: ProjectSummary; grant: null; error: string };\n\n/**\n * The Access tab's rows, project by project: a row per grant, and a project\n * whose read failed keeps a row of its own that says why, so a failure\n * never reads as no access.\n */\nexport function accessRows(access: ProjectAccess[]): AccessRow[] {\n return access.flatMap(({ project, grants, grantsError }): AccessRow[] =>\n grantsError === null\n ? grants.map((grant) => ({ project, grant, error: null }))\n : [{ project, grant: null, error: grantsError }],\n );\n}\n","import type { SecretKey } from '@coffre/client';\nimport type { Generation } from '@coffre/core/recipe';\n\n/**\n * A listed key's recipe, as far as the page may act on it: a key pair's\n * only while the list holds both its halves, live, each saying the same of\n * the pair. The server lists a pair by that rule; this holds the page to it\n * between a change shown at once and the list read back, while a value\n * typed over one half, or an archive, has not reached the other half yet.\n */\nexport function liveGeneration(entry: SecretKey, entries: readonly SecretKey[]): Generation | null {\n const { generated } = entry;\n if (generated === null || generated.pair === undefined) return generated;\n const { pair, recipe } = generated;\n const holds = (key: string) =>\n entries.some(\n (each) =>\n each.key === key &&\n !each.archived &&\n each.generated?.recipe === recipe &&\n each.generated.pair?.private === pair.private &&\n each.generated.pair.public === pair.public,\n );\n return holds(pair.private) && holds(pair.public) ? generated : null;\n}\n\n/**\n * The list after keys were renamed, `from` to `to`: each pair names its\n * halves as they are now, in both halves, as the server lists them.\n */\nexport function renamePairs(entries: readonly SecretKey[], renames: ReadonlyMap<string, string>): SecretKey[] {\n if (renames.size === 0) return [...entries];\n const now = (key: string) => renames.get(key) ?? key;\n return entries.map((entry) =>\n entry.generated?.pair === undefined\n ? entry\n : {\n ...entry,\n generated: {\n ...entry.generated,\n pair: { private: now(entry.generated.pair.private), public: now(entry.generated.pair.public) },\n },\n },\n );\n}\n\n/** The keys regenerating a key writes: itself, or a key pair's two halves. */\nexport function regeneratedKeys(key: string, generated: Generation): string[] {\n return generated.pair === undefined ? [key] : [generated.pair.private, generated.pair.public];\n}\n\n/**\n * Whether a key's Regenerate waits: while the key, or either half of its\n * pair, is busy, being edited or with a save on its way. A regenerate\n * addresses keys by name, so one sent beside a rename of a half could land\n * on either side of it: before, and the rename fails with the old name\n * holding the old private key beside a new public key; after, and it\n * writes the old name again. Regenerate's own save marks every key it\n * writes busy (`regenerateSecret`), so neither half is edited meanwhile.\n */\nexport function regenerateWaits(key: string, generated: Generation, busy: (key: string) => boolean): boolean {\n return [key, ...regeneratedKeys(key, generated)].some(busy);\n}\n","import type { Generation } from '@coffre/core/recipe';\n\n/**\n * A second secret a row writes with its own value, in the same patch: a\n * generated key pair's public key, beside its private key. It is part of\n * the row's edit, so saving, undoing or retrying the row takes both.\n */\nexport type Companion = { key: string; value: string };\n\nexport type SecretDraft = {\n id: number;\n key: string;\n value: string;\n companion?: Companion;\n /** The recipe a generated value was made by, saved with it; typing over the value drops it. */\n recipe?: string;\n};\n\nexport type SecretChange = {\n key: string;\n value: string | null;\n archived: boolean;\n /** Only beside a new value. */\n companion?: Companion;\n /** Only beside a generated value. */\n recipe?: string;\n};\n\ntype ActiveSecret = { key: string };\n\n/**\n * A merge patch: a string sets a key, adding it if it is new; a value with\n * how it was generated sets it with its recipe; `null` archives it.\n */\nexport type SecretPatch = Record<string, string | { value: string; generated: Generation } | null>;\n\n/**\n * How a row's generated value was made, as its write says it: its recipe,\n * and for a key pair the names both halves are saved under.\n */\nfunction generationOf(key: string, edit: { recipe?: string; companion?: Companion }): Generation | undefined {\n if (edit.recipe === undefined) return undefined;\n return edit.companion === undefined\n ? { recipe: edit.recipe }\n : { recipe: edit.recipe, pair: { private: key, public: edit.companion.key.trim() } };\n}\n\n/** What a row writes under each key: its value, and its companion's beside it. */\nfunction rowPatch(key: string, value: string, edit: { recipe?: string; companion?: Companion }): SecretPatch {\n const generated = generationOf(key, edit);\n const entry = (each: string) => (generated === undefined ? each : { value: each, generated });\n const patch: SecretPatch = Object.create(null);\n patch[key] = entry(value);\n if (edit.companion !== undefined) patch[edit.companion.key.trim()] = entry(edit.companion.value);\n return patch;\n}\n\n/**\n * The recipe each key a save writes will hold, by its name after the save:\n * what the list shows of it until it is read back.\n */\nexport function generationsOf(\n active: readonly ActiveSecret[],\n drafts: readonly SecretDraft[],\n changes: Readonly<Record<string, SecretChange>>,\n): Map<string, Generation> {\n const out = new Map<string, Generation>();\n const add = (key: string, edit: { recipe?: string; companion?: Companion }) => {\n const generated = generationOf(key, edit);\n if (generated === undefined) return;\n out.set(key, generated);\n if (edit.companion !== undefined) out.set(edit.companion.key.trim(), generated);\n };\n for (const draft of drafts) add(draft.key.trim(), draft);\n for (const entry of active) {\n const change = secretChangeFor(changes, entry.key);\n if (change !== undefined && !change.archived && change.value !== null) add(change.key.trim(), change);\n }\n return out;\n}\n\ntype SecretEditOperations = {\n rename: (key: string, nextKey: string) => Promise<void>;\n /** One transaction: every key in it lands, or none does. */\n write: (patch: SecretPatch) => Promise<void>;\n};\n\ntype PlannedEdit = { sourceKey: string; change: SecretChange };\n\nexport function secretChangeFor(\n changes: Readonly<Record<string, SecretChange>>,\n key: string,\n): SecretChange | undefined {\n return Object.hasOwn(changes, key) ? changes[key] : undefined;\n}\n\nexport type SecretEditBatchResult = {\n applied: number;\n drafts: SecretDraft[];\n changes: Record<string, SecretChange>;\n error: unknown | null;\n};\n\n/**\n * The companions a save writes: those of new rows, and of value edits to keys\n * still listed. An edit whose key went from the list (renamed or archived\n * elsewhere, then refreshed) writes nothing, its companion included.\n */\nexport function companionsOf(\n active: readonly ActiveSecret[],\n drafts: readonly SecretDraft[],\n changes: Readonly<Record<string, SecretChange>>,\n): Companion[] {\n return [\n ...drafts.flatMap((draft) => (draft.companion === undefined ? [] : [draft.companion])),\n ...active.flatMap((entry) => {\n const change = secretChangeFor(changes, entry.key);\n return change === undefined || change.archived || change.value === null || change.companion === undefined\n ? []\n : [change.companion];\n }),\n ];\n}\n\n/** Return true when one save would give two pending edits the same target. */\nexport function hasSecretEditConflict(\n active: readonly ActiveSecret[],\n drafts: readonly SecretDraft[],\n changes: Readonly<Record<string, SecretChange>>,\n): boolean {\n const finalActiveKeys = active\n .filter((entry) => !secretChangeFor(changes, entry.key)?.archived)\n .map((entry) => secretChangeFor(changes, entry.key)?.key.trim() ?? entry.key);\n if (new Set(finalActiveKeys).size !== finalActiveKeys.length) return true;\n\n // A companion writes its key as a new row does.\n const draftKeys = [...drafts, ...companionsOf(active, drafts, changes)].map((draft) => draft.key.trim());\n if (new Set(draftKeys).size !== draftKeys.length) return true;\n\n const valueEditTargets = new Set(\n active.flatMap((entry) => {\n const change = secretChangeFor(changes, entry.key);\n return change !== undefined && !change.archived && change.value !== null\n ? [change.key.trim()]\n : [];\n }),\n );\n if (draftKeys.some((key) => valueEditTargets.has(key))) return true;\n\n const archivedKeys = new Set(\n active\n .filter((entry) => secretChangeFor(changes, entry.key)?.archived)\n .map((entry) => entry.key),\n );\n return draftKeys.some((key) => archivedKeys.has(key));\n}\n\n/**\n * Save every pending edit: renames first, one call each, then everything else\n * as one merge patch.\n *\n * The patch is a single transaction, so values, new keys and archives land\n * together or not at all. Renames cannot join it: a merge patch names keys and\n * has no way to move one with its history. A failed rename therefore stops the\n * save before the patch. The renames before it stay done, and every other edit\n * is kept for the retry, a value following its key to the new name.\n */\nexport async function applySecretEditBatch({\n active,\n drafts,\n changes,\n operations,\n}: {\n active: readonly ActiveSecret[];\n drafts: readonly SecretDraft[];\n changes: Readonly<Record<string, SecretChange>>;\n operations: SecretEditOperations;\n}): Promise<SecretEditBatchResult> {\n const remainingChanges = { ...changes };\n const plan = planEdits(active, drafts, changes);\n if (plan instanceof Error) {\n return { applied: 0, drafts: [...drafts], changes: remainingChanges, error: plan };\n }\n\n let applied = 0;\n // A key named `__proto__` is a key like any other.\n const patch: SecretPatch = Object.create(null);\n try {\n for (const { sourceKey, change } of plan) {\n if (change.archived) {\n patch[sourceKey] = null;\n continue;\n }\n const key = change.key.trim();\n if (key !== sourceKey) {\n await operations.rename(sourceKey, key);\n delete remainingChanges[sourceKey];\n applied += 1;\n if (change.value !== null) remainingChanges[key] = { ...change, key };\n }\n if (change.value !== null) Object.assign(patch, rowPatch(key, change.value, change));\n }\n for (const draft of drafts) Object.assign(patch, rowPatch(draft.key.trim(), draft.value, draft));\n\n const written = Object.keys(patch).length;\n if (written > 0) await operations.write({ ...patch });\n return { applied: applied + written, drafts: [], changes: {}, error: null };\n } catch (error) {\n return { applied, drafts: [...drafts], changes: remainingChanges, error };\n }\n}\n\n/**\n * Put dependent renames in an order that frees each destination first.\n * Cycles and archive-then-restore plans fail before the first mutation.\n */\nfunction planEdits(\n active: readonly ActiveSecret[],\n drafts: readonly SecretDraft[],\n changes: Readonly<Record<string, SecretChange>>,\n): PlannedEdit[] | Error {\n const activeKeys = new Set(active.map((entry) => entry.key));\n const archivedKeys = new Set(\n active\n .filter((entry) => secretChangeFor(changes, entry.key)?.archived)\n .map((entry) => entry.key),\n );\n const restoredByDraft = [...drafts, ...companionsOf(active, drafts, changes)].find((draft) =>\n archivedKeys.has(draft.key.trim()),\n );\n if (restoredByDraft) {\n return new Error(\n `${restoredByDraft.key.trim()}: cannot archive and write the same key in one save`,\n );\n }\n\n const renames = new Map<string, SecretChange>();\n const otherEdits: PlannedEdit[] = [];\n for (const entry of active) {\n const change = secretChangeFor(changes, entry.key);\n if (change === undefined) continue;\n if (!change.archived && change.key.trim() !== entry.key) {\n renames.set(entry.key, change);\n } else {\n otherEdits.push({ sourceKey: entry.key, change });\n }\n }\n\n for (const [sourceKey, change] of renames) {\n const destination = change.key.trim();\n if (activeKeys.has(destination) && !renames.has(destination)) {\n return new Error(`${sourceKey}: ${destination} is already in use`);\n }\n }\n\n const orderedRenames: PlannedEdit[] = [];\n const freedKeys = new Set<string>();\n while (renames.size > 0) {\n const ready = [...renames].find(([, change]) => {\n const destination = change.key.trim();\n return !activeKeys.has(destination) || freedKeys.has(destination);\n });\n if (!ready) {\n return new Error('Secret renames contain a cycle. Save them in separate steps.');\n }\n const [sourceKey, change] = ready;\n renames.delete(sourceKey);\n freedKeys.add(sourceKey);\n orderedRenames.push({ sourceKey, change });\n }\n\n return [...orderedRenames, ...otherEdits];\n}\n","import type { CoffreClient, ConnectedApp, IdentityRow, MissingKey, OffboardingReport, SecretKey, SessionRow, TokenRow } from '@coffre/client';\nimport { EVERYWHERE, unscoped, type InstanceRole, type Role, type Scope } from '@coffre/core/access';\nimport type { QueryKey } from '@tanstack/react-query';\n\nimport { failureMessage, memberRef, Refusal } from './coffre.ts';\nimport { projectAccessLabel } from './project-access.ts';\nimport type { Change, ListShape, Target, Words } from './optimistic.ts';\nimport { affects, keys } from './queries.ts';\nimport { regenerateWrite, type Generation } from '@coffre/core/recipe';\nimport { regeneratedKeys, renamePairs } from './recipes.ts';\nimport { applySecretEditBatch, companionsOf, generationsOf, type SecretChange, type SecretDraft, type SecretEditBatchResult } from './secret-edit-batch.ts';\nimport type { DirectoryPrincipal, GrantRow, ProjectSummary } from '../shared/models.ts';\n\n/**\n * Every change the pages make before the server answers, one per kind, each\n * with the list it shows in (`lib/optimistic.ts`). Issuing a token is not\n * here: only the server can show what it issued.\n */\n\ntype Failure = { ok: false; error: string };\n\n/** A list held in a read's `field`, when the read answered. */\nfunction listOf<TItem, TData extends { ok: boolean } | null>(\n queryKey: QueryKey,\n field: string,\n id: (item: TItem) => string,\n): ListShape<TData, TItem> {\n return {\n queryKey,\n items: (data) => (data?.ok === true ? ((data as unknown as Record<string, TItem[]>)[field] ?? []) : []),\n withItems: (data, items) => (data?.ok === true ? { ...data, [field]: items } : data),\n id,\n };\n}\n\nconst ARCHIVING: Words = { pending: 'Archiving…', done: 'archived', failed: 'Not archived.' };\nconst REVOKING: Words = { pending: 'Revoking…', done: 'revoked', failed: 'Not revoked.' };\nconst DISCONNECTING: Words = { pending: 'Disconnecting…', done: 'disconnected', failed: 'Not disconnected.' };\nconst MOVING: Words = { pending: 'Moving…', done: 'moved', failed: 'Not moved.' };\nconst REGENERATING: Words = { pending: 'Regenerating…', done: 'regenerated', failed: 'Not regenerated.' };\n\nconst saving = (id: string): Target => ({ id, kind: 'saving' });\nconst removing = (id: string): Target => ({ id, kind: 'removing' });\n\n// --- access --------------------------------------------------------------------\n\ntype Grants = ({ ok: true; grants: GrantRow[] } | Failure);\n\n/** A grant's identity, before the server has given it an id: who, and where; or who, by their instance role. */\nexport function grantId(grant: Pick<GrantRow, 'principalType' | 'principalId' | 'environmentSlug'> & { scope?: GrantRow['scope'] }): string {\n const member = memberRef(grant.principalType, grant.principalId);\n return grant.scope === 'instance-role' ? `${member}#role` : `${member}@${grant.environmentSlug ?? ''}`;\n}\n\nexport function grantsList(project: string) {\n return listOf<GrantRow, Grants>(keys.grants(project), 'grants', grantId);\n}\n\n/** Where a grant applies, as the API names it: `market`, or `market/prod`. */\nexport function grantPlace(project: string, environmentSlug: string | null): string {\n return environmentSlug === null ? project : `${project}/${environmentSlug}`;\n}\n\nexport type GrantVars = {\n principalType: GrantRow['principalType'];\n principalId: string;\n role: string;\n /** How the role is shown while it saves. */\n roleName: string;\n environmentSlug: string | null;\n expiresAt: string | null;\n /** A new service account, which the grant makes in the same call: refused, neither is made. */\n admit?: boolean;\n};\n\n/**\n * Give someone a role at one place. Access is declarative, so asking for what\n * they already hold is not an error, whoever asked first: `existed` says so.\n */\nexport function grantAccess(client: CoffreClient, project: string): Change<Grants, GrantRow, GrantVars, { existed: boolean }> {\n const list = grantsList(project);\n return {\n list,\n label: (vars) => `${vars.roleName} for ${vars.principalId}`,\n targets: (vars) => [saving(grantId(vars))],\n apply: (grants, vars) => {\n const row: GrantRow = {\n id: `pending:${grantId(vars)}`,\n principalType: vars.principalType,\n principalId: vars.principalId,\n role: vars.role,\n roleName: vars.roleName,\n permissions: [],\n scope: vars.environmentSlug === null ? 'project' : 'environment',\n environmentSlug: vars.environmentSlug,\n expiresAt: vars.expiresAt,\n };\n const id = grantId(vars);\n return grants.some((grant) => grantId(grant) === id)\n ? grants.map((grant) => (grantId(grant) === id ? { ...row, id: grant.id } : grant))\n : [...grants, row];\n },\n affects: (vars) => [\n ...affects.access(project, memberRef(vars.principalType, vars.principalId)),\n ...(vars.admit === true ? affects.admission(memberRef(vars.principalType, vars.principalId)) : []),\n ],\n run: async (vars) => {\n const place = grantPlace(project, vars.environmentSlug);\n const role = vars.role as Role;\n const member = memberRef(vars.principalType, vars.principalId);\n const access = { [place]: vars.expiresAt === null ? role : { role, until: vars.expiresAt } };\n const { changes } = vars.admit === true ? await client.members.add(member, { access }) : await client.access.set(member, access);\n return { existed: changes?.[place] === 'unchanged' };\n },\n };\n}\n\nexport function revokeGrant(client: CoffreClient, project: string): Change<Grants, GrantRow, GrantRow, unknown> {\n return {\n list: grantsList(project),\n label: (grant) => `${projectAccessLabel(grant)} for ${grant.principalId}`,\n targets: (grant) => [removing(grantId(grant))],\n removing: REVOKING,\n affects: (grant) => affects.access(project, memberRef(grant.principalType, grant.principalId)),\n run: (grant) =>\n client.access.set(memberRef(grant.principalType, grant.principalId), {\n [grantPlace(project, grant.environmentSlug)]: null,\n }),\n };\n}\n\n// --- the directory -------------------------------------------------------------\n\ntype Directory = ({ ok: true; principals: DirectoryPrincipal[] } | Failure);\n\nconst principalId = (principal: Pick<DirectoryPrincipal, 'principalType' | 'principalId'>) =>\n memberRef(principal.principalType, principal.principalId);\n\n/** The directory as admins and owners read it: the only ones who change it. */\nexport const directoryList = listOf<DirectoryPrincipal, Directory>([...keys.directory, { owner: true }], 'principals', principalId);\n\n/** A person's instance role and where it applies, projects by slug: what Add and Change role set. */\nexport type RoleVars = { role: InstanceRole; scope: Scope };\n\nexport type InviteVars = { principalType: DirectoryPrincipal['principalType']; principalId: string } & RoleVars;\n\n/** What the API takes for a role: the scope only when it narrows anything. */\nfunction roleInput({ role, scope }: RoleVars): RoleVars | { role: InstanceRole } {\n return role === 'member' || unscoped(scope) ? { role } : { role, scope };\n}\n\nexport function invite(client: CoffreClient): Change<Directory, DirectoryPrincipal, InviteVars, void> {\n return {\n list: directoryList,\n label: (vars) => vars.principalId,\n targets: (vars) => [saving(principalId(vars))],\n // Someone already listed is not added twice: the server will say they exist.\n apply: (principals, vars) =>\n principals.some((principal) => principalId(principal) === principalId(vars)) ? principals : [\n ...principals,\n {\n principalType: vars.principalType,\n principalId: vars.principalId,\n instanceRole: vars.principalType === 'user' ? vars.role : 'member',\n scope: vars.principalType === 'user' ? vars.scope : EVERYWHERE,\n },\n ],\n affects: (vars) => affects.admission(principalId(vars)),\n run: async (vars) => {\n // Adding is an idempotent PUT that would also set the role of someone\n // already here; this is only for someone new.\n const member = memberRef(vars.principalType, vars.principalId);\n const { members } = await client.members.list();\n if (members.some((entry) => entry.member === member)) throw new Refusal('That principal already exists.');\n await client.members.add(member, vars.principalType === 'user' ? roleInput(vars) : {});\n },\n };\n}\n\nexport function changeRole(client: CoffreClient): Change<Directory, DirectoryPrincipal, { principalId: string } & RoleVars, unknown> {\n const id = (vars: { principalId: string }) => memberRef('user', vars.principalId);\n return {\n list: directoryList,\n label: (vars) => `the role of ${vars.principalId}`,\n targets: (vars) => [saving(id(vars))],\n apply: (principals, vars) =>\n principals.map((principal) =>\n principalId(principal) === id(vars) ? { ...principal, instanceRole: vars.role, scope: vars.scope } : principal,\n ),\n affects: (vars) => affects.role(id(vars)),\n run: (vars) => client.members.add(id(vars), roleInput(vars)),\n };\n}\n\nexport function removeMember(client: CoffreClient): Change<Directory, DirectoryPrincipal, DirectoryPrincipal, unknown> {\n return {\n list: directoryList,\n label: (principal) => principal.principalId,\n targets: (principal) => [removing(principalId(principal))],\n affects: (principal) => affects.removal(principalId(principal)),\n run: (principal) => client.members.remove(principalId(principal)),\n };\n}\n\n// --- credentials, sessions, linked accounts --------------------------------------\n\ntype Credentials = ({ ok: true; tokens: TokenRow[] } | Failure) | null;\n\n/** Revoking a member's token: a service account's bearer token, on its page, or a personal token of your own, on your account. */\nexport function revokeCredential(client: CoffreClient, member: string): Change<Credentials, TokenRow, TokenRow, unknown> {\n return {\n list: listOf<TokenRow, Credentials>([...keys.credentials(member), { allowed: true }], 'tokens', (token) => token.id),\n label: (token) => `token ${token.hint}`,\n targets: (token) => [removing(token.id)],\n removing: REVOKING,\n affects: () => affects.credentials(member),\n run: (token) => client.tokens.revoke(member, token.id),\n };\n}\n\ntype Binding = { id: string; label: string | null };\ntype Bindings = ({ ok: true; bindings: Binding[] } | Failure) | null;\n\n/** Removing a trust binding: its tombstone, as far as the page goes, is the row leaving. */\nexport function removeBinding(client: CoffreClient, serviceId: string): Change<Bindings, Binding, Binding, unknown> {\n const member = memberRef('service', serviceId);\n return {\n list: listOf<Binding, Bindings>([...keys.bindings(member), { allowed: true }], 'bindings', (binding) => binding.id),\n label: (binding) => (binding.label === null ? 'the binding' : `binding ${binding.label}`),\n targets: (binding) => [removing(binding.id)],\n removing: { pending: 'Removing…', done: 'removed', failed: 'Not removed.' },\n affects: () => affects.bindings(member),\n run: (binding) => client.bindings.remove(member, binding.id),\n };\n}\n\ntype Sessions = ({ ok: true; sessions: SessionRow[] } | Failure);\n\nexport function endSession(client: CoffreClient): Change<Sessions, SessionRow, SessionRow, unknown> {\n return {\n list: listOf<SessionRow, Sessions>(keys.sessions, 'sessions', (session) => session.id),\n label: () => 'the session',\n targets: (session) => [removing(session.id)],\n removing: { pending: 'Ending…', done: 'ended', failed: 'Not ended.' },\n affects: () => affects.sessions(),\n run: (session) => client.sessions.revoke(session.id),\n };\n}\n\ntype Apps = ({ ok: true; apps: ConnectedApp[] } | Failure);\n\nexport function disconnectApp(client: CoffreClient): Change<Apps, ConnectedApp, ConnectedApp, unknown> {\n return {\n list: listOf<ConnectedApp, Apps>(keys.apps, 'apps', (app) => app.id),\n label: (app) => app.name,\n targets: (app) => [removing(app.id)],\n removing: DISCONNECTING,\n affects: () => affects.apps(),\n run: (app) => client.apps.disconnect(app.id),\n };\n}\n\ntype Report = { ok: true; report: OffboardingReport | null } | Failure | null;\n\n/** Whoever runs the instance revoking someone's personal token, on their page: their report lists it, as they read it. */\nexport function revokeMemberToken(client: CoffreClient, member: string): Change<Report, TokenRow, TokenRow, unknown> {\n return {\n list: {\n queryKey: [...keys.report(member), { owner: true }],\n items: (data) => (data?.ok === true ? (data.report?.personalTokens ?? []) : []),\n withItems: (data, personalTokens) => (data?.ok === true && data.report !== null ? { ...data, report: { ...data.report, personalTokens } } : data),\n id: (token) => token.id,\n },\n label: (token) => `token ${token.hint}`,\n targets: (token) => [removing(token.id)],\n removing: REVOKING,\n // Their report counts what removing them would end; the list on their account is theirs to read again.\n affects: () => [keys.report(member), keys.credentials(member)],\n run: (token) => client.tokens.revoke(member, token.id),\n };\n}\n\n/** An owner disconnecting someone's app, on their page: their report lists it, as the owner reads it. */\nexport function disconnectMemberApp(client: CoffreClient, member: string): Change<Report, ConnectedApp, ConnectedApp, unknown> {\n return {\n list: {\n queryKey: [...keys.report(member), { owner: true }],\n items: (data) => (data?.ok === true ? (data.report?.apps ?? []) : []),\n withItems: (data, apps) => (data?.ok === true && data.report !== null ? { ...data, report: { ...data.report, apps } } : data),\n id: (app) => app.id,\n },\n label: (app) => app.name,\n targets: (app) => [removing(app.id)],\n removing: DISCONNECTING,\n // Their report counts what removing them would end; an owner's own apps may be among them.\n affects: () => [keys.report(member), ...affects.apps()],\n run: (app) => client.apps.disconnect(app.id),\n };\n}\n\ntype Identities = ({ ok: true; identities: IdentityRow[] } | Failure);\n\nexport function unlinkIdentity(client: CoffreClient): Change<Identities, IdentityRow, IdentityRow & { label: string }, unknown> {\n return {\n list: listOf<IdentityRow, Identities>(keys.identities, 'identities', (identity) => identity.id),\n label: (identity) => `the ${identity.label} account`,\n targets: (identity) => [removing(identity.id)],\n removing: { pending: 'Unlinking…', done: 'unlinked', failed: 'Not unlinked.' },\n affects: () => affects.identities(),\n run: (identity) => client.identities.unlink(identity.id),\n };\n}\n\n// --- projects and environments ---------------------------------------------------\n\ntype Projects = ({ ok: true; projects: ProjectSummary[] } | Failure);\n\nexport const projectsList = listOf<ProjectSummary, Projects>(keys.projects, 'projects', (project) => project.slug);\n\nexport function createProject(client: CoffreClient): Change<Projects, ProjectSummary, { slug: string }, void> {\n return {\n list: projectsList,\n label: (vars) => `project ${vars.slug}`,\n targets: (vars) => [saving(vars.slug)],\n apply: (projects, vars) => [\n ...projects,\n {\n slug: vars.slug,\n name: vars.slug,\n archivedAt: null,\n folder: null,\n // Its maker manages it by their instance role, an Admin's or an Owner's.\n permissions: ['audit.read', 'environment.manage', 'grant.manage', 'project.manage'],\n environments: [],\n secretCount: null,\n },\n ],\n affects: () => affects.places(),\n run: async (vars) => {\n // Creating is an idempotent PUT; a slug that is taken is refused here.\n const { created } = await client.projects.create(vars.slug);\n if (!created) throw new Refusal(`A project named \"${vars.slug}\" already exists.`);\n },\n };\n}\n\ntype Environment = ProjectSummary['environments'][number];\n\n/** One project's environments, held in the project list. */\n/** File a project in a folder, or in none: shown at once, under its new heading. */\nexport function moveProject(client: CoffreClient): Change<Projects, ProjectSummary, { slug: string; folder: string | null }, unknown> {\n return {\n list: projectsList,\n label: (vars) => `project ${vars.slug}`,\n targets: (vars) => [saving(vars.slug)],\n apply: (projects, vars) => projects.map((project) => (project.slug === vars.slug ? { ...project, folder: vars.folder } : project)),\n affects: () => affects.places(),\n run: (vars) => client.projects.update(vars.slug, { folder: vars.folder }),\n };\n}\n\nexport function environmentsList(project: string): ListShape<Projects, Environment> {\n const environmentsOf = (data: Projects) =>\n data.ok ? (data.projects.find((entry) => entry.slug === project)?.environments ?? []) : [];\n return {\n queryKey: keys.projects,\n items: environmentsOf,\n withItems: (data, environments) =>\n data.ok\n ? { ...data, projects: data.projects.map((entry) => (entry.slug === project ? { ...entry, environments } : entry)) }\n : data,\n // Under the project's name: the projects list, in the same read, uses bare slugs.\n id: (environment) => environmentId(project, environment.slug),\n };\n}\n\nexport function environmentId(project: string, environment: string): string {\n return `${project}/${environment}`;\n}\n\n/** A new environment, empty or, `from` a sibling, forked: each of its keys copied. */\nexport function createEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, { slug: string; from?: string; references?: boolean; inherit?: boolean }, void> {\n return {\n list: environmentsList(project),\n label: (vars) => `environment ${vars.slug}`,\n targets: (vars) => [saving(environmentId(project, vars.slug))],\n apply: (environments, vars) => [\n ...environments,\n { slug: vars.slug, name: vars.slug, accessible: false, parent: vars.inherit === true ? (vars.from ?? null) : null, personal: false, details: { archivedAt: null, secretCount: 0 } },\n ],\n affects: () => affects.places(),\n run: async (vars) => {\n const { created } = await client.environments.create(`${project}/${vars.slug}`, {\n ...(vars.from === undefined ? {} : { from: vars.from }),\n ...(vars.references === true ? { references: true } : {}),\n ...(vars.inherit === true ? { inherit: true } : {}),\n });\n if (!created) throw new Refusal(`An environment named \"${vars.slug}\" already exists.`);\n },\n };\n}\n\nexport type RenameVars = { from: string; slug: string };\n\nexport function renameEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, RenameVars, unknown> {\n return {\n list: environmentsList(project),\n label: (vars) => `environment ${vars.from}`,\n targets: (vars) =>\n vars.slug === vars.from\n ? [saving(environmentId(project, vars.from))]\n : [saving(environmentId(project, vars.from)), saving(environmentId(project, vars.slug))],\n apply: (environments, vars) =>\n environments.map((environment) =>\n environment.slug === vars.from ? { ...environment, slug: vars.slug } : environment,\n ),\n affects: () => affects.places(),\n run: (vars) => client.environments.update(`${project}/${vars.from}`, { slug: vars.slug }),\n };\n}\n\n/**\n * Archive an environment or bring it back. Archiving ends every read of it,\n * so it waits for the server, as a removal does; restoring shows at once.\n */\nexport function archiveEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, { slug: string; archived: boolean }, unknown> {\n const archivedAt = (archived: boolean) => (archived ? new Date().toISOString() : null);\n const withArchived = (environment: Environment, archived: boolean): Environment =>\n environment.details === null\n ? environment\n : { ...environment, details: { ...environment.details, archivedAt: archivedAt(archived) } };\n return {\n list: environmentsList(project),\n label: (vars) => `environment ${vars.slug}`,\n targets: (vars) => [\n vars.archived ? removing(environmentId(project, vars.slug)) : saving(environmentId(project, vars.slug)),\n ],\n removing: ARCHIVING,\n apply: (environments, vars) =>\n vars.archived\n ? environments\n : environments.map((environment) => (environment.slug === vars.slug ? withArchived(environment, false) : environment)),\n confirmed: (environments, _vars, archived) =>\n environments.map((environment) =>\n archived.has(environmentId(project, environment.slug)) ? withArchived(environment, true) : environment,\n ),\n affects: () => affects.places(),\n run: (vars) => client.environments.update(`${project}/${vars.slug}`, { archived: vars.archived }),\n };\n}\n\n// --- secrets ---------------------------------------------------------------------\n\ntype Secrets = ({ ok: true; keys: SecretKey[] } | Failure);\n\nexport function secretsList(place: { project: string; environment: string }) {\n return listOf<SecretKey, Secrets>(keys.secrets(place), 'keys', (entry) => entry.key);\n}\n\n/** A save that stopped partway: what is left to retry, as the ledger holds it. */\nexport class UnsavedEdits extends Refusal {\n readonly outcome: SecretEditBatchResult;\n\n constructor(outcome: SecretEditBatchResult) {\n const message = outcome.error instanceof Error ? outcome.error.message : failureMessage(outcome.error);\n // Only renames can have landed before a failure: the patch is all or nothing.\n super(\n outcome.applied === 0\n ? message\n : `${message} The renames before it were saved; nothing else was, and the rest is ready to retry.`,\n );\n this.outcome = outcome;\n }\n}\n\nexport type SaveSecretsVars = {\n active: SecretKey[];\n drafts: SecretDraft[];\n changes: Record<string, SecretChange>;\n};\n\n/**\n * Write the ledger's pending edits, as `applySecretEditBatch` does: renames\n * one by one, then the rest as one patch that lands whole or not at all.\n * New and edited secrets show at once; archived ones stay, struck through,\n * until the server confirms.\n */\nexport function saveSecrets(\n client: CoffreClient,\n place: { project: string; environment: string },\n /** Who is saving, shown as the author until the list is read back. */\n author: string | null,\n): Change<Secrets, SecretKey, SaveSecretsVars, number> {\n const path = `${place.project}/${place.environment}`;\n const edits = (vars: SaveSecretsVars) =>\n vars.active.flatMap((entry) => {\n const change = vars.changes[entry.key];\n return change === undefined ? [] : [{ entry, change }];\n });\n // A key pair's public key lands as a new row would, beside its private key.\n const written = (vars: SaveSecretsVars) => [...vars.drafts, ...companionsOf(vars.active, vars.drafts, vars.changes)];\n return {\n list: secretsList(place),\n label: (vars) => {\n const named = [...vars.drafts.map((draft) => draft.key.trim()), ...edits(vars).map(({ entry }) => entry.key)];\n return named.length === 1 ? named[0]! : `${named.length} changes`;\n },\n targets: (vars) => [\n ...written(vars).map((draft) => saving(draft.key.trim())),\n ...edits(vars).flatMap(({ entry, change }) =>\n change.archived\n ? [removing(entry.key)]\n : change.key.trim() === entry.key\n ? [saving(entry.key)]\n : [saving(entry.key), saving(change.key.trim())],\n ),\n ],\n removing: ARCHIVING,\n apply: (entries, vars) => {\n const now = new Date().toISOString();\n // A value typed by hand has no recipe; a generated one has the one it was made by.\n const generations = generationsOf(vars.active, vars.drafts, vars.changes);\n const bumped = (entry: SecretKey | undefined, key: string): SecretKey => {\n // In a fork, a value written over the parent's is an override, whose own version the list read back says.\n const inherited = entry?.parent != null && entry.parent.state !== 'overridden' && entry.key === key;\n return {\n key,\n // A rename keeps its folder; a new secret is in none.\n folder: entry?.folder ?? null,\n // A value of its own: no longer a reference.\n reference: null,\n archived: false,\n version: inherited ? null : (entry?.version ?? 0) + 1,\n // Known once the list is read back: until then, nothing regenerates it.\n versionId: null,\n updatedAt: now,\n updatedBy: author,\n generated: generations.get(key) ?? null,\n parent: entry?.parent == null || entry.key !== key ? null : { ...entry.parent, state: 'overridden', changed: false, reset: false },\n };\n };\n const renames = new Map<string, string>();\n let next = entries.map((entry) => {\n const change = vars.changes[entry.key];\n if (change === undefined || change.archived) return entry;\n const key = change.key.trim();\n if (key !== entry.key) renames.set(entry.key, key);\n return change.value === null ? { ...entry, key } : bumped(entry, key);\n });\n // A rename moves no value: a pair it touches names the new key, in both halves.\n next = renamePairs(next, renames);\n for (const draft of written(vars)) {\n const key = draft.key.trim();\n const existing = next.find((entry) => entry.key === key);\n next = existing === undefined ? [bumped(undefined, key), ...next] : next.map((entry) => (entry.key === key ? bumped(entry, key) : entry));\n }\n return next;\n },\n confirmed: (entries, _vars, archived) =>\n entries.map((entry) => (archived.has(entry.key) ? { ...entry, archived: true } : entry)),\n affects: () => affects.secrets(place),\n run: async (vars) => {\n const outcome = await applySecretEditBatch({\n active: vars.active,\n drafts: vars.drafts,\n changes: vars.changes,\n operations: {\n rename: async (key, nextKey) => {\n try {\n await client.secrets.rename(`${path}/${key}`, nextKey);\n } catch (error) {\n // A refused rename names the key it stopped at.\n throw new Refusal(`${key}: ${failureMessage(error)}`);\n }\n },\n write: async (patch) => {\n try {\n await client.secrets.set(path, patch);\n } catch (error) {\n throw new Refusal(failureMessage(error));\n }\n },\n },\n });\n if (outcome.error !== null) throw new UnsavedEdits(outcome);\n return outcome.applied;\n },\n };\n}\n\n/** File a secret in a folder, or in none: shown at once, under its new heading. */\nexport function moveSecret(\n client: CoffreClient,\n place: { project: string; environment: string },\n): Change<Secrets, SecretKey, { key: string; folder: string | null }, unknown> {\n return {\n list: secretsList(place),\n saving: MOVING,\n label: (vars) => vars.key,\n targets: (vars) => [saving(vars.key)],\n apply: (entries, vars) => entries.map((entry) => (entry.key === vars.key ? { ...entry, folder: vars.folder } : entry)),\n affects: () => affects.secrets(place),\n run: (vars) => client.secrets.update(`${place.project}/${place.environment}/${vars.key}`, { folder: vars.folder }),\n };\n}\n\n/** What Regenerate is asked: the key, its recipe, and the version id of each key it writes, as listed. */\nexport type RegenerateVars = { key: string; generated: Generation; versions: Readonly<Record<string, string>> };\n\n/**\n * Regenerate a key by its recipe: the value made in this browser as the\n * change runs, and sent at once, never on the page. Each key it writes, a\n * key pair's two halves, shows it pending, so neither is edited, renamed\n * or regenerated again until it lands. The server holds it to the versions\n * listed, which settles a race with any other write.\n */\nexport function regenerateSecret(\n client: CoffreClient,\n place: { project: string; environment: string },\n /** Who is regenerating, shown as the author until the list is read back. */\n author: string | null,\n): Change<Secrets, SecretKey, RegenerateVars, unknown> {\n const path = `${place.project}/${place.environment}`;\n return {\n list: secretsList(place),\n saving: REGENERATING,\n label: (vars) => regeneratedKeys(vars.key, vars.generated).join(' and '),\n targets: (vars) => regeneratedKeys(vars.key, vars.generated).map(saving),\n apply: (entries, vars) => {\n const keys = new Set(regeneratedKeys(vars.key, vars.generated));\n const now = new Date().toISOString();\n return entries.map((entry) => {\n if (!keys.has(entry.key)) return entry;\n // In a fork, regenerating a key it inherits writes an override here, never the parent:\n // its own version is the one the list read back says.\n const inherited = entry.parent != null && entry.parent.state !== 'overridden';\n return {\n ...entry,\n reference: null,\n version: inherited ? null : (entry.version ?? 0) + 1,\n versionId: null,\n updatedAt: now,\n updatedBy: author,\n generated: vars.generated,\n parent: entry.parent == null ? null : { ...entry.parent, state: 'overridden', changed: false, reset: false },\n };\n });\n },\n affects: () => affects.secrets(place),\n // Each key replaces the version the page listed, or the server refuses the write.\n run: async (vars) => client.secrets.set(path, await regenerateWrite(vars.key, vars.generated, (key) => (Object.hasOwn(vars.versions, key) ? vars.versions[key]! : null))),\n };\n}\n\n/** Restore an archived secret, from the Archived list. */\nexport function restoreSecret(\n client: CoffreClient,\n place: { project: string; environment: string },\n): Change<Secrets, SecretKey, { key: string }, unknown> {\n return {\n list: secretsList(place),\n label: (vars) => vars.key,\n targets: (vars) => [saving(vars.key)],\n apply: (entries, vars) => entries.map((entry) => (entry.key === vars.key ? { ...entry, archived: false } : entry)),\n affects: () => affects.secrets(place),\n run: (vars) => client.secrets.update(`${place.project}/${place.environment}/${vars.key}`, { archived: false }),\n };\n}\n\n/** Archive one secret, as Undo after a restore does: it stays, struck through, until confirmed. */\nexport function archiveSecret(\n client: CoffreClient,\n place: { project: string; environment: string },\n): Change<Secrets, SecretKey, { key: string }, unknown> {\n return {\n list: secretsList(place),\n label: (vars) => vars.key,\n targets: (vars) => [removing(vars.key)],\n removing: ARCHIVING,\n confirmed: (entries, _vars, archived) =>\n entries.map((entry) => (archived.has(entry.key) ? { ...entry, archived: true } : entry)),\n affects: () => affects.secrets(place),\n run: (vars) => client.secrets.update(`${place.project}/${place.environment}/${vars.key}`, { archived: true }),\n };\n}\n\n/**\n * In a fork, a key's standing to its parent's (docs/design/forking.md):\n * `remove` does without the parent's key and `restore` inherits it again,\n * a dismissal and its end; `reset` drops an override for the parent's\n * value, its own kept, and `override` serves its own again. Each shows at\n * once, and is undone by its opposite.\n */\nexport type ForkAction = 'remove' | 'restore' | 'reset' | 'override';\n\nconst FORK_WORDS: Record<ForkAction, Words> = {\n remove: { pending: 'Removing…', done: 'removed', failed: 'Not removed.' },\n restore: { pending: 'Restoring…', done: 'restored', failed: 'Not restored.' },\n reset: { pending: 'Resetting…', done: 'reset', failed: 'Not reset.' },\n override: { pending: 'Overriding…', done: 'overridden', failed: 'Not overridden.' },\n};\n\nexport function forkKey(\n client: CoffreClient,\n place: { project: string; environment: string },\n action: ForkAction,\n): Change<Secrets, SecretKey, { key: string }, unknown> {\n const path = `${place.project}/${place.environment}`;\n const standing = (entry: SecretKey): SecretKey => {\n if (entry.parent === null) return entry;\n switch (action) {\n // Not served: nothing of the parent's value is shown for it.\n case 'remove':\n return { ...entry, reference: null, version: null, updatedAt: null, updatedBy: null, parent: { ...entry.parent, state: 'removed' } };\n // The parent's value, which the list read back brings.\n case 'restore':\n case 'reset':\n return { ...entry, parent: { ...entry.parent, state: 'inherited', changed: false, reset: action === 'reset' || entry.parent.reset } };\n case 'override':\n return { ...entry, parent: { ...entry.parent, state: 'overridden', changed: false, reset: false } };\n }\n };\n return {\n list: secretsList(place),\n saving: FORK_WORDS[action],\n label: (vars) => vars.key,\n targets: (vars) => [saving(vars.key)],\n // A removal of a key the parent archived since, restored, leaves nothing to list.\n apply: (entries, vars) => entries.flatMap((entry) =>\n entry.key !== vars.key ? [entry] : action === 'restore' && entry.parent?.held === false ? [] : [standing(entry)]),\n affects: () => affects.secrets(place),\n run: (vars) =>\n action === 'remove' || action === 'restore'\n ? client.environments.dismiss(path, { [vars.key]: action === 'remove' ? true : null })\n : client.secrets.inherit(`${path}/${vars.key}`, action === 'reset'),\n };\n}\n\n// --- missing keys ----------------------------------------------------------------\n\ntype Missing = ({ ok: true; missing: MissingKey[] } | Failure);\n\nexport function missingList(place: { project: string; environment: string }) {\n return listOf<MissingKey, Missing>(keys.missing(place), 'missing', (entry) => entry.key);\n}\n\nconst DISMISSING: Words = { pending: 'Dismissing…', done: 'dismissed', failed: 'Not dismissed.' };\nconst RESTORING: Words = { pending: 'Restoring…', done: 'restored', failed: 'Not restored.' };\n\n/**\n * Dismiss missing keys for the whole team. It shows at once: a dismissal\n * hides nothing anyone may read, so it need not wait for the server, and a\n * refusal puts the keys back.\n */\nexport function dismissMissing(client: CoffreClient, place: { project: string; environment: string }) {\n return missingChange(client, place, true);\n}\n\n/** Bring dismissed keys back, as Undo after a dismissal does: listed again at once. */\nexport function restoreMissing(client: CoffreClient, place: { project: string; environment: string }) {\n return missingChange(client, place, false);\n}\n\nfunction missingChange(\n client: CoffreClient,\n place: { project: string; environment: string },\n dismissed: boolean,\n): Change<Missing, MissingKey, MissingKey[], unknown> {\n return {\n list: missingList(place),\n saving: dismissed ? DISMISSING : RESTORING,\n label: (entries) => (entries.length === 1 ? entries[0]!.key : `${entries.length} missing keys`),\n targets: (entries) => entries.map((entry) => saving(entry.key)),\n apply: (entries, named) => {\n const names = new Set(named.map((entry) => entry.key));\n const others = entries.filter((entry) => !names.has(entry.key));\n // Listed by name, as the server lists them.\n return dismissed ? others : [...others, ...named].sort((a, b) => (a.key < b.key ? -1 : 1));\n },\n affects: () => [],\n run: (entries) =>\n client.environments.dismiss(\n `${place.project}/${place.environment}`,\n Object.fromEntries(entries.map((entry) => [entry.key, dismissed ? true : null])),\n ),\n };\n}\n","import type { Mutation, MutationOptions, QueryClient, QueryKey } from '@tanstack/react-query';\n\nimport { announce } from './announce.ts';\nimport { failureMessage } from './coffre.ts';\nimport { refresh } from './queries.ts';\n\n/**\n * Changes that show before the server answers.\n *\n * An add or an edit shows at once, as it will be, marked as saving; a removal\n * keeps its row, struck through, until the server confirms it, since access\n * must never look gone while it still holds. Either way, if the server\n * refuses, the list goes back to what it was and the row says why\n * (`failureMessage`: the API's own sentence where it gives one), until\n * dismissed or retried.\n *\n * Several changes can be in flight at once, so a failure undoes its own\n * items only, not the whole list as it was when it started; and the list is\n * read back from the server once the last change to it has landed, so one\n * landing does not erase another still on its way.\n */\n\n/** What a row is waiting for. */\nexport type Pending = 'saving' | 'removing';\n\n/** One item a change touches, and how. */\nexport type Target = { id: string; kind: Pending };\n\n/** How a change is worded on its row: \"Archiving…\", \"Not archived.\" */\nexport type Words = { pending: string; done: string; failed: string };\n\nconst WORDS: Record<Pending, Words> = {\n saving: { pending: 'Saving…', done: 'saved', failed: 'Not saved.' },\n removing: { pending: 'Removing…', done: 'removed', failed: 'Not removed.' },\n};\n\n/** How one cached query holds a list of items, each with an identity. */\nexport type ListShape<TData, TItem> = {\n queryKey: QueryKey;\n items: (data: TData) => TItem[];\n withItems: (data: TData, items: TItem[]) => TData;\n id: (item: TItem) => string;\n};\n\nexport type Change<TData, TItem, TVars, TResult> = {\n list: ListShape<TData, TItem>;\n /** What the change is called, for the screen reader: \"access for dev@acme.example\". */\n label: (vars: TVars) => string;\n /**\n * The items it touches, whose rows show it: saved ones as they will be,\n * removed ones as they are until confirmed. A rename touches both names.\n */\n targets: (vars: TVars) => Target[];\n /** How saves are worded, when not as saves: dismissing. */\n saving?: Words;\n /** How removals are worded, when not as removals: archiving, revoking. */\n removing?: Words;\n /** The items as they will be once the saves land; removals are left for the server. */\n apply?: (items: TItem[], vars: TVars) => TItem[];\n /** The items once the server confirms; by default, without those removed. Archiving keeps them, archived. */\n confirmed?: (items: TItem[], vars: TVars, removed: ReadonlySet<string>) => TItem[];\n /** Anything else it touches, refetched once it lands (`affects` in `queries.ts`). */\n affects: (vars: TVars, result: TResult | undefined) => QueryKey[];\n run: (vars: TVars) => Promise<TResult>;\n};\n\n/** What `onMutate` keeps: the list as it was, and what the rows should show. */\nexport type ChangeContext = { previous: unknown; targets: Target[]; words: Record<Pending, Words> };\n\n/** Every optimistic change is keyed under this, then its list's key. */\nexport const CHANGE = 'change';\n\nexport function changeKey(list: QueryKey): QueryKey {\n return [CHANGE, ...list];\n}\n\nexport function changeOptions<TData, TItem, TVars, TResult>(\n queryClient: QueryClient,\n change: Change<TData, TItem, TVars, TResult>,\n): MutationOptions<TResult, unknown, TVars, ChangeContext> {\n const { list } = change;\n const mutationKey = changeKey(list.queryKey);\n return {\n mutationKey,\n mutationFn: change.run,\n onMutate: async (vars) => {\n const targets = change.targets(vars);\n const words = { saving: change.saving ?? WORDS.saving, removing: change.removing ?? WORDS.removing };\n announce(`${change.label(vars)}: ${words[mainKind(targets)].pending}`);\n // A read already on its way would land over the change.\n await queryClient.cancelQueries({ queryKey: list.queryKey });\n const previous = queryClient.getQueryData<TData>(list.queryKey);\n if (change.apply !== undefined && previous !== undefined) {\n const apply = change.apply;\n queryClient.setQueryData<TData>(list.queryKey, (current) =>\n current === undefined ? current : list.withItems(current, apply(list.items(current), vars)),\n );\n }\n return { previous, targets, words };\n },\n onError: (error, vars, context) => {\n if (context === undefined) return;\n announce(\n `${change.label(vars)}: ${context.words[mainKind(context.targets)].failed} ${failureMessage(error)}`,\n { urgent: true },\n );\n if (context.previous === undefined || change.apply === undefined) return;\n const previous = context.previous as TData;\n const saved = context.targets.filter((target) => target.kind === 'saving').map((target) => target.id);\n queryClient.setQueryData<TData>(list.queryKey, (current) =>\n current === undefined ? current : revert(list, current, previous, saved),\n );\n },\n onSuccess: (_result, vars, context) => {\n if (context === undefined) return;\n announce(`${capitalize(change.label(vars))} ${context.words[mainKind(context.targets)].done}`);\n // Confirmed: the rows removed can go now, before the list is read back.\n const gone = new Set(\n context.targets.filter((target) => target.kind === 'removing').map((target) => target.id),\n );\n if (gone.size > 0) {\n const confirmed =\n change.confirmed ?? ((items: TItem[]) => items.filter((item) => !gone.has(list.id(item))));\n queryClient.setQueryData<TData>(list.queryKey, (current) =>\n current === undefined ? current : list.withItems(current, confirmed(list.items(current), vars, gone)),\n );\n }\n },\n onSettled: (result, _error, vars) => {\n // This one still counts as in flight here.\n if (queryClient.isMutating({ mutationKey }) > 1) return;\n // Not awaited: the row settles when the server answers, and the list\n // is read back behind it.\n void refresh(queryClient, [list.queryKey, ...change.affects(vars, result)]);\n },\n };\n}\n\n/**\n * The list with one change undone: each target as it was before, wherever\n * it now is, and gone if it was not there. Everything else stays as it is,\n * including other changes still in flight.\n */\nexport function revert<TData, TItem>(\n list: ListShape<TData, TItem>,\n current: TData,\n previous: TData,\n targets: string[],\n): TData {\n const before = list.items(previous);\n let items = list.items(current).filter((item) => !targets.includes(list.id(item)));\n for (const id of targets) {\n const index = before.findIndex((item) => list.id(item) === id);\n if (index === -1) continue;\n // Back where it was, counting only what is still there before it.\n const after = before\n .slice(0, index)\n .filter((item) => items.some((kept) => list.id(kept) === list.id(item))).length;\n items = [...items.slice(0, after), before[index]!, ...items.slice(after)];\n }\n return list.withItems(current, items);\n}\n\n/** What a change mostly does, to word it as a whole: a save, unless it only removes. */\nfunction mainKind(targets: Target[]): Pending {\n return targets.length > 0 && targets.every((target) => target.kind === 'removing') ? 'removing' : 'saving';\n}\n\n/** What a row shows: nothing, a change on its way, or one the server refused. */\nexport type ItemStatus =\n | { state: 'idle' }\n | { state: 'pending'; kind: Pending; words: Words }\n | { state: 'failed'; kind: Pending; words: Words; error: string; mutationId: number };\n\ntype Tracked = Pick<Mutation<unknown, unknown, unknown, ChangeContext>, 'mutationId' | 'state'>;\n\n/**\n * An item's status, from the changes to its list: the latest one that\n * touches it decides, so retrying clears an old failure.\n */\nexport function itemStatus(changes: readonly Tracked[], id: string): ItemStatus {\n let latest: Tracked | undefined;\n for (const change of changes) {\n if (change.state.context?.targets.some((target) => target.id === id) !== true) continue;\n if (latest === undefined || change.state.submittedAt >= latest.state.submittedAt) latest = change;\n }\n const context = latest?.state.context;\n if (latest === undefined || context === undefined) return { state: 'idle' };\n const kind = context.targets.find((target) => target.id === id)!.kind;\n const words = context.words[kind];\n if (latest.state.status === 'pending') return { state: 'pending', kind, words };\n if (latest.state.status === 'error') {\n const error = failureMessage(latest.state.error);\n return { state: 'failed', kind, words, error, mutationId: latest.mutationId };\n }\n return { state: 'idle' };\n}\n\n/** A refused add: no row is left to say so, so it gets one of its own. */\nexport type FailedAdd<TVars> = {\n mutationId: number;\n vars: TVars;\n /** The ids it would have added. */\n ids: string[];\n status: Extract<ItemStatus, { state: 'failed' }>;\n};\n\n/**\n * The adds the server refused whose items are not listed: each is shown as\n * a row of its own. Asked again and refused again, an add is listed once,\n * as the latest refusal.\n */\nexport function failedAdds<TVars>(changes: readonly Tracked[], present: readonly string[]): FailedAdd<TVars>[] {\n return changes.flatMap((change) => {\n const context = change.state.context;\n if (change.state.status !== 'error' || context === undefined) return [];\n const added = context.targets.filter((target) => target.kind === 'saving' && !present.includes(target.id));\n if (added.length === 0 || added.length < context.targets.length) return [];\n const status = itemStatus(changes, added[0]!.id);\n if (status.state !== 'failed' || status.mutationId !== change.mutationId) return [];\n const ids = added.map((target) => target.id);\n return [{ mutationId: change.mutationId, vars: change.state.variables as TVars, ids, status }];\n });\n}\n\n/** Forget a failure once its row has said so and been dismissed. */\nexport function dismiss(queryClient: QueryClient, mutationId: number): void {\n const cache = queryClient.getMutationCache();\n const mutation = cache.getAll().find((entry) => entry.mutationId === mutationId);\n if (mutation !== undefined) cache.remove(mutation);\n}\n\nfunction capitalize(text: string): string {\n return text.charAt(0).toUpperCase() + text.slice(1);\n}\n","import { useMutation, useMutationState, useQueryClient, type QueryKey } from '@tanstack/react-query';\nimport { useCallback } from 'react';\n\nimport {\n changeKey,\n changeOptions,\n dismiss,\n failedAdds,\n itemStatus,\n type Change,\n type ChangeContext,\n} from './optimistic';\n\n/** Make a change that shows before the server answers (`lib/optimistic.ts`). */\nexport function useChange<TData, TItem, TVars, TResult>(change: Change<TData, TItem, TVars, TResult>) {\n const queryClient = useQueryClient();\n return useMutation(changeOptions(queryClient, change)).mutate;\n}\n\n/** How each item of a list stands, from the changes made to it here. */\nexport function useChangeStatus(list: QueryKey) {\n const queryClient = useQueryClient();\n const changes = useMutationState({\n filters: { mutationKey: changeKey(list) },\n select: (mutation) => ({\n mutationId: mutation.mutationId,\n state: mutation.state as typeof mutation.state & { context: ChangeContext | undefined },\n }),\n });\n\n const status = useCallback((id: string) => itemStatus(changes, id), [changes]);\n\n /** Adds the server refused, whose items are not in `present`: rendered as rows of their own. */\n const refusedAdds = useCallback(\n <TVars,>(present: readonly string[]) => failedAdds<TVars>(changes, present),\n [changes],\n );\n\n const forget = useCallback((mutationId: number) => dismiss(queryClient, mutationId), [queryClient]);\n\n return { status, failedAdds: refusedAdds, dismiss: forget };\n}\n"],"mappings":";;;;;;;;AAcA,SAAgB,qBACd,cACuB;CACvB,MAAM,UAAiC,CACrC;EACE,OAAO;EACP,MAAM;EACN,iBAAiB;EACjB,OAAO,MAAM,MAAM;CACrB,CACF;CAEA,KAAK,MAAM,QAAQ,CAAC,UAAU,WAAW,GACvC,QAAQ,KAAK;EACX,OAAO,GAAG,KAAK;EACf;EACA,iBAAiB;EACjB,OAAO,GAAG,MAAM,KAAK,CAAC,KAAK;CAC7B,CAAC;CAGH,KAAK,MAAM,eAAe,cAAc;EACtC,IAAI,YAAY,YAAY,QAAQ,YAAY,QAAQ,eAAe,MAAM;EAC7E,KAAK,MAAM,QAAQ,CAAC,UAAU,WAAW,GACvC,QAAQ,KAAK;GACX,OAAO,GAAG,KAAK,GAA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