@cosmicdrift/kumiko-samples 0.417.0 → 0.419.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 (114) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +6 -1
  3. package/packages/bundled-features/src/agent-tools/api-docs/schema-fields.ts +14 -0
  4. package/packages/bundled-features/src/agent-tools/changes.json +6 -0
  5. package/packages/bundled-features/src/auth-email-password/index.ts +1 -1
  6. package/packages/bundled-features/src/auth-email-password/signup-activation.ts +2 -5
  7. package/packages/bundled-features/src/auth-email-password/signup-token-store.ts +0 -6
  8. package/packages/bundled-features/src/cap-counter/changes.json +6 -0
  9. package/packages/bundled-features/src/cap-counter/stock-cap-guard.ts +46 -13
  10. package/packages/bundled-features/src/channel-whatsapp/changes.json +1 -1
  11. package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
  12. package/packages/bundled-features/src/document-ingest-foundation/feature.ts +13 -1
  13. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +23 -6
  14. package/packages/bundled-features/src/signature/README.md +4 -4
  15. package/packages/bundled-features/src/signature/changes.json +18 -0
  16. package/packages/bundled-features/src/signature/entity.ts +3 -1
  17. package/packages/bundled-features/src/signature/feature.ts +16 -3
  18. package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +33 -1
  19. package/packages/bundled-features/src/signature/i18n.ts +1 -0
  20. package/packages/bundled-features/src/signature/list-cursor-seal.ts +59 -0
  21. package/packages/bundled-features/src/signature/options.ts +2 -2
  22. package/packages/bundled-features/src/signature/payloads.ts +14 -2
  23. package/packages/bundled-features/src/signature/png.ts +25 -4
  24. package/packages/bundled-features/src/signature/subject-queries.ts +47 -7
  25. package/packages/bundled-features/src/signature/sweep.ts +32 -8
  26. package/packages/bundled-features/src/signature/web/constants.ts +12 -0
  27. package/packages/bundled-features/src/subscription-paddle/changes.json +1 -1
  28. package/packages/bundled-features/src/subscription-stripe/changes.json +6 -0
  29. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +2 -0
  30. package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +21 -16
  31. package/packages/bundled-features/src/template-resolver/changes.json +38 -0
  32. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +3 -8
  33. package/packages/bundled-features/src/template-resolver/compile-document-styles.ts +102 -0
  34. package/packages/bundled-features/src/template-resolver/document-frames.ts +25 -0
  35. package/packages/bundled-features/src/template-resolver/document-op-blocks.ts +568 -0
  36. package/packages/bundled-features/src/template-resolver/document-ops.ts +136 -126
  37. package/packages/bundled-features/src/template-resolver/document-print-only.ts +41 -0
  38. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +41 -19
  39. package/packages/bundled-features/src/template-resolver/feature.ts +15 -0
  40. package/packages/bundled-features/src/template-resolver/handlers/apply-layout.write.ts +137 -0
  41. package/packages/bundled-features/src/template-resolver/handlers/create-layout.write.ts +87 -0
  42. package/packages/bundled-features/src/template-resolver/handlers/document-base.ts +2 -2
  43. package/packages/bundled-features/src/template-resolver/handlers/document-blocks.query.ts +13 -8
  44. package/packages/bundled-features/src/template-resolver/handlers/document-region.ts +47 -0
  45. package/packages/bundled-features/src/template-resolver/handlers/failure-reason.ts +13 -0
  46. package/packages/bundled-features/src/template-resolver/handlers/import-bundle-system.write.ts +3 -0
  47. package/packages/bundled-features/src/template-resolver/handlers/layout-source.query.ts +17 -5
  48. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +16 -4
  49. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +19 -6
  50. package/packages/bundled-features/src/template-resolver/handlers/publish-templates.write.ts +69 -0
  51. package/packages/bundled-features/src/template-resolver/handlers/set.write.ts +7 -0
  52. package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +15 -3
  53. package/packages/bundled-features/src/template-resolver/handlers/tenant-settings.ts +122 -0
  54. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +25 -10
  55. package/packages/bundled-features/src/template-resolver/handlers/upsert-system.write.ts +7 -3
  56. package/packages/bundled-features/src/template-resolver/handlers/usage.query.ts +131 -18
  57. package/packages/bundled-features/src/template-resolver/handlers/validate.query.ts +10 -0
  58. package/packages/bundled-features/src/template-resolver/i18n.ts +3 -0
  59. package/packages/bundled-features/src/template-resolver/index.ts +29 -0
  60. package/packages/bundled-features/src/template-resolver/layout-regions.ts +54 -16
  61. package/packages/bundled-features/src/template-resolver/print-document.ts +3 -1
  62. package/packages/bundled-features/src/template-resolver/seeding.ts +4 -0
  63. package/packages/bundled-features/src/template-resolver/template-delivery-policy.ts +11 -1
  64. package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +37 -1
  65. package/packages/bundled-features/src/template-resolver/template-meta.ts +25 -6
  66. package/packages/bundled-features/src/template-resolver/template-preview.ts +6 -7
  67. package/packages/bundled-features/src/template-resolver/template-validation.ts +10 -3
  68. package/packages/bundled-features/src/template-resolver/web/constants.ts +29 -0
  69. package/packages/bundled-features/src/template-resolver/web/document-blocks.ts +5 -0
  70. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +34 -2
  71. package/packages/bundled-features/src/template-resolver/web/document-editor-fonts.ts +13 -0
  72. package/packages/bundled-features/src/template-resolver/web/document-fonts.ts +21 -0
  73. package/packages/bundled-features/src/template-resolver/web/document-frame-control.ts +428 -0
  74. package/packages/bundled-features/src/template-resolver/web/document-frame-node-view.tsx +207 -0
  75. package/packages/bundled-features/src/template-resolver/web/document-print-decorations.ts +196 -0
  76. package/packages/bundled-features/src/template-resolver/web/document-print-defaults.ts +59 -0
  77. package/packages/bundled-features/src/template-resolver/web/document-print-style.ts +246 -0
  78. package/packages/bundled-features/src/template-resolver/web/document-repeat-strip.ts +104 -0
  79. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +29 -9
  80. package/packages/bundled-features/src/template-resolver/web/document-style-css.ts +107 -0
  81. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +24 -2
  82. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +66 -7
  83. package/packages/bundled-features/src/template-resolver/web/document-tiptap-context.ts +13 -1
  84. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +24 -4
  85. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +149 -4
  86. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +290 -10
  87. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +90 -8
  88. package/packages/bundled-features/src/template-resolver/web/document-toolbar-blocks.ts +20 -0
  89. package/packages/bundled-features/src/template-resolver/web/fontsource-css.d.ts +2 -0
  90. package/packages/bundled-features/src/template-resolver/web/i18n.ts +28 -0
  91. package/packages/bundled-features/src/template-resolver/web/index.ts +34 -0
  92. package/packages/bundled-features/src/template-resolver/web/pdf-constants.ts +6 -0
  93. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +7 -0
  94. package/packages/bundled-features/src/template-resolver/web/use-document-tiptap-model.ts +74 -5
  95. package/packages/bundled-features/src/tenant/company-config.ts +48 -0
  96. package/packages/bundled-features/src/tenant/feature.ts +11 -0
  97. package/packages/bundled-features/src/tenant/i18n.ts +14 -0
  98. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +7 -3
  99. package/packages/bundled-features/src/tenant-lifecycle/changes.json +6 -0
  100. package/packages/bundled-features/src/tenant-lifecycle/run-tenant-destroy.ts +90 -42
  101. package/samples/apps/ui-walkthrough/src/app/auth-constants.ts +51 -0
  102. package/samples/apps/ui-walkthrough/src/app/seed-print-editor-tenants.ts +118 -0
  103. package/samples/apps/ui-walkthrough/src/app/seed-templates.ts +2 -0
  104. package/samples/apps/ui-walkthrough/src/app/server.ts +9 -1
  105. package/samples/apps/ui-walkthrough/src/app/template-seed-data.ts +27 -1
  106. package/samples/apps/ui-walkthrough/src/run-config.ts +1 -0
  107. package/samples/apps/use-all-bundled/feature-manifest.json +238 -1
  108. package/samples/recipes/crypto-shredding-hr/README.md +1 -1
  109. package/samples/recipes/crypto-shredding-hr/src/feature.ts +1 -1
  110. package/samples/recipes/list-table-options/README.md +9 -3
  111. package/samples/recipes/list-table-options/src/feature.ts +123 -3
  112. package/samples/recipes/pdf-letterhead/README.md +23 -0
  113. package/samples/recipes/pdf-letterhead/package.json +12 -0
  114. package/samples/recipes/pdf-letterhead/src/letterhead.ts +92 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-samples",
3
- "version": "0.417.0",
3
+ "version": "0.419.0",
4
4
  "description": "Source trees of the Kumiko sample recipes, sample apps and bundled features in repo layout, for tooling such as few-shot corpus builds.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-bundled-features",
3
- "version": "0.417.0",
3
+ "version": "0.419.0",
4
4
  "description": "Built-in features — tenant, user, auth, delivery. The stuff you'd rewrite anyway, already typed.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -183,6 +183,11 @@
183
183
  "@cosmicdrift/kumiko-framework": "workspace:*",
184
184
  "@cosmicdrift/kumiko-renderer": "workspace:*",
185
185
  "@cosmicdrift/kumiko-types": "workspace:*",
186
+ "@fontsource/arimo": "^5.3.0",
187
+ "@fontsource/caladea": "^5.3.0",
188
+ "@fontsource/carlito": "^5.3.0",
189
+ "@fontsource/cousine": "^5.3.0",
190
+ "@fontsource/tinos": "^5.3.0",
186
191
  "@mollie/api-client": "^4.6.0",
187
192
  "@node-rs/argon2": "^2.2.2",
188
193
  "@tiptap/core": "^3.32.2",
@@ -54,6 +54,19 @@ function alternatives(node: SchemaNode): readonly SchemaNode[] {
54
54
  return [...nodeList(node["anyOf"]), ...nodeList(node["oneOf"])];
55
55
  }
56
56
 
57
+ function typeArrayLabel(
58
+ node: SchemaNode,
59
+ type: readonly unknown[],
60
+ root: SchemaNode,
61
+ depth: number,
62
+ ): string {
63
+ const names = type.filter((name): name is string => typeof name === "string");
64
+ const labels = names
65
+ .filter((name) => name !== "null")
66
+ .map((name) => typeLabel({ ...node, type: name }, root, depth + 1));
67
+ return [...labels, ...(names.includes("null") ? ["null"] : [])].join(" | ") || "any";
68
+ }
69
+
57
70
  export function typeLabel(rawNode: SchemaNode, root: SchemaNode = rawNode, depth = 0): string {
58
71
  const node = resolveRef(rawNode, root);
59
72
  if (depth > MAX_SCHEMA_DEPTH) return "object";
@@ -67,6 +80,7 @@ export function typeLabel(rawNode: SchemaNode, root: SchemaNode = rawNode, depth
67
80
  return node["enum"].map((value) => JSON.stringify(value)).join(" | ");
68
81
  if ("const" in node) return JSON.stringify(node["const"]);
69
82
  const type = node["type"];
83
+ if (Array.isArray(type)) return typeArrayLabel(node, type, root, depth);
70
84
  if (type === "array") {
71
85
  const items = asNode(node["items"]);
72
86
  return `array of ${items === undefined ? "any" : typeLabel(items, root, depth + 1)}`;
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "API docs label nullable types",
6
+ "detail": "A JSON Schema type array such as `[\"string\", \"null\"]` (Zod nullable) was labelled `any` in the generated API docs. Each element is now labelled (string keeps its format) and joined with ` | `, with null last, e.g. `string | null`."
7
+ },
2
8
  {
3
9
  "version": "0.416.0",
4
10
  "type": "improvement",
@@ -1,6 +1,7 @@
1
1
  // Convention paths for the auth pages (reset/verify/signup/invite); apps build
2
2
  // their magic-link appUrls from these. All mail now goes through delivery.
3
3
 
4
+ export { normalizeEmail } from "../shared/index.ts";
4
5
  // Kept as a public re-export (not just internal call sites) — this feature's
5
6
  // barrel is where consumers of the published package have always found
6
7
  // hashPassword/verifyPassword; removing it is a breaking change that needs
@@ -49,7 +50,6 @@ export {
49
50
  } from "./signup-activation.ts";
50
51
  export {
51
52
  invalidateExistingSignupToken,
52
- normalizeEmail,
53
53
  SIGNUP_TOKEN_KEY_PREFIXES,
54
54
  storeSignupToken,
55
55
  } from "./signup-token-store.ts";
@@ -8,13 +8,10 @@ import { generateToken } from "@cosmicdrift/kumiko-framework/api";
8
8
  import type { NotifyFn } from "@cosmicdrift/kumiko-framework/engine";
9
9
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
10
10
  import type { Redis } from "ioredis";
11
+ import { normalizeEmail } from "../shared/index.ts";
11
12
  import { dispatchMagicLinkMail } from "./magic-link-mail.ts";
12
13
  import { AuthMailNotificationTypes } from "./mail-notifications.ts";
13
- import {
14
- invalidateExistingSignupToken,
15
- normalizeEmail,
16
- storeSignupToken,
17
- } from "./signup-token-store.ts";
14
+ import { invalidateExistingSignupToken, storeSignupToken } from "./signup-token-store.ts";
18
15
  import { AUTH_SIGNUP_DEFAULT_TTL_MINUTES } from "./web/constants.ts";
19
16
 
20
17
  export const SIGNUP_ACTIVATION_NOTIFICATION_TYPE = AuthMailNotificationTypes.signupActivation;
@@ -19,12 +19,6 @@ import {
19
19
  type SignupHandoverBinding,
20
20
  } from "../shared/index.ts";
21
21
 
22
- /** Email normalization — single source for every lookup layer (used
23
- * internally by the store AND by callers that need a consistent form
24
- * in the return body / mail send). Previously two places called
25
- * `.toLowerCase()` — one source means no drift. */
26
- export { normalizeEmail };
27
-
28
22
  export const SIGNUP_TOKEN_KEY_PREFIXES = {
29
23
  token: "signup:by-token:",
30
24
  email: "signup:by-email:",
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "withStockCap keeps the handler type",
6
+ "detail": "`withStockCap` is generic over the write handler definition and returns the type it received, so a `defineWriteHandler` result passes in without an `as unknown as WriteHandlerDef` cast. Callers passing a `WriteHandlerDef` compile unchanged."
7
+ },
2
8
  {
3
9
  "version": "0.414.0",
4
10
  "type": "fix",
@@ -9,12 +9,19 @@ import type {
9
9
  TenantDb,
10
10
  WhereObject,
11
11
  } from "@cosmicdrift/kumiko-framework/db";
12
- import type { ConfigAccessor, WriteHandlerDef } from "@cosmicdrift/kumiko-framework/engine";
12
+ import type {
13
+ ConfigAccessor,
14
+ KumikoEventTypeMap,
15
+ WriteHandlerDef,
16
+ WriteHandlerDefinition,
17
+ } from "@cosmicdrift/kumiko-framework/engine";
13
18
  import {
14
19
  UnprocessableError,
15
20
  type WriteFailure,
16
21
  writeFailure,
17
22
  } from "@cosmicdrift/kumiko-framework/errors";
23
+ import type { BeforeTransactionWhenNested } from "@cosmicdrift/kumiko-types/handlers";
24
+ import type { ZodType } from "zod";
18
25
  import { enforceStockCap } from "./enforce-cap.ts";
19
26
 
20
27
  // Runtime inputs a tier's cap limit may depend on, e.g. a SystemAdmin-edited
@@ -63,13 +70,34 @@ function hasToJson(value: object): boolean {
63
70
  return "toJSON" in value && typeof value.toJSON === "function";
64
71
  }
65
72
 
73
+ type WriteHandlerWithStockCap<TCaps> = {
74
+ (handler: WriteHandlerDef, spec: StockCapSpec<TCaps>): WriteHandlerDef;
75
+ <
76
+ TName extends string,
77
+ TSchema extends ZodType,
78
+ TData,
79
+ TPrepared,
80
+ TWhenNested extends BeforeTransactionWhenNested | undefined,
81
+ >(
82
+ handler: WriteHandlerDefinition<
83
+ TName,
84
+ TSchema,
85
+ TData,
86
+ KumikoEventTypeMap,
87
+ TPrepared,
88
+ TWhenNested
89
+ >,
90
+ spec: StockCapSpec<TCaps>,
91
+ ): WriteHandlerDefinition<TName, TSchema, TData, KumikoEventTypeMap, TPrepared, TWhenNested>;
92
+ };
93
+
66
94
  export type StockCapGuard<TCaps> = {
67
95
  readonly checkStockCap: (
68
96
  db: TenantDb,
69
97
  spec: StockCapSpec<TCaps>,
70
98
  context?: CapLimitContext,
71
99
  ) => Promise<WriteFailure | null>;
72
- readonly withStockCap: (handler: WriteHandlerDef, spec: StockCapSpec<TCaps>) => WriteHandlerDef;
100
+ readonly withStockCap: WriteHandlerWithStockCap<TCaps>;
73
101
  };
74
102
 
75
103
  export function createStockCapGuard<TCaps>(
@@ -97,19 +125,24 @@ export function createStockCapGuard<TCaps>(
97
125
  );
98
126
  }
99
127
 
100
- function withStockCap(handler: WriteHandlerDef, spec: StockCapSpec<TCaps>): WriteHandlerDef {
101
- return {
102
- ...handler,
103
- handler: async (event, ctx) => {
104
- // ctx.db is the handler's transaction, so the xact lock releases with its commit or
105
- // rollback. A handler wrapped in several caps must list them in the same order
106
- // everywhere; Postgres aborts one side of an inverse order with a deadlock error.
107
- await ctx.db.advisoryXactLock(STOCK_CAP_LOCK_NAMESPACE, countedSetKey(spec));
108
- const failure = await checkStockCap(ctx.db, spec, { config: ctx.config });
109
- return failure ?? handler.handler(event, ctx);
110
- },
128
+ function guardHandlerFn<TEvent, TCtx extends CapGuardContext, TResult>(
129
+ inner: (event: TEvent, ctx: TCtx) => Promise<TResult>,
130
+ spec: StockCapSpec<TCaps>,
131
+ ): (event: TEvent, ctx: TCtx) => Promise<TResult | WriteFailure> {
132
+ return async (event, ctx) => {
133
+ // ctx.db is the handler's transaction, so the xact lock releases with its commit or
134
+ // rollback. A handler wrapped in several caps must list them in the same order
135
+ // everywhere; Postgres aborts one side of an inverse order with a deadlock error.
136
+ await ctx.db.advisoryXactLock(STOCK_CAP_LOCK_NAMESPACE, countedSetKey(spec));
137
+ const failure = await checkStockCap(ctx.db, spec, { config: ctx.config });
138
+ return failure ?? inner(event, ctx);
111
139
  };
112
140
  }
113
141
 
142
+ const withStockCap: WriteHandlerWithStockCap<TCaps> = (
143
+ handler: WriteHandlerDef,
144
+ spec: StockCapSpec<TCaps>,
145
+ ) => ({ ...handler, handler: guardHandlerFn(handler.handler, spec) });
146
+
114
147
  return { checkStockCap, withStockCap };
115
148
  }
@@ -15,7 +15,7 @@
15
15
  "version": "0.415.0",
16
16
  "type": "fix",
17
17
  "title": "WhatsApp webhook skips oversized ids and survives absurd timestamps",
18
- "detail": "An entry with a wamid or phone number id above its limit is counted as skipped instead of failing the whole delivery with a 5xx. Overlong context ids, media ids and mime types are clipped, and a timestamp beyond the Temporal range falls back to the receive time."
18
+ "detail": "An entry with a wamid or phone number id above its limit is counted as skipped instead of failing the whole delivery with a 5xx. Overlong context ids and media ids are dropped to null and overlong mime types are clipped, and a timestamp beyond the Temporal range falls back to the receive time."
19
19
  },
20
20
  {
21
21
  "version": "0.415.0",
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "Ingest progress only moves forward",
6
+ "detail": "Parallel `reportIngestProgress` calls for one file can land in any order; the progress row now keeps the highest `pagesDone`, a report whose progress is already stored stops early, and after 10 version conflicts the call throws instead of returning silently."
7
+ },
2
8
  {
3
9
  "version": "0.415.0",
4
10
  "type": "fix",
@@ -4,7 +4,12 @@
4
4
  // hardcoded mime allowlist or size cap — providers register via
5
5
  // EXT_DOCUMENT_INGEST_PROVIDER (see providers.ts).
6
6
 
7
- import { applyEntityEvent, entityEventName, upsertByPk } from "@cosmicdrift/kumiko-framework/db";
7
+ import {
8
+ applyEntityEvent,
9
+ entityEventName,
10
+ selectMany,
11
+ upsertByPk,
12
+ } from "@cosmicdrift/kumiko-framework/db";
8
13
  import {
9
14
  access,
10
15
  createTenantConfig,
@@ -224,6 +229,13 @@ export function createDocumentIngestFoundationFeature() {
224
229
  apply: {
225
230
  [DOCUMENT_INGEST_PROGRESS_EVENT_QN]: async (event, tx) => {
226
231
  const progress = documentIngestProgressPayloadSchema.parse(event.payload);
232
+ const [existing] = await selectMany<{ pagesDone: number }>(
233
+ tx,
234
+ documentIngestProgressTable,
235
+ { id: event.aggregateId, tenantId: event.tenantId },
236
+ );
237
+ // skip: reports can land out of order, progress only moves forward
238
+ if (existing !== undefined && existing.pagesDone > progress.pagesDone) return;
227
239
  await upsertByPk(
228
240
  tx,
229
241
  documentIngestProgressTable,
@@ -1,4 +1,4 @@
1
- import { type DbConnection, transaction } from "@cosmicdrift/kumiko-framework/db";
1
+ import { type DbConnection, selectMany, transaction } from "@cosmicdrift/kumiko-framework/db";
2
2
  import type { Registry } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import {
4
4
  append,
@@ -12,6 +12,7 @@ import {
12
12
  DOCUMENT_INGEST_PROGRESS_EVENT_QN,
13
13
  documentIngestProgressPayloadSchema,
14
14
  } from "./events.ts";
15
+ import { documentIngestProgressTable } from "./tables.ts";
15
16
 
16
17
  export type ReportIngestProgressDeps = {
17
18
  readonly db: DbConnection;
@@ -26,9 +27,12 @@ export type ReportIngestProgressInput = {
26
27
  readonly pagesTotal: number;
27
28
  };
28
29
 
29
- // Parallel reports for one file race on the stream version; progress is idempotent and the newest
30
- // report wins, so a lost race re-reads the version and appends again.
31
- const MAX_VERSION_CONFLICT_ATTEMPTS = 3;
30
+ // Parallel reports for one file race on the stream version, so a lost race re-reads the version and
31
+ // appends again. The projection keeps the highest pagesDone, so landing order does not matter. A
32
+ // conflict means another report committed, so N parallel reports need at most N-1 retries; 10
33
+ // covers the parallelism one file sees. Every conflict is retried so each report lands its event;
34
+ // only when the attempts run out, a report whose progress is already stored is treated as done.
35
+ const MAX_VERSION_CONFLICT_ATTEMPTS = 10;
32
36
 
33
37
  // Low-level append() does not fire projections, so they run explicitly, in the same transaction as the append.
34
38
  export async function reportIngestProgress(
@@ -56,8 +60,21 @@ export async function reportIngestProgress(
56
60
  return;
57
61
  } catch (e) {
58
62
  if (!(e instanceof VersionConflictError)) throw e;
59
- // skip: a conflict after the last attempt means a newer report already landed
60
- if (attempt >= MAX_VERSION_CONFLICT_ATTEMPTS) return;
63
+ if (attempt < MAX_VERSION_CONFLICT_ATTEMPTS) continue;
64
+ if (await storedProgressCovers(deps, aggregateId, payload.pagesDone)) return;
65
+ throw e;
61
66
  }
62
67
  }
63
68
  }
69
+
70
+ async function storedProgressCovers(
71
+ deps: ReportIngestProgressDeps,
72
+ aggregateId: string,
73
+ pagesDone: number,
74
+ ): Promise<boolean> {
75
+ const rows = await selectMany<{ pagesDone: number }>(deps.db, documentIngestProgressTable, {
76
+ id: aggregateId,
77
+ tenantId: deps.tenantId,
78
+ });
79
+ return (rows[0]?.pagesDone ?? 0) >= pagesDone;
80
+ }
@@ -37,7 +37,7 @@ subjects a user may see. It runs for every signed-in handler and query; `false`
37
37
  record. `unscopedRoles` (e.g. `["TenantAdmin"]`) skip it. For a scoped user `signatureRequest:list` keeps only the
38
38
  rows of allowed subjects, reading up to ten base pages per answer (it can still hold fewer rows than `limit`), and has no `total`; screens
39
39
  and nav stay at `access`. `signatureSigner:list` needs a `requestId` eq filter, otherwise 403. `request` also
40
- refuses a document the caller cannot open through `GET /files/:id`.
40
+ refuses a document the caller cannot open through `GET /files/:id`. The list cursor of a scoped user is sealed with a key derived from `linkSecret`, so `authorizeSubject` throws at startup without a non-empty `linkSecret`.
41
41
 
42
42
  ## Handlers
43
43
 
@@ -54,9 +54,9 @@ all get the same 422. Of two simultaneous `sign-by-link` calls exactly one wins.
54
54
 
55
55
  ## Events
56
56
 
57
- `signature:event:completed`, `signature:event:declined`, `signature:event:expired`, each with
58
- request id, subject type and id (and the file id or signer id). A cron job (`signature:job:sweep`, every
59
- 5 minutes, per tenant) expires requests, completes `all-signed` ones and re-checks races.
57
+ `signature:event:completed`, `signature:event:declined`, `signature:event:expired`, `signature:event:failed`, each with
58
+ request id, subject type and id (and the file id, signer id or failure reason). A cron job (`signature:job:sweep`, every
59
+ 5 minutes, per tenant) expires requests, completes `all-signed` ones (a changed or missing original or signature image ends them as `failed`) and re-checks races.
60
60
 
61
61
  ## Client
62
62
 
@@ -1,4 +1,22 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "List cursor of subject-scoped users is sealed",
6
+ "detail": "The request list returned the plain cursor of the last base page, which could name a request of a foreign subject. Scoped users now get an encrypted cursor bound to their user and tenant, a plain or foreign cursor is answered with access denied, and `authorizeSubject` now requires a non-empty `linkSecret` because the cursor key is derived from it. A scoped user asking for `limit: 0` is refused like `offset`."
7
+ },
8
+ {
9
+ "version": "0.418.0",
10
+ "type": "fix",
11
+ "title": "Unrecoverable finalisation ends in status failed",
12
+ "detail": "A request whose original PDF changed or went missing, or whose signature image is missing, used to stay `all-signed` forever while the sweep warned every five minutes. It now ends in the status `failed` with the event `signature:event:failed` and a reason (`document-changed` or `signature-image-missing`). Renderer outages and storage errors still retry on the next run."
13
+ },
14
+ {
15
+ "version": "0.418.0",
16
+ "type": "fix",
17
+ "title": "Empty signatures are rejected on every background",
18
+ "detail": "The ink check treats an image as having a solid background only when all four corners are opaque and identical; a lone opaque pixel no longer counts the whole image as ink, and signer emails must be valid addresses."
19
+ },
2
20
  {
3
21
  "version": "0.417.0",
4
22
  "type": "breaking",
@@ -23,6 +23,7 @@ const REQUEST_STATUS_OPTIONS = [
23
23
  SIGNATURE_REQUEST_STATUS.Completed,
24
24
  SIGNATURE_REQUEST_STATUS.Declined,
25
25
  SIGNATURE_REQUEST_STATUS.Expired,
26
+ SIGNATURE_REQUEST_STATUS.Failed,
26
27
  SIGNATURE_REQUEST_STATUS.Cancelled,
27
28
  ] as const;
28
29
  const SIGNER_STATUS_OPTIONS = [
@@ -48,7 +49,7 @@ export function createSignatureRequestEntity(
48
49
  return createEntity({
49
50
  table: "read_signature_requests",
50
51
  description:
51
- "A request to sign one PDF document by several people, on a display in person or through a link, tracked through open, all-signed, completed, declined, expired and cancelled; the document is referenced by file id and hash and never changed.",
52
+ "A request to sign one PDF document by several people, on a display in person or through a link, tracked through open, all-signed, completed, declined, expired, failed and cancelled; the document is referenced by file id and hash and never changed.",
52
53
  retention: { keepFor: retention.keepFor, strategy: "hardDelete", reference: "createdAt" },
53
54
  fields: {
54
55
  documentFileId: createTextField({
@@ -95,6 +96,7 @@ export function createSignatureRequestEntity(
95
96
  [SIGNATURE_REQUEST_STATUS.Completed]: "ok",
96
97
  [SIGNATURE_REQUEST_STATUS.Declined]: "bad",
97
98
  [SIGNATURE_REQUEST_STATUS.Expired]: "neutral",
99
+ [SIGNATURE_REQUEST_STATUS.Failed]: "bad",
98
100
  [SIGNATURE_REQUEST_STATUS.Cancelled]: "neutral",
99
101
  },
100
102
  }),
@@ -10,7 +10,12 @@ import { createSignatureRequestEntity, createSignatureSignerEntity } from "./ent
10
10
  import { createAnonymousLinkHandlers } from "./handlers/anonymous.write.ts";
11
11
  import { createCancelHandler } from "./handlers/cancel.write.ts";
12
12
  import { createIssueLinkHandler } from "./handlers/issue-link.write.ts";
13
- import { expireHandler, finishHandler, reconcileHandler } from "./handlers/lifecycle.write.ts";
13
+ import {
14
+ expireHandler,
15
+ failHandler,
16
+ finishHandler,
17
+ reconcileHandler,
18
+ } from "./handlers/lifecycle.write.ts";
14
19
  import { createLinkInternalHandlers } from "./handlers/link-internal.write.ts";
15
20
  import { createRequestHandler } from "./handlers/request.write.ts";
16
21
  import { createRevokeLinkHandler } from "./handlers/revoke-link.write.ts";
@@ -22,6 +27,7 @@ import {
22
27
  SignatureCompletedEventSchema,
23
28
  SignatureDeclinedEventSchema,
24
29
  SignatureExpiredEventSchema,
30
+ SignatureFailedEventSchema,
25
31
  } from "./payloads.ts";
26
32
  import { createSignatureDetailScreen, createSignatureListScreen } from "./screens.ts";
27
33
  import { scopeRequestDetail, scopeRequestList, scopeSignerList } from "./subject-queries.ts";
@@ -35,6 +41,9 @@ import {
35
41
  } from "./web/constants.ts";
36
42
 
37
43
  export function createSignatureFeature(opts: SignatureOptions): FeatureDefinition {
44
+ if (opts.authorizeSubject !== undefined && opts.linkSecret === "") {
45
+ throw new Error("authorizeSubject needs a non-empty linkSecret: it also seals the list cursor");
46
+ }
38
47
  const signedInAccess = opts.access ?? DEFAULT_SIGNATURE_ACCESS;
39
48
  const scope = createSubjectScope(opts);
40
49
  const requestEntity = createSignatureRequestEntity(opts.retention);
@@ -44,7 +53,7 @@ export function createSignatureFeature(opts: SignatureOptions): FeatureDefinitio
44
53
 
45
54
  return defineFeature(SIGNATURE_FEATURE, (r) => {
46
55
  r.describe(
47
- "Signature requests: a signed-in user asks several people to sign one PDF of the tenant. Each signer draws a signature on a display in person or through a link in the URL fragment (14 days, limited opens, revocable, single-use, one answer for every rejection). The last signature moves the request to all-signed; a job renders a signature page through the injected print function, appends it to the unchanged original and completes the request. Events completed, declined and expired report the outcome; signer name, email, image, IP and user agent are personal data.",
56
+ "Signature requests: a signed-in user asks several people to sign one PDF of the tenant. Each signer draws a signature on a display in person or through a link in the URL fragment (14 days, limited opens, revocable, single-use, one answer for every rejection). The last signature moves the request to all-signed; a job renders a signature page through the injected print function, appends it to the unchanged original and completes the request. Events completed, declined, expired and failed report the outcome; signer name, email, image, IP and user agent are personal data.",
48
57
  );
49
58
  r.uiHints({ displayLabel: "Signatures", category: "data", recommended: false });
50
59
  r.requires({ features: ["files", "user-data-rights"] });
@@ -63,6 +72,9 @@ export function createSignatureFeature(opts: SignatureOptions): FeatureDefinitio
63
72
  r.defineEvent("expired", SignatureExpiredEventSchema, {
64
73
  piiFields: "none",
65
74
  });
75
+ r.defineEvent("failed", SignatureFailedEventSchema, {
76
+ piiFields: "none",
77
+ });
66
78
 
67
79
  r.writeHandler(createRequestHandler(signedInAccess, scope));
68
80
  r.writeHandler(createSignInPersonHandler(signedInAccess, scope));
@@ -77,6 +89,7 @@ export function createSignatureFeature(opts: SignatureOptions): FeatureDefinitio
77
89
  r.writeHandler(link.linkDecline);
78
90
  r.writeHandler(finishHandler);
79
91
  r.writeHandler(expireHandler);
92
+ r.writeHandler(failHandler);
80
93
  r.writeHandler(reconcileHandler);
81
94
 
82
95
  const requestList = defineEntityListHandler(SIGNATURE_REQUEST_ENTITY, requestEntity, {
@@ -94,7 +107,7 @@ export function createSignatureFeature(opts: SignatureOptions): FeatureDefinitio
94
107
  description:
95
108
  "Lists the signers of requests with their status and way of signing; carries the signers' personal data.",
96
109
  });
97
- r.queryHandler(scopeRequestList(requestList, scope));
110
+ r.queryHandler(scopeRequestList(requestList, scope, opts.linkSecret));
98
111
  r.queryHandler(scopeRequestDetail(requestDetail, scope));
99
112
  r.queryHandler(scopeSignerList(signerList, scope));
100
113
 
@@ -8,7 +8,7 @@ import {
8
8
  listSigners,
9
9
  setRequestStatus,
10
10
  } from "../lib.ts";
11
- import { FinishSchema, RequestIdSchema } from "../payloads.ts";
11
+ import { FailSchema, FinishSchema, RequestIdSchema } from "../payloads.ts";
12
12
  import { SIGNATURE_REQUEST_STATUS, SignatureEvents } from "../web/constants.ts";
13
13
 
14
14
  // The writes of the sweep job. They run as handlers because a job may only append its own
@@ -84,6 +84,38 @@ export const expireHandler = defineWriteHandler({
84
84
  },
85
85
  });
86
86
 
87
+ export const failHandler = defineWriteHandler({
88
+ name: "fail",
89
+ schema: FailSchema,
90
+ access: internalAccess,
91
+ agent: { expose: false },
92
+ description:
93
+ "Internal: ends an all-signed request that can never be completed (original changed or missing, signature image missing) as failed and emits the failed event once.",
94
+ handler: async (event, ctx) => {
95
+ const request = await requestExecutor.detail(
96
+ { id: event.payload.requestId },
97
+ event.user,
98
+ ctx.db,
99
+ );
100
+ if (request === null) return { isSuccess: true, data: { failed: false } };
101
+ const moved = await setRequestStatus(
102
+ ctx,
103
+ event.user,
104
+ request.id,
105
+ SIGNATURE_REQUEST_STATUS.AllSigned,
106
+ { status: SIGNATURE_REQUEST_STATUS.Failed },
107
+ );
108
+ if (!moved.isSuccess) return { isSuccess: true, data: { failed: false } };
109
+ await appendOutcomeEvent(ctx, SignatureEvents.failed, {
110
+ requestId: request.id,
111
+ subjectType: request.subjectType,
112
+ subjectId: request.subjectId,
113
+ reason: event.payload.reason,
114
+ });
115
+ return { isSuccess: true, data: { failed: true } };
116
+ },
117
+ });
118
+
87
119
  // Two last signers committing at the same moment can each still see the other as unsigned; the
88
120
  // sweep repeats the check so such a request cannot stay open for good.
89
121
  export const reconcileHandler = defineWriteHandler({
@@ -48,5 +48,6 @@ export const SIGNATURE_I18N: Readonly<Record<string, LocalizedString>> = {
48
48
  [`${REQUEST}:status:option:completed`]: { en: "Completed", de: "Abgeschlossen" },
49
49
  [`${REQUEST}:status:option:declined`]: { en: "Declined", de: "Abgelehnt" },
50
50
  [`${REQUEST}:status:option:expired`]: { en: "Expired", de: "Abgelaufen" },
51
+ [`${REQUEST}:status:option:failed`]: { en: "Failed", de: "Fehlgeschlagen" },
51
52
  [`${REQUEST}:status:option:cancelled`]: { en: "Cancelled", de: "Abgebrochen" },
52
53
  };
@@ -0,0 +1,59 @@
1
+ import { createHmac } from "node:crypto";
2
+ import type { SessionUser } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
4
+ import { CompactEncrypt, compactDecrypt } from "jose";
5
+
6
+ // Domain separation: the same secret also keys the link HMAC.
7
+ const CURSOR_KEY_LABEL = "signature-list-cursor";
8
+ const encoder = new TextEncoder();
9
+ const decoder = new TextDecoder();
10
+
11
+ type SealedCursorPayload = { readonly c: string; readonly u: string; readonly t: string };
12
+
13
+ function isSealedCursorPayload(value: unknown): value is SealedCursorPayload {
14
+ return (
15
+ isPlainObject(value) &&
16
+ typeof value["c"] === "string" &&
17
+ typeof value["u"] === "string" &&
18
+ typeof value["t"] === "string"
19
+ );
20
+ }
21
+
22
+ function cursorKey(secret: string): Uint8Array {
23
+ return new Uint8Array(createHmac("sha256", secret).update(CURSOR_KEY_LABEL).digest());
24
+ }
25
+
26
+ export async function sealListCursor(
27
+ baseCursor: string,
28
+ user: SessionUser,
29
+ secret: string,
30
+ ): Promise<string> {
31
+ const payload: SealedCursorPayload = {
32
+ c: baseCursor,
33
+ u: String(user.id),
34
+ t: String(user.tenantId),
35
+ };
36
+ return new CompactEncrypt(encoder.encode(JSON.stringify(payload)))
37
+ .setProtectedHeader({ alg: "dir", enc: "A256GCM" })
38
+ .encrypt(cursorKey(secret));
39
+ }
40
+
41
+ export async function openListCursor(
42
+ sealed: string,
43
+ user: SessionUser,
44
+ secret: string,
45
+ ): Promise<string | null> {
46
+ try {
47
+ // Allowlist: a foreign header such as PBES2 would cost PBKDF2 rounds per request.
48
+ const { plaintext } = await compactDecrypt(sealed, cursorKey(secret), {
49
+ keyManagementAlgorithms: ["dir"],
50
+ contentEncryptionAlgorithms: ["A256GCM"],
51
+ });
52
+ const payload: unknown = JSON.parse(decoder.decode(plaintext));
53
+ if (!isSealedCursorPayload(payload)) return null;
54
+ if (payload.u !== String(user.id) || payload.t !== String(user.tenantId)) return null;
55
+ return payload.c;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
@@ -45,13 +45,13 @@ export type SignatureOptions = {
45
45
  readonly renderHtmlToPdf: RenderSignatureHtmlToPdf;
46
46
  /** HMAC secret of the signing links. Without it every link is rejected. */
47
47
  readonly linkSecret: string;
48
- /** Sends a freshly issued link to the signer, e.g. by mail. A throw fails issue-link and leaves no link sent. */
48
+ /** Sends a freshly issued link to the signer, e.g. by mail. Runs inside the issue-link transaction, before it commits: enqueue through `ctx.dispatch` so the send commits or rolls back with the new link; a throw fails issue-link and leaves no link sent. */
49
49
  readonly deliverLink: DeliverSignatureLink;
50
50
  /** URL of the app's signature page; the token is appended as `#<token>`. */
51
51
  readonly signaturePageUrl: string;
52
52
  /** Access rule of the signed-in handlers, queries, screens and nav. Default `{ roles: ["TenantAdmin", "TenantMember"] }`; set it when the app hands out other roles. The link handlers stay anonymous. */
53
53
  readonly access?: AccessRule;
54
- /** Runs for every signed-in handler and query on the subject of the request, except for `unscopedRoles`. `false` answers like "does not exist". Without it every user with `access` sees every request of the tenant. */
54
+ /** Runs for every signed-in handler and query on the subject of the request, except for `unscopedRoles`. `false` answers like "does not exist". Without it every user with `access` sees every request of the tenant. Needs a non-empty `linkSecret`, which also seals the list cursor. */
55
55
  readonly authorizeSubject?: AuthorizeSignatureSubject;
56
56
  /** Roles that skip `authorizeSubject`, e.g. admins. */
57
57
  readonly unscopedRoles?: readonly string[];
@@ -1,6 +1,6 @@
1
1
  import * as z from "zod";
2
2
  import { MAX_SIGNATURE_PNG_BYTES } from "./png.ts";
3
- import { SIGNATURE_LEVEL } from "./web/constants.ts";
3
+ import { SIGNATURE_FAILURE_REASON, SIGNATURE_LEVEL } from "./web/constants.ts";
4
4
 
5
5
  export const MAX_SIGNERS_PER_REQUEST = 20;
6
6
  const MAX_VALIDITY_DAYS = 365;
@@ -12,7 +12,7 @@ const SignerInputSchema = z.object({
12
12
  name: z.string().trim().min(1).max(200),
13
13
  role: z.string().trim().min(1).max(100).optional(),
14
14
  contactId: z.string().min(1).max(64).optional(),
15
- email: z.string().trim().min(3).max(320).optional(),
15
+ email: z.string().trim().max(320).pipe(z.email()).optional(),
16
16
  });
17
17
 
18
18
  export const RequestSignatureSchema = z.object({
@@ -49,6 +49,13 @@ export const DeclineByLinkSchema = z.object({
49
49
  reason: z.string().trim().min(1).max(1000).optional(),
50
50
  });
51
51
 
52
+ const FailureReasonSchema = z.enum([
53
+ SIGNATURE_FAILURE_REASON.DocumentChanged,
54
+ SIGNATURE_FAILURE_REASON.SignatureImageMissing,
55
+ ]);
56
+
57
+ export const FailSchema = z.object({ requestId: z.uuid(), reason: FailureReasonSchema });
58
+
52
59
  export const FinishSchema = z.object({ requestId: z.uuid(), completedFileId: z.uuid() });
53
60
 
54
61
  const OutcomeBase = {
@@ -69,3 +76,8 @@ export const SignatureDeclinedEventSchema = z.object({
69
76
  });
70
77
 
71
78
  export const SignatureExpiredEventSchema = z.object(OutcomeBase);
79
+
80
+ export const SignatureFailedEventSchema = z.object({
81
+ ...OutcomeBase,
82
+ reason: FailureReasonSchema,
83
+ });