@cosmicdrift/kumiko-framework 0.411.0 → 0.412.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agents/api/framework-db.md +1 -1
- package/agents/api/framework-engine.md +48 -1
- package/agents/api/framework-errors.md +2 -0
- package/agents/api/types.md +8 -0
- package/agents/api.md +2 -2
- package/agents/examples/api-docs.md +702 -0
- package/agents/examples.md +1 -0
- package/dist/api/auth-middleware.d.ts +1 -0
- package/dist/api/index.d.ts +3 -0
- package/dist/api/index.js +3 -0
- package/dist/api/pat-auth-reject.d.ts +7 -0
- package/dist/api/pat-auth-reject.js +7 -0
- package/dist/api/server-middleware.js +2 -1
- package/dist/compliance/sub-processors.js +2 -2
- package/dist/config/index.d.ts +25 -0
- package/dist/config/index.js +28 -1
- package/dist/db/event-store-executor-read-paging.d.ts +1 -0
- package/dist/db/event-store-executor-read-paging.js +2 -1
- package/dist/db/read-gate-clause.js +26 -7
- package/dist/db/table-builder.d.ts +1 -2
- package/dist/engine/define-feature.js +3 -0
- package/dist/engine/entity-list-runtime-options.js +12 -0
- package/dist/engine/factories.d.ts +2 -0
- package/dist/engine/feature-builder-state.d.ts +2 -1
- package/dist/engine/feature-builder-state.js +1 -0
- package/dist/engine/index.d.ts +5 -2
- package/dist/engine/index.js +4 -1
- package/dist/engine/registry-facade.js +13 -0
- package/dist/engine/webhook-contracts.d.ts +12 -0
- package/dist/engine/webhook-contracts.js +172 -0
- package/dist/engine/webhook-events.d.ts +34 -0
- package/dist/engine/webhook-events.js +71 -0
- package/dist/errors/docs-url.js +2 -19
- package/dist/errors/error-codes.d.ts +20 -0
- package/dist/errors/error-codes.js +19 -0
- package/dist/errors/index.d.ts +2 -0
- package/dist/errors/index.js +1 -0
- package/dist/i18n/required-surface-keys.d.ts +4 -0
- package/dist/i18n/required-surface-keys.js +15 -0
- package/package.json +3 -3
- package/src/changes.json +30 -0
|
@@ -0,0 +1,702 @@
|
|
|
1
|
+
<!-- Generated by `bun run gen:agent-docs` from samples/recipes/api-docs. Do not edit. -->
|
|
2
|
+
|
|
3
|
+
# api-docs
|
|
4
|
+
|
|
5
|
+
API documentation for personal access tokens: recorded examples, kumiko api-docs and a committed golden.
|
|
6
|
+
|
|
7
|
+
## README
|
|
8
|
+
|
|
9
|
+
# API docs
|
|
10
|
+
|
|
11
|
+
API documentation for personal access tokens, generated from the app itself. A helpdesk
|
|
12
|
+
feature exposes its ticket handlers through token scopes; `kumiko api-docs` turns the
|
|
13
|
+
registry, the translations and recorded requests into Markdown pages, an OpenAPI file and
|
|
14
|
+
an `index.json` that a website or an agent can read.
|
|
15
|
+
|
|
16
|
+
## What it shows
|
|
17
|
+
|
|
18
|
+
- **Scopes decide the content.** Only handlers that a scope of the token feature reaches
|
|
19
|
+
appear. `helpdesk:write:ticket:purge` is reachable from a screen but in no scope, so it is
|
|
20
|
+
listed under `apiDocs.uiOnlyWrites` with a reason; without that entry the generator reports it.
|
|
21
|
+
- **Texts come from the feature.** Titles, descriptions and field labels per locale use the
|
|
22
|
+
keys `<handler qn>:title`, `:description` and `:field:<name>`; the German pages need the
|
|
23
|
+
German translations, the menu path to the token screen comes from the nav tree.
|
|
24
|
+
- **Examples are recordings.** The integration test sends real requests with a token through
|
|
25
|
+
`recordApiExample` from `@cosmicdrift/kumiko-testing/api-examples`. UUIDs, timestamps and
|
|
26
|
+
tokens are replaced by fixed values, so a recording only changes when the API changes.
|
|
27
|
+
- **The output is a golden.** `api-docs/` is committed and the golden test fails when the
|
|
28
|
+
generator would produce something else.
|
|
29
|
+
|
|
30
|
+
## Commands
|
|
31
|
+
|
|
32
|
+
Record the examples (writes `api-examples/`, needs Postgres from `docker compose up -d`):
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
KUMIKO_RECORD_API_EXAMPLES=1 bun test --config=bunfig.integration.toml samples/recipes/api-docs/src/__tests__/api-docs.integration.test.ts
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Regenerate the golden (empties and rewrites `api-docs/`):
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
KUMIKO_UPDATE_API_DOCS_GOLDEN=1 bun test samples/recipes/api-docs/src/__tests__/api-docs.golden.test.ts
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Both tests run without the flags as ordinary checks.
|
|
45
|
+
|
|
46
|
+
In an app, `kumiko api-docs` writes the pages to `apiDocs.outDir` (default `api-docs`) and
|
|
47
|
+
`kumiko api-docs --check` compares them with the disk, so a CI step can keep them current.
|
|
48
|
+
The golden test pins the framework and app version in `index.json` and `openapi.json`, so
|
|
49
|
+
those two files differ from a real run of the command.
|
|
50
|
+
|
|
51
|
+
## Files
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
kumiko.config.ts features and the apiDocs block
|
|
55
|
+
src/feature.ts helpdesk feature and the token feature with its scopes
|
|
56
|
+
src/__tests__/api-docs.integration.test.ts mints a token, records the examples, checks scope limits
|
|
57
|
+
src/__tests__/api-docs.golden.test.ts generator output equals api-docs/
|
|
58
|
+
api-examples/ recorded requests and responses
|
|
59
|
+
api-docs/ the golden output
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Source files
|
|
63
|
+
|
|
64
|
+
### kumiko.config.ts
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { createAuthFoundationFeature } from "@cosmicdrift/kumiko-bundled-features/auth-foundation";
|
|
68
|
+
import { defineAppConfig } from "@cosmicdrift/kumiko-framework/config";
|
|
69
|
+
import { localeDe } from "@cosmicdrift/kumiko-locale-de";
|
|
70
|
+
import { helpdeskFeature, patFeature } from "./src/feature";
|
|
71
|
+
|
|
72
|
+
const PURGE_REASON =
|
|
73
|
+
"Purging is an admin chore that stays in the app and is never offered to API clients.";
|
|
74
|
+
|
|
75
|
+
export default defineAppConfig({
|
|
76
|
+
features: [createAuthFoundationFeature(), helpdeskFeature, patFeature(), localeDe()],
|
|
77
|
+
includeBundled: true,
|
|
78
|
+
client: { entries: ["src/client.tsx"] },
|
|
79
|
+
ports: { dev: 4520, e2e: 4521, infra: { postgres: 15520 } },
|
|
80
|
+
apiDocs: {
|
|
81
|
+
appName: "Helpdesk",
|
|
82
|
+
baseUrl: "https://helpdesk.example.com",
|
|
83
|
+
locales: ["en", "de"],
|
|
84
|
+
planNote: {
|
|
85
|
+
en: "API tokens are included in every Helpdesk plan.",
|
|
86
|
+
de: "API-Tokens sind in jedem Helpdesk-Tarif enthalten.",
|
|
87
|
+
},
|
|
88
|
+
webhookDelivery: {
|
|
89
|
+
en: "Deliveries are signed so that you can verify the sender. A delivery that fails is retried a few times before it is dropped. Answer within a few seconds and treat repeated deliveries of the same event as one.",
|
|
90
|
+
de: "Zustellungen sind signiert, damit du den Absender prüfen kannst. Eine fehlgeschlagene Zustellung wird einige Male wiederholt, bevor sie verworfen wird. Antworte innerhalb weniger Sekunden und behandle wiederholte Zustellungen desselben Ereignisses als eine.",
|
|
91
|
+
},
|
|
92
|
+
uiOnlyWrites: [
|
|
93
|
+
{
|
|
94
|
+
pattern: "helpdesk:write:ticket:purge",
|
|
95
|
+
reason: PURGE_REASON,
|
|
96
|
+
},
|
|
97
|
+
],
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### src/__tests__/api-docs.golden.test.ts
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
// The committed api-docs/ is the golden of what `kumiko api-docs` generates for this app.
|
|
106
|
+
// Regenerate it with KUMIKO_UPDATE_API_DOCS_GOLDEN=1 after changing the feature, the
|
|
107
|
+
// translations, the config or the recordings in api-examples/.
|
|
108
|
+
|
|
109
|
+
import { describe, expect, test } from "bun:test";
|
|
110
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
111
|
+
import { dirname, join, relative } from "node:path";
|
|
112
|
+
import {
|
|
113
|
+
ApiExampleFileSchema,
|
|
114
|
+
diffApiDocsOutput,
|
|
115
|
+
generateApiDocs,
|
|
116
|
+
type NamedApiExample,
|
|
117
|
+
type NamedWebhookExample,
|
|
118
|
+
WebhookExampleFileSchema,
|
|
119
|
+
} from "@cosmicdrift/kumiko-bundled-features/agent-tools";
|
|
120
|
+
import { allAppFeatures } from "@cosmicdrift/kumiko-framework/config";
|
|
121
|
+
import { createRegistry } from "@cosmicdrift/kumiko-framework/engine";
|
|
122
|
+
import { composeFeatures } from "@cosmicdrift/kumiko-server-runtime";
|
|
123
|
+
import { z } from "zod";
|
|
124
|
+
import config from "../../kumiko.config";
|
|
125
|
+
|
|
126
|
+
const ROOT = join(import.meta.dir, "../..");
|
|
127
|
+
const GOLDEN_DIR = join(ROOT, "api-docs");
|
|
128
|
+
const EXAMPLES_DIR = join(ROOT, "api-examples");
|
|
129
|
+
const UPDATE_FLAG = "KUMIKO_UPDATE_API_DOCS_GOLDEN";
|
|
130
|
+
|
|
131
|
+
const PackageNameSchema = z.object({ name: z.string() });
|
|
132
|
+
|
|
133
|
+
function readExamples(): NamedApiExample[] {
|
|
134
|
+
return readdirSync(EXAMPLES_DIR)
|
|
135
|
+
.filter((fileName) => fileName.endsWith(".json"))
|
|
136
|
+
.sort()
|
|
137
|
+
.map((fileName) => ({
|
|
138
|
+
fileName,
|
|
139
|
+
file: ApiExampleFileSchema.parse(
|
|
140
|
+
JSON.parse(readFileSync(join(EXAMPLES_DIR, fileName), "utf8")),
|
|
141
|
+
),
|
|
142
|
+
}));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function readWebhookExamples(): NamedWebhookExample[] {
|
|
146
|
+
const dir = join(EXAMPLES_DIR, "webhooks");
|
|
147
|
+
if (!existsSync(dir)) return [];
|
|
148
|
+
return readdirSync(dir)
|
|
149
|
+
.filter((fileName) => fileName.endsWith(".json"))
|
|
150
|
+
.sort()
|
|
151
|
+
.map((fileName) => ({
|
|
152
|
+
fileName,
|
|
153
|
+
file: WebhookExampleFileSchema.parse(JSON.parse(readFileSync(join(dir, fileName), "utf8"))),
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function readGolden(dir: string): Map<string, string> {
|
|
158
|
+
if (!existsSync(dir)) return new Map();
|
|
159
|
+
const files = readdirSync(dir, { recursive: true, withFileTypes: true }).filter((entry) =>
|
|
160
|
+
entry.isFile(),
|
|
161
|
+
);
|
|
162
|
+
return new Map(
|
|
163
|
+
files.map((entry) => {
|
|
164
|
+
const path = join(entry.parentPath, entry.name);
|
|
165
|
+
return [relative(dir, path).split("\\").join("/"), readFileSync(path, "utf8")];
|
|
166
|
+
}),
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
describe("api-docs golden", () => {
|
|
171
|
+
const appName = PackageNameSchema.parse(
|
|
172
|
+
JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")),
|
|
173
|
+
).name;
|
|
174
|
+
const generated = generateApiDocs({
|
|
175
|
+
registry: createRegistry(
|
|
176
|
+
composeFeatures(allAppFeatures(config), { includeBundled: config.includeBundled === true }),
|
|
177
|
+
),
|
|
178
|
+
config: {
|
|
179
|
+
...config.apiDocs,
|
|
180
|
+
locales: config.apiDocs?.locales ?? ["en"],
|
|
181
|
+
baseUrl: config.apiDocs?.baseUrl ?? "",
|
|
182
|
+
appName: config.apiDocs?.appName ?? appName,
|
|
183
|
+
},
|
|
184
|
+
// Fixed so that a release does not turn the golden red.
|
|
185
|
+
source: { framework: "0.0.0-recipe", app: { name: appName, version: "0.0.0" } },
|
|
186
|
+
examples: readExamples(),
|
|
187
|
+
webhookExamples: readWebhookExamples(),
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
if (process.env[UPDATE_FLAG] === "1") {
|
|
191
|
+
rmSync(GOLDEN_DIR, { recursive: true, force: true });
|
|
192
|
+
for (const [path, content] of generated.files) {
|
|
193
|
+
mkdirSync(dirname(join(GOLDEN_DIR, path)), { recursive: true });
|
|
194
|
+
writeFileSync(join(GOLDEN_DIR, path), content);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
test("every documented handler is complete", () => {
|
|
199
|
+
expect(generated.problems).toEqual([]);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test("the committed output equals what the generator produces", () => {
|
|
203
|
+
expect(diffApiDocsOutput(generated.files, readGolden(GOLDEN_DIR))).toEqual({
|
|
204
|
+
missing: [],
|
|
205
|
+
changed: [],
|
|
206
|
+
extra: [],
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
});
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
### src/__tests__/api-docs.integration.test.ts
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
// Records the request/response pairs that api-docs/ shows. A normal run only asserts the
|
|
216
|
+
// behaviour; with KUMIKO_RECORD_API_EXAMPLES=1 the pairs are also written to api-examples/.
|
|
217
|
+
|
|
218
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
219
|
+
import { join } from "node:path";
|
|
220
|
+
import {
|
|
221
|
+
AuthHandlers,
|
|
222
|
+
createAuthEmailPasswordFeature,
|
|
223
|
+
hashPassword,
|
|
224
|
+
} from "@cosmicdrift/kumiko-bundled-features/auth-email-password";
|
|
225
|
+
import {
|
|
226
|
+
createAuthFoundationFeature,
|
|
227
|
+
resolveTokenVerifier,
|
|
228
|
+
} from "@cosmicdrift/kumiko-bundled-features/auth-foundation";
|
|
229
|
+
import {
|
|
230
|
+
configValuesTable,
|
|
231
|
+
createConfigFeature,
|
|
232
|
+
} from "@cosmicdrift/kumiko-bundled-features/config";
|
|
233
|
+
import {
|
|
234
|
+
apiTokenEntity,
|
|
235
|
+
PatHandlers,
|
|
236
|
+
} from "@cosmicdrift/kumiko-bundled-features/personal-access-tokens";
|
|
237
|
+
import {
|
|
238
|
+
createTenantFeature,
|
|
239
|
+
tenantEntity,
|
|
240
|
+
tenantMembershipsTable,
|
|
241
|
+
} from "@cosmicdrift/kumiko-bundled-features/tenant";
|
|
242
|
+
import { seedTenantMembership } from "@cosmicdrift/kumiko-bundled-features/tenant/seeding";
|
|
243
|
+
import {
|
|
244
|
+
createUserFeature,
|
|
245
|
+
UserHandlers,
|
|
246
|
+
userEntity,
|
|
247
|
+
} from "@cosmicdrift/kumiko-bundled-features/user";
|
|
248
|
+
import { entityEventName, selectMany } from "@cosmicdrift/kumiko-framework/db";
|
|
249
|
+
import {
|
|
250
|
+
formatWebhookPayloadIssues,
|
|
251
|
+
type SessionUser,
|
|
252
|
+
type TenantId,
|
|
253
|
+
toEntityWebhookPayload,
|
|
254
|
+
} from "@cosmicdrift/kumiko-framework/engine";
|
|
255
|
+
import { eventsTable } from "@cosmicdrift/kumiko-framework/event-store";
|
|
256
|
+
import { TestUsers, testTenantId } from "@cosmicdrift/kumiko-framework/seeding";
|
|
257
|
+
import { recordApiExample, recordWebhookExample } from "@cosmicdrift/kumiko-testing/api-examples";
|
|
258
|
+
import {
|
|
259
|
+
setupTestStack,
|
|
260
|
+
type TestStack,
|
|
261
|
+
unsafeCreateEntityTable,
|
|
262
|
+
unsafePushTables,
|
|
263
|
+
} from "@cosmicdrift/kumiko-testing/stack";
|
|
264
|
+
import { z } from "zod";
|
|
265
|
+
import { helpdeskFeature, patFeature } from "../feature";
|
|
266
|
+
|
|
267
|
+
const TENANT: TenantId = testTenantId(1);
|
|
268
|
+
const EXAMPLES_DIR = join(import.meta.dir, "../../api-examples");
|
|
269
|
+
|
|
270
|
+
let stack: TestStack;
|
|
271
|
+
let actor: SessionUser;
|
|
272
|
+
|
|
273
|
+
async function mintToken(scopes: readonly string[]): Promise<string> {
|
|
274
|
+
const minted = await stack.http.writeOk<{ token: string }>(
|
|
275
|
+
PatHandlers.create,
|
|
276
|
+
{ name: "Integration", scopes, currentPassword: "super-long-password" },
|
|
277
|
+
actor,
|
|
278
|
+
);
|
|
279
|
+
return minted.token;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
beforeAll(async () => {
|
|
283
|
+
stack = await setupTestStack({
|
|
284
|
+
features: [
|
|
285
|
+
createConfigFeature(),
|
|
286
|
+
createUserFeature(),
|
|
287
|
+
createTenantFeature(),
|
|
288
|
+
createAuthEmailPasswordFeature(),
|
|
289
|
+
createAuthFoundationFeature(),
|
|
290
|
+
helpdeskFeature,
|
|
291
|
+
patFeature(),
|
|
292
|
+
],
|
|
293
|
+
authConfig: {
|
|
294
|
+
membershipQuery: "tenant:query:memberships",
|
|
295
|
+
loginHandler: AuthHandlers.login,
|
|
296
|
+
tokenVerifier: (raw: string) =>
|
|
297
|
+
resolveTokenVerifier({ db: stack.db, registry: stack.registry }, raw),
|
|
298
|
+
},
|
|
299
|
+
});
|
|
300
|
+
await unsafeCreateEntityTable(stack.db, userEntity);
|
|
301
|
+
await unsafeCreateEntityTable(stack.db, tenantEntity);
|
|
302
|
+
await unsafeCreateEntityTable(stack.db, apiTokenEntity);
|
|
303
|
+
await unsafePushTables(stack.db, { configValuesTable, tenantMembershipsTable });
|
|
304
|
+
|
|
305
|
+
const created = await stack.http.writeOk<{ id: string }>(
|
|
306
|
+
UserHandlers.create,
|
|
307
|
+
{
|
|
308
|
+
email: "agent@example.com",
|
|
309
|
+
passwordHash: await hashPassword("super-long-password"),
|
|
310
|
+
displayName: "Agent",
|
|
311
|
+
},
|
|
312
|
+
TestUsers.systemAdmin,
|
|
313
|
+
);
|
|
314
|
+
await seedTenantMembership(stack.db, { userId: created.id, tenantId: TENANT, roles: ["User"] });
|
|
315
|
+
actor = { id: created.id, tenantId: TENANT, roles: ["User"] };
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
afterAll(async () => {
|
|
319
|
+
await stack.cleanup();
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
const TicketRowSchema = z.object({
|
|
323
|
+
id: z.string(),
|
|
324
|
+
title: z.string(),
|
|
325
|
+
status: z.string(),
|
|
326
|
+
priority: z.string(),
|
|
327
|
+
});
|
|
328
|
+
const CreatedSchema = z.object({ data: z.object({ id: z.string() }) });
|
|
329
|
+
const ListedSchema = z.object({ data: z.object({ rows: z.array(TicketRowSchema) }) });
|
|
330
|
+
const DetailSchema = z.object({ data: TicketRowSchema });
|
|
331
|
+
|
|
332
|
+
async function denied(token: string, type: string, payload: unknown) {
|
|
333
|
+
const response = await stack.http.raw(
|
|
334
|
+
"POST",
|
|
335
|
+
"/api/write",
|
|
336
|
+
{ type, payload },
|
|
337
|
+
{ Authorization: `Bearer ${token}` },
|
|
338
|
+
);
|
|
339
|
+
return { status: response.status, body: await response.json() };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
describe("helpdesk API with a personal access token", () => {
|
|
343
|
+
test("create, list, detail, update and close a ticket", async () => {
|
|
344
|
+
const token = await mintToken(["tickets:write"]);
|
|
345
|
+
const record = (
|
|
346
|
+
name: string,
|
|
347
|
+
endpoint: "/api/query" | "/api/write",
|
|
348
|
+
type: string,
|
|
349
|
+
payload: unknown,
|
|
350
|
+
) =>
|
|
351
|
+
recordApiExample(stack.http, {
|
|
352
|
+
name,
|
|
353
|
+
dir: EXAMPLES_DIR,
|
|
354
|
+
endpoint,
|
|
355
|
+
body: { type, payload },
|
|
356
|
+
token,
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
const created = await record("ticket-create", "/api/write", "helpdesk:write:ticket:create", {
|
|
360
|
+
title: "Printer is on fire",
|
|
361
|
+
priority: "high",
|
|
362
|
+
});
|
|
363
|
+
expect(created.status).toBe(200);
|
|
364
|
+
const id = CreatedSchema.parse(created.body).data.id;
|
|
365
|
+
|
|
366
|
+
const listed = await record("ticket-list", "/api/query", "helpdesk:query:ticket:list", {});
|
|
367
|
+
expect(ListedSchema.parse(listed.body).data.rows.map((row) => row.id)).toContain(id);
|
|
368
|
+
|
|
369
|
+
const detail = await record("ticket-detail", "/api/query", "helpdesk:query:ticket:detail", {
|
|
370
|
+
id,
|
|
371
|
+
});
|
|
372
|
+
expect(DetailSchema.parse(detail.body).data).toMatchObject({
|
|
373
|
+
title: "Printer is on fire",
|
|
374
|
+
status: "open",
|
|
375
|
+
priority: "high",
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
const updated = await record("ticket-update", "/api/write", "helpdesk:write:ticket:update", {
|
|
379
|
+
id,
|
|
380
|
+
version: 1,
|
|
381
|
+
changes: { priority: "normal" },
|
|
382
|
+
});
|
|
383
|
+
expect(updated.status).toBe(200);
|
|
384
|
+
|
|
385
|
+
const closed = await record("ticket-close", "/api/write", "helpdesk:write:ticket:close", {
|
|
386
|
+
id,
|
|
387
|
+
resolution: "Replaced the cartridge",
|
|
388
|
+
});
|
|
389
|
+
expect(closed.status).toBe(200);
|
|
390
|
+
const after = await stack.http.queryOk("helpdesk:query:ticket:detail", { id }, actor);
|
|
391
|
+
expect(TicketRowSchema.parse(after)).toMatchObject({ status: "closed", priority: "normal" });
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
test("webhook payloads built from the appended events satisfy their contracts and are recorded", async () => {
|
|
395
|
+
const created = await stack.http.writeOk<{ id: string }>(
|
|
396
|
+
"helpdesk:write:ticket:create",
|
|
397
|
+
{ title: "Scanner jams", priority: "low" },
|
|
398
|
+
actor,
|
|
399
|
+
);
|
|
400
|
+
await stack.http.writeOk(
|
|
401
|
+
"helpdesk:write:ticket:update",
|
|
402
|
+
{ id: created.id, version: 1, changes: { priority: "high" } },
|
|
403
|
+
actor,
|
|
404
|
+
);
|
|
405
|
+
await stack.http.writeOk(
|
|
406
|
+
"helpdesk:write:ticket:close",
|
|
407
|
+
{ id: created.id, resolution: "Replaced the roller" },
|
|
408
|
+
actor,
|
|
409
|
+
);
|
|
410
|
+
const stored = await selectMany<{ type: string; payload: Record<string, unknown> }>(
|
|
411
|
+
stack.db,
|
|
412
|
+
eventsTable,
|
|
413
|
+
{ aggregateId: created.id },
|
|
414
|
+
);
|
|
415
|
+
const webhookPayloadOf = (verb: "created" | "updated") => {
|
|
416
|
+
const qn = entityEventName("ticket", verb);
|
|
417
|
+
const contract = stack.registry.getWebhookEventContract(qn);
|
|
418
|
+
const event = stored.find((candidate) => candidate.type === qn);
|
|
419
|
+
if (contract === undefined || event === undefined) {
|
|
420
|
+
throw new Error(`${qn} is neither a contract nor an appended event`);
|
|
421
|
+
}
|
|
422
|
+
const mapped = toEntityWebhookPayload(contract, {
|
|
423
|
+
aggregateId: created.id,
|
|
424
|
+
payload: event.payload,
|
|
425
|
+
});
|
|
426
|
+
if (!mapped.ok) throw new Error(formatWebhookPayloadIssues(mapped.issues));
|
|
427
|
+
return { contract, payload: mapped.payload };
|
|
428
|
+
};
|
|
429
|
+
|
|
430
|
+
const createdWebhook = webhookPayloadOf("created");
|
|
431
|
+
expect(Object.keys(createdWebhook.payload).sort()).toEqual(
|
|
432
|
+
Object.keys(createdWebhook.contract.payload.shape).sort(),
|
|
433
|
+
);
|
|
434
|
+
const recordedCreated = await recordWebhookExample({
|
|
435
|
+
name: "ticket-created",
|
|
436
|
+
dir: EXAMPLES_DIR,
|
|
437
|
+
contract: createdWebhook.contract,
|
|
438
|
+
payload: createdWebhook.payload,
|
|
439
|
+
});
|
|
440
|
+
expect(recordedCreated).toMatchObject({
|
|
441
|
+
id: created.id,
|
|
442
|
+
title: "Scanner jams",
|
|
443
|
+
priority: "low",
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
const updatedWebhook = webhookPayloadOf("updated");
|
|
447
|
+
expect(Object.keys(updatedWebhook.payload).sort()).toEqual(["changes", "id", "previous"]);
|
|
448
|
+
expect(updatedWebhook.payload["changes"]).toEqual({ priority: "high" });
|
|
449
|
+
|
|
450
|
+
const closedContract = stack.registry.getWebhookEventContract("helpdesk:ticket-closed");
|
|
451
|
+
const closedEvent = stored.find((event) => event.type.endsWith("ticket-closed"));
|
|
452
|
+
if (closedContract === undefined || closedEvent === undefined) {
|
|
453
|
+
throw new Error("helpdesk:ticket-closed has no contract or no appended event");
|
|
454
|
+
}
|
|
455
|
+
const recordedClosed = await recordWebhookExample({
|
|
456
|
+
name: "ticket-closed",
|
|
457
|
+
dir: EXAMPLES_DIR,
|
|
458
|
+
contract: closedContract,
|
|
459
|
+
payload: { id: created.id, resolution: closedEvent.payload["resolution"] },
|
|
460
|
+
});
|
|
461
|
+
expect(recordedClosed).toEqual({ id: created.id, resolution: "Replaced the roller" });
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
test("a read-only token cannot create a ticket", async () => {
|
|
465
|
+
const result = await denied(await mintToken(["tickets:read"]), "helpdesk:write:ticket:create", {
|
|
466
|
+
title: "Nope",
|
|
467
|
+
});
|
|
468
|
+
expect(result.status).toBe(403);
|
|
469
|
+
expect(result.body).toMatchObject({ error: { code: "access_denied" } });
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
test("a write token cannot reach the UI-only purge", async () => {
|
|
473
|
+
const result = await denied(await mintToken(["tickets:write"]), "helpdesk:write:ticket:purge", {
|
|
474
|
+
olderThanDays: 30,
|
|
475
|
+
});
|
|
476
|
+
expect(result.status).toBe(403);
|
|
477
|
+
});
|
|
478
|
+
});
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
### src/feature.ts
|
|
482
|
+
|
|
483
|
+
```ts
|
|
484
|
+
// API docs sample: a helpdesk whose ticket handlers are reachable with a personal access token.
|
|
485
|
+
// Every handler a token scope reaches needs a description and, per locale, a title, description
|
|
486
|
+
// and field labels; `kumiko api-docs` turns them into the pages under api-docs/.
|
|
487
|
+
|
|
488
|
+
import { createPersonalAccessTokensFeature } from "@cosmicdrift/kumiko-bundled-features/personal-access-tokens";
|
|
489
|
+
import {
|
|
490
|
+
createEntity,
|
|
491
|
+
createEntityExecutor,
|
|
492
|
+
createSelectField,
|
|
493
|
+
createTextField,
|
|
494
|
+
defineFeature,
|
|
495
|
+
emitEvent,
|
|
496
|
+
setFields,
|
|
497
|
+
} from "@cosmicdrift/kumiko-framework/engine";
|
|
498
|
+
import { failNotFound, failUnprocessable } from "@cosmicdrift/kumiko-framework/errors";
|
|
499
|
+
import { z } from "zod";
|
|
500
|
+
|
|
501
|
+
export const ticketEntity = createEntity({
|
|
502
|
+
table: "read_api_docs_tickets",
|
|
503
|
+
webhookEvents: true,
|
|
504
|
+
description: "A support request with a title, a priority and an open or closed status.",
|
|
505
|
+
fields: {
|
|
506
|
+
title: createTextField({ personal: false, reason: "is_business_data", required: true }),
|
|
507
|
+
status: createSelectField({ options: ["open", "closed"] as const, default: "open" }),
|
|
508
|
+
priority: createSelectField({ options: ["low", "normal", "high"] as const, default: "normal" }),
|
|
509
|
+
},
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
const ticketAccess = { roles: ["Admin", "User"] } as const;
|
|
513
|
+
|
|
514
|
+
export const helpdeskFeature = defineFeature("helpdesk", (r) => {
|
|
515
|
+
const { table: ticketTable, executor: ticketExecutor } = createEntityExecutor(
|
|
516
|
+
"ticket",
|
|
517
|
+
ticketEntity,
|
|
518
|
+
);
|
|
519
|
+
|
|
520
|
+
r.crud("ticket", ticketEntity, {
|
|
521
|
+
write: { access: ticketAccess },
|
|
522
|
+
read: { access: ticketAccess },
|
|
523
|
+
verbs: { delete: false },
|
|
524
|
+
descriptions: {
|
|
525
|
+
create: "Opens a new ticket.",
|
|
526
|
+
update: "Changes the title or the priority of a ticket.",
|
|
527
|
+
list: "Lists tickets, newest first.",
|
|
528
|
+
detail: "Returns one ticket.",
|
|
529
|
+
},
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
const ticketClosed = r.defineEvent("ticket-closed", z.object({ resolution: z.string().min(1) }), {
|
|
533
|
+
piiFields: "none",
|
|
534
|
+
});
|
|
535
|
+
|
|
536
|
+
r.defineWebhookEvent({
|
|
537
|
+
name: "ticket-closed",
|
|
538
|
+
wireName: "ticket.closed",
|
|
539
|
+
description: "A ticket was closed and its resolution recorded.",
|
|
540
|
+
payload: z.object({
|
|
541
|
+
id: z.uuid().describe("ID of the closed ticket"),
|
|
542
|
+
resolution: z.string().describe("How the ticket was resolved"),
|
|
543
|
+
}),
|
|
544
|
+
version: 1,
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
r.writeHandler({
|
|
548
|
+
name: "ticket:close",
|
|
549
|
+
description: "Closes a ticket and records how it was resolved.",
|
|
550
|
+
schema: z.object({ id: z.uuid(), resolution: z.string().min(1) }),
|
|
551
|
+
access: ticketAccess,
|
|
552
|
+
handler: async (event, ctx) => {
|
|
553
|
+
const ticket = await ticketExecutor.detail({ id: event.payload.id }, event.user, ctx.db);
|
|
554
|
+
if (!ticket) return failNotFound("ticket", event.payload.id);
|
|
555
|
+
if (ticket["status"] === "closed") return failUnprocessable("ticket_already_closed");
|
|
556
|
+
await emitEvent(ctx, ticketClosed, {
|
|
557
|
+
aggregateId: event.payload.id,
|
|
558
|
+
aggregateType: "ticket",
|
|
559
|
+
payload: { resolution: event.payload.resolution },
|
|
560
|
+
});
|
|
561
|
+
return { isSuccess: true as const, data: { id: event.payload.id } };
|
|
562
|
+
},
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
// Reachable from a screen but deliberately outside every token scope: see uiOnlyWrites in kumiko.config.ts.
|
|
566
|
+
r.writeHandler({
|
|
567
|
+
name: "ticket:purge",
|
|
568
|
+
description: "Removes tickets that were closed long ago.",
|
|
569
|
+
schema: z.object({ olderThanDays: z.number().int().min(30) }),
|
|
570
|
+
access: { roles: ["Admin"] },
|
|
571
|
+
handler: async () => ({ isSuccess: true as const, data: { purged: 0 } }),
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
const markTicketClosed = setFields(ticketTable, { status: "closed" });
|
|
575
|
+
r.projection({
|
|
576
|
+
name: "ticket-status",
|
|
577
|
+
source: "ticket",
|
|
578
|
+
table: ticketTable,
|
|
579
|
+
apply: { [ticketClosed.name]: (event, tx, ctx) => markTicketClosed(event, tx, ctx) },
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
r.screen({
|
|
583
|
+
id: "ticket-list",
|
|
584
|
+
type: "entityList",
|
|
585
|
+
entity: "ticket",
|
|
586
|
+
columns: ["title", "status", "priority"],
|
|
587
|
+
});
|
|
588
|
+
r.screen({
|
|
589
|
+
id: "ticket-edit",
|
|
590
|
+
type: "entityEdit",
|
|
591
|
+
entity: "ticket",
|
|
592
|
+
layout: { sections: [{ title: "helpdesk:section.ticket", fields: ["title", "priority"] }] },
|
|
593
|
+
});
|
|
594
|
+
r.screen({
|
|
595
|
+
id: "close-ticket",
|
|
596
|
+
type: "actionForm",
|
|
597
|
+
handler: "helpdesk:write:ticket:close",
|
|
598
|
+
fields: { resolution: createTextField({ personal: false, reason: "is_business_data" }) },
|
|
599
|
+
layout: { sections: [{ title: "helpdesk:section.close", fields: ["resolution"] }] },
|
|
600
|
+
});
|
|
601
|
+
r.screen({
|
|
602
|
+
id: "purge-tickets",
|
|
603
|
+
type: "actionForm",
|
|
604
|
+
handler: "helpdesk:write:ticket:purge",
|
|
605
|
+
fields: {},
|
|
606
|
+
layout: { sections: [] },
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
r.nav({ id: "tickets", label: "helpdesk:nav:tickets", screen: "helpdesk:screen:ticket-list" });
|
|
610
|
+
r.nav({ id: "settings", label: "helpdesk:nav:settings" });
|
|
611
|
+
r.nav({
|
|
612
|
+
id: "api-tokens",
|
|
613
|
+
label: "helpdesk:nav:api-tokens",
|
|
614
|
+
parent: "helpdesk:nav:settings",
|
|
615
|
+
screen: "personal-access-tokens:screen:api-tokens",
|
|
616
|
+
});
|
|
617
|
+
|
|
618
|
+
r.translations({
|
|
619
|
+
keys: {
|
|
620
|
+
"helpdesk:nav:tickets": { en: "Tickets", de: "Tickets" },
|
|
621
|
+
"helpdesk:nav:settings": { en: "Settings", de: "Einstellungen" },
|
|
622
|
+
"helpdesk:nav:api-tokens": { en: "API tokens", de: "API-Tokens" },
|
|
623
|
+
"helpdesk:section.ticket": { en: "Ticket", de: "Ticket" },
|
|
624
|
+
"helpdesk:section.close": { en: "Close ticket", de: "Ticket schließen" },
|
|
625
|
+
"helpdesk:entity:ticket:field:title": { en: "Title", de: "Titel" },
|
|
626
|
+
"helpdesk:entity:ticket:field:status": { en: "Status", de: "Status" },
|
|
627
|
+
"helpdesk:entity:ticket:field:priority": { en: "Priority", de: "Priorität" },
|
|
628
|
+
"helpdesk:write:ticket:create:title": { en: "Create ticket", de: "Ticket anlegen" },
|
|
629
|
+
"helpdesk:write:ticket:create:description": {
|
|
630
|
+
en: "Opens a new ticket.",
|
|
631
|
+
de: "Legt ein neues Ticket an.",
|
|
632
|
+
},
|
|
633
|
+
"helpdesk:write:ticket:update:title": { en: "Update ticket", de: "Ticket ändern" },
|
|
634
|
+
"helpdesk:write:ticket:update:description": {
|
|
635
|
+
en: "Changes the title or the priority of a ticket.",
|
|
636
|
+
de: "Ändert Titel oder Priorität eines Tickets.",
|
|
637
|
+
},
|
|
638
|
+
"helpdesk:query:ticket:list:title": { en: "List tickets", de: "Tickets auflisten" },
|
|
639
|
+
"helpdesk:query:ticket:list:description": {
|
|
640
|
+
en: "Lists tickets, newest first.",
|
|
641
|
+
de: "Listet Tickets, neueste zuerst.",
|
|
642
|
+
},
|
|
643
|
+
"helpdesk:query:ticket:detail:title": { en: "Show ticket", de: "Ticket anzeigen" },
|
|
644
|
+
"helpdesk:query:ticket:detail:description": {
|
|
645
|
+
en: "Returns one ticket.",
|
|
646
|
+
de: "Liefert ein Ticket.",
|
|
647
|
+
},
|
|
648
|
+
"helpdesk:write:ticket:close:title": { en: "Close ticket", de: "Ticket schließen" },
|
|
649
|
+
"helpdesk:write:ticket:close:description": {
|
|
650
|
+
en: "Closes a ticket and records how it was resolved.",
|
|
651
|
+
de: "Schließt ein Ticket und hält fest, wie es gelöst wurde.",
|
|
652
|
+
},
|
|
653
|
+
"helpdesk:write:ticket:close:field:id": { en: "Ticket", de: "Ticket" },
|
|
654
|
+
"helpdesk:write:ticket:close:field:resolution": { en: "Resolution", de: "Lösung" },
|
|
655
|
+
"helpdesk:write:ticket:purge:title": { en: "Purge tickets", de: "Tickets bereinigen" },
|
|
656
|
+
"helpdesk:write:ticket:purge:description": {
|
|
657
|
+
en: "Removes tickets that were closed long ago.",
|
|
658
|
+
de: "Entfernt Tickets, die lange geschlossen sind.",
|
|
659
|
+
},
|
|
660
|
+
"helpdesk:write:ticket:purge:field:olderThanDays": {
|
|
661
|
+
en: "Closed longer than (days)",
|
|
662
|
+
de: "Länger geschlossen als (Tage)",
|
|
663
|
+
},
|
|
664
|
+
"helpdesk:entity:ticket": { en: "ticket", de: "Ticket" },
|
|
665
|
+
"helpdesk:entity:ticket:field:id": { en: "Ticket ID", de: "Ticket-ID" },
|
|
666
|
+
"helpdesk:webhook:ticket-closed:description": {
|
|
667
|
+
en: "A ticket was closed and its resolution recorded.",
|
|
668
|
+
de: "Ein Ticket wurde geschlossen und seine Lösung festgehalten.",
|
|
669
|
+
},
|
|
670
|
+
"helpdesk:webhook:ticket-closed:field:id": {
|
|
671
|
+
en: "ID of the closed ticket",
|
|
672
|
+
de: "ID des geschlossenen Tickets",
|
|
673
|
+
},
|
|
674
|
+
"helpdesk:webhook:ticket-closed:field:resolution": {
|
|
675
|
+
en: "How the ticket was resolved",
|
|
676
|
+
de: "Wie das Ticket gelöst wurde",
|
|
677
|
+
},
|
|
678
|
+
"helpdesk:entity:__action-form__:field:resolution": { en: "Resolution", de: "Lösung" },
|
|
679
|
+
},
|
|
680
|
+
});
|
|
681
|
+
});
|
|
682
|
+
|
|
683
|
+
export const PAT_RATE_LIMIT = { maxRequests: 60, windowMs: 60_000 } as const;
|
|
684
|
+
|
|
685
|
+
export function patFeature() {
|
|
686
|
+
return createPersonalAccessTokensFeature({
|
|
687
|
+
scopes: {
|
|
688
|
+
tickets: {
|
|
689
|
+
label: "Tickets",
|
|
690
|
+
events: ["ticket.created", "helpdesk:ticket-closed"],
|
|
691
|
+
read: ["helpdesk:query:ticket:*"],
|
|
692
|
+
write: [
|
|
693
|
+
"helpdesk:write:ticket:create",
|
|
694
|
+
"helpdesk:write:ticket:update",
|
|
695
|
+
"helpdesk:write:ticket:close",
|
|
696
|
+
],
|
|
697
|
+
},
|
|
698
|
+
},
|
|
699
|
+
rateLimit: PAT_RATE_LIMIT,
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
```
|