@cosmicdrift/kumiko-samples 0.416.0 → 0.418.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 (59) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +1 -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/helpdesk/screens.ts +5 -1
  15. package/packages/bundled-features/src/signature/README.md +10 -3
  16. package/packages/bundled-features/src/signature/changes.json +25 -0
  17. package/packages/bundled-features/src/signature/entity.ts +3 -1
  18. package/packages/bundled-features/src/signature/feature.ts +41 -28
  19. package/packages/bundled-features/src/signature/handlers/cancel.write.ts +11 -3
  20. package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +5 -0
  21. package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +33 -1
  22. package/packages/bundled-features/src/signature/handlers/request.write.ts +37 -3
  23. package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +15 -1
  24. package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +5 -1
  25. package/packages/bundled-features/src/signature/i18n.ts +1 -0
  26. package/packages/bundled-features/src/signature/index.ts +2 -0
  27. package/packages/bundled-features/src/signature/list-cursor-seal.ts +59 -0
  28. package/packages/bundled-features/src/signature/options.ts +16 -1
  29. package/packages/bundled-features/src/signature/payloads.ts +14 -2
  30. package/packages/bundled-features/src/signature/png.ts +25 -4
  31. package/packages/bundled-features/src/signature/screens.ts +2 -0
  32. package/packages/bundled-features/src/signature/static-sign.ts +2 -1
  33. package/packages/bundled-features/src/signature/subject-queries.ts +184 -0
  34. package/packages/bundled-features/src/signature/subject-scope.ts +43 -0
  35. package/packages/bundled-features/src/signature/sweep.ts +32 -8
  36. package/packages/bundled-features/src/signature/web/constants.ts +12 -0
  37. package/packages/bundled-features/src/subscription-paddle/changes.json +1 -1
  38. package/packages/bundled-features/src/subscription-stripe/changes.json +6 -0
  39. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +2 -0
  40. package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +21 -16
  41. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +7 -3
  42. package/packages/bundled-features/src/tenant-lifecycle/changes.json +6 -0
  43. package/packages/bundled-features/src/tenant-lifecycle/run-tenant-destroy.ts +90 -42
  44. package/samples/apps/use-all-bundled/feature-manifest.json +2 -1
  45. package/samples/recipes/crypto-shredding-hr/README.md +1 -1
  46. package/samples/recipes/crypto-shredding-hr/src/feature.ts +1 -1
  47. package/samples/recipes/dashboard-stats/README.md +4 -0
  48. package/samples/recipes/dashboard-stats/src/feature.ts +47 -0
  49. package/samples/recipes/event-sourcing/src/feature.ts +31 -0
  50. package/samples/recipes/list-table-options/README.md +18 -3
  51. package/samples/recipes/list-table-options/src/feature.ts +170 -5
  52. package/samples/recipes/managed-config/src/feature.ts +9 -1
  53. package/samples/recipes/record-detail-layout/README.md +7 -0
  54. package/samples/recipes/record-detail-layout/src/feature.ts +40 -2
  55. package/samples/recipes/record-detail-layout/src/order-board.ts +1 -0
  56. package/samples/recipes/secrets-demo/README.md +1 -1
  57. package/samples/recipes/secrets-demo/src/feature.ts +2 -0
  58. package/samples/recipes/writeform-section/README.md +4 -0
  59. package/samples/recipes/writeform-section/src/feature.ts +97 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-samples",
3
- "version": "0.416.0",
3
+ "version": "0.418.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.416.0",
3
+ "version": "0.418.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>",
@@ -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
+ }
@@ -323,7 +323,11 @@ function createRequestDetailScreen(
323
323
  field: "authorName",
324
324
  label: `${HELPDESK_FEATURE}:entity:helpdesk-reply:field:authorName`,
325
325
  },
326
- { field: "message", label: `${HELPDESK_FEATURE}:entity:helpdesk-reply:field:message` },
326
+ {
327
+ field: "message",
328
+ label: `${HELPDESK_FEATURE}:entity:helpdesk-reply:field:message`,
329
+ multiline: true,
330
+ },
327
331
  ],
328
332
  },
329
333
  {
@@ -32,6 +32,13 @@ the `files` feature. Order of signatures is free.
32
32
  | `signaturePageUrl` | required | URL of the app's signature page; the token is appended as `#<token>` |
33
33
  | `access` | `{ roles: ["TenantAdmin", "TenantMember"] }` | `AccessRule` of the signed-in handlers, queries, screens and nav; set it when the app hands out other roles. Link handlers stay anonymous |
34
34
 
35
+ Subject scope: `authorizeSubject(ctx, user, { subjectType, subjectId })` limits requests to the
36
+ subjects a user may see. It runs for every signed-in handler and query; `false` answers like a missing
37
+ record. `unscopedRoles` (e.g. `["TenantAdmin"]`) skip it. For a scoped user `signatureRequest:list` keeps only the
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
+ 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`. 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
+
35
42
  ## Handlers
36
43
 
37
44
  Signed in: `request`, `sign-in-person`, `issue-link`, `revoke-link`, `cancel`.
@@ -47,9 +54,9 @@ all get the same 422. Of two simultaneous `sign-by-link` calls exactly one wins.
47
54
 
48
55
  ## Events
49
56
 
50
- `signature:event:completed`, `signature:event:declined`, `signature:event:expired`, each with
51
- request id, subject type and id (and the file id or signer id). A cron job (`signature:job:sweep`, every
52
- 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.
53
60
 
54
61
  ## Client
55
62
 
@@ -1,4 +1,29 @@
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
+ },
20
+ {
21
+ "version": "0.417.0",
22
+ "type": "breaking",
23
+ "title": "Subject check for the signature feature and a readable-file check on requests",
24
+ "detail": "`createSignatureFeature({ ..., authorizeSubject, unscopedRoles })`: `authorizeSubject(ctx, user, { subjectType, subjectId })` runs for `request`, `cancel`, `issue-link`, `revoke-link`, `sign-in-person` and the queries, except for users holding a role of `unscopedRoles`; `false` answers like a missing record (not found, `null` or an empty page). `signatureRequest:list` keeps only the rows of allowed subjects for a scoped user and reads up to ten base pages to fill one answer (no 403; an answer can still hold fewer rows than `limit`, and it has no `total`); screens and nav stay at `access`. A scoped user must pass a `requestId` eq filter to `signatureSigner:list`, otherwise the query answers 403. `request` now also checks that the caller may read the document through the same decision as GET /files/:id; a file that is unknown or not readable answers `document_not_a_pdf`. `SIGNATURE_INVALID_LINK_REASON` is exported from `signature/static-sign`.",
25
+ "migration": "Apps that request a signature on a file the caller cannot open through GET /files/:id bind it to a record the caller can read first. Apps with authorizeSubject pass a requestId eq filter to signatureSigner:list and do not rely on `total` of signatureRequest:list for scoped users."
26
+ },
2
27
  {
3
28
  "version": "0.416.0",
4
29
  "type": "improvement",
@@ -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,8 +27,11 @@ 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";
33
+ import { scopeRequestDetail, scopeRequestList, scopeSignerList } from "./subject-queries.ts";
34
+ import { createSubjectScope } from "./subject-scope.ts";
27
35
  import { sweepSignatureRequests } from "./sweep.ts";
28
36
  import { signatureDeleteHook, signatureExportHook } from "./user-data.ts";
29
37
  import {
@@ -33,7 +41,11 @@ import {
33
41
  } from "./web/constants.ts";
34
42
 
35
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
+ }
36
47
  const signedInAccess = opts.access ?? DEFAULT_SIGNATURE_ACCESS;
48
+ const scope = createSubjectScope(opts);
37
49
  const requestEntity = createSignatureRequestEntity(opts.retention);
38
50
  const signerEntity = createSignatureSignerEntity(opts.retention);
39
51
  const anonymous = createAnonymousLinkHandlers(LINK_RATE_LIMIT);
@@ -41,7 +53,7 @@ export function createSignatureFeature(opts: SignatureOptions): FeatureDefinitio
41
53
 
42
54
  return defineFeature(SIGNATURE_FEATURE, (r) => {
43
55
  r.describe(
44
- "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.",
45
57
  );
46
58
  r.uiHints({ displayLabel: "Signatures", category: "data", recommended: false });
47
59
  r.requires({ features: ["files", "user-data-rights"] });
@@ -60,12 +72,15 @@ export function createSignatureFeature(opts: SignatureOptions): FeatureDefinitio
60
72
  r.defineEvent("expired", SignatureExpiredEventSchema, {
61
73
  piiFields: "none",
62
74
  });
75
+ r.defineEvent("failed", SignatureFailedEventSchema, {
76
+ piiFields: "none",
77
+ });
63
78
 
64
- r.writeHandler(createRequestHandler(signedInAccess));
65
- r.writeHandler(createSignInPersonHandler(signedInAccess));
66
- r.writeHandler(createIssueLinkHandler(signedInAccess, opts));
67
- r.writeHandler(createRevokeLinkHandler(signedInAccess));
68
- r.writeHandler(createCancelHandler(signedInAccess));
79
+ r.writeHandler(createRequestHandler(signedInAccess, scope));
80
+ r.writeHandler(createSignInPersonHandler(signedInAccess, scope));
81
+ r.writeHandler(createIssueLinkHandler(signedInAccess, scope, opts));
82
+ r.writeHandler(createRevokeLinkHandler(signedInAccess, scope));
83
+ r.writeHandler(createCancelHandler(signedInAccess, scope));
69
84
  r.writeHandler(anonymous.openByLink);
70
85
  r.writeHandler(anonymous.signByLink);
71
86
  r.writeHandler(anonymous.declineByLink);
@@ -74,29 +89,27 @@ export function createSignatureFeature(opts: SignatureOptions): FeatureDefinitio
74
89
  r.writeHandler(link.linkDecline);
75
90
  r.writeHandler(finishHandler);
76
91
  r.writeHandler(expireHandler);
92
+ r.writeHandler(failHandler);
77
93
  r.writeHandler(reconcileHandler);
78
94
 
79
- r.queryHandler(
80
- defineEntityListHandler(SIGNATURE_REQUEST_ENTITY, requestEntity, {
81
- access: signedInAccess,
82
- description:
83
- "Lists signature requests with status, deadline and the object they belong to; paging, search over the title and sorting.",
84
- }),
85
- );
86
- r.queryHandler(
87
- defineEntityDetailHandler(SIGNATURE_REQUEST_ENTITY, requestEntity, {
88
- access: signedInAccess,
89
- description: "Returns one signature request.",
90
- }),
91
- );
92
- r.queryHandler(
93
- defineEntityListHandler(SIGNATURE_SIGNER_ENTITY, signerEntity, {
94
- access: signedInAccess,
95
- agent: { expose: false },
96
- description:
97
- "Lists the signers of requests with their status and way of signing; carries the signers' personal data.",
98
- }),
99
- );
95
+ const requestList = defineEntityListHandler(SIGNATURE_REQUEST_ENTITY, requestEntity, {
96
+ access: signedInAccess,
97
+ description:
98
+ "Lists signature requests with status, deadline and the object they belong to; paging, search over the title and sorting.",
99
+ });
100
+ const requestDetail = defineEntityDetailHandler(SIGNATURE_REQUEST_ENTITY, requestEntity, {
101
+ access: signedInAccess,
102
+ description: "Returns one signature request.",
103
+ });
104
+ const signerList = defineEntityListHandler(SIGNATURE_SIGNER_ENTITY, signerEntity, {
105
+ access: signedInAccess,
106
+ agent: { expose: false },
107
+ description:
108
+ "Lists the signers of requests with their status and way of signing; carries the signers' personal data.",
109
+ });
110
+ r.queryHandler(scopeRequestList(requestList, scope, opts.linkSecret));
111
+ r.queryHandler(scopeRequestDetail(requestDetail, scope));
112
+ r.queryHandler(scopeSignerList(signerList, scope));
100
113
 
101
114
  r.useExtension(EXT_USER_DATA, SIGNATURE_SIGNER_ENTITY, {
102
115
  export: signatureExportHook,
@@ -1,12 +1,14 @@
1
1
  import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
- import { signerExecutor } from "../entity.ts";
2
+ import { NotFoundError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import { requestExecutor, signerExecutor } from "../entity.ts";
3
4
  import { isUnsignedSigner, listSigners, setRequestStatus } from "../lib.ts";
4
5
  import { RequestIdSchema } from "../payloads.ts";
5
- import { SIGNATURE_REQUEST_STATUS } from "../web/constants.ts";
6
+ import type { SubjectScope } from "../subject-scope.ts";
7
+ import { SIGNATURE_REQUEST_ENTITY, SIGNATURE_REQUEST_STATUS } from "../web/constants.ts";
6
8
 
7
9
  // Cancelling moves the request out of `open`, which already makes every link of it fail; the
8
10
  // anchors are cleared as well so no token verifies against a cancelled request.
9
- export function createCancelHandler(access: AccessRule) {
11
+ export function createCancelHandler(access: AccessRule, scope: SubjectScope) {
10
12
  return defineWriteHandler<"cancel", typeof RequestIdSchema, { readonly cancelled: true }>({
11
13
  name: "cancel",
12
14
  schema: RequestIdSchema,
@@ -16,6 +18,12 @@ export function createCancelHandler(access: AccessRule) {
16
18
  "Cancels an open signature request; all its signing links stop working. Signatures already given stay on record.",
17
19
  handler: async (event, ctx) => {
18
20
  const user = event.user;
21
+ if (scope.isScoped(user)) {
22
+ const request = await requestExecutor.detail({ id: event.payload.requestId }, user, ctx.db);
23
+ if (request === null || !(await scope.allowsRequest(ctx, user, request))) {
24
+ return writeFailure(new NotFoundError(SIGNATURE_REQUEST_ENTITY, event.payload.requestId));
25
+ }
26
+ }
19
27
  const moved = await setRequestStatus(
20
28
  ctx,
21
29
  user,
@@ -10,12 +10,14 @@ import { signSignatureLinkToken } from "../grant.ts";
10
10
  import { isOpenRequest, isUnsignedSigner, loadRequestOfSigner } from "../lib.ts";
11
11
  import type { SignatureOptions } from "../options.ts";
12
12
  import { SignerIdSchema } from "../payloads.ts";
13
+ import type { SubjectScope } from "../subject-scope.ts";
13
14
 
14
15
  export type IssueLinkData = { readonly signerId: string; readonly linkSentAt: string };
15
16
 
16
17
  // A new link replaces the previous one: the anchor moves on, so the old token stops verifying.
17
18
  export function createIssueLinkHandler(
18
19
  access: AccessRule,
20
+ scope: SubjectScope,
19
21
  opts: Pick<SignatureOptions, "linkSecret" | "deliverLink" | "signaturePageUrl">,
20
22
  ) {
21
23
  return defineWriteHandler<"issue-link", typeof SignerIdSchema, IssueLinkData>({
@@ -30,6 +32,9 @@ export function createIssueLinkHandler(
30
32
  const signer = await signerExecutor.detail({ id: event.payload.signerId }, user, ctx.db);
31
33
  if (signer === null) return writeFailure(new NotFoundError("signer", event.payload.signerId));
32
34
  const request = await loadRequestOfSigner(ctx, user, signer);
35
+ if (request !== null && !(await scope.allowsRequest(ctx, user, request))) {
36
+ return writeFailure(new NotFoundError("signer", event.payload.signerId));
37
+ }
33
38
  const now = ctx.tz.now();
34
39
  if (request === null || !isOpenRequest(request, now) || !isUnsignedSigner(signer)) {
35
40
  return writeFailure(new UnprocessableError("link_not_possible"));
@@ -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({