@cosmicdrift/kumiko-bundled-features 0.417.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 (41) hide show
  1. package/dist/agent-tools/api-docs/schema-fields.js +9 -0
  2. package/dist/auth-email-password/index.d.ts +2 -1
  3. package/dist/auth-email-password/index.js +2 -1
  4. package/dist/auth-email-password/signup-activation.js +2 -1
  5. package/dist/auth-email-password/signup-token-store.d.ts +1 -6
  6. package/dist/auth-email-password/signup-token-store.js +0 -5
  7. package/dist/cap-counter/stock-cap-guard.d.ts +9 -2
  8. package/dist/cap-counter/stock-cap-guard.js +9 -11
  9. package/dist/document-ingest-foundation/feature.js +5 -1
  10. package/dist/document-ingest-foundation/report-ingest-progress.js +19 -6
  11. package/dist/signature/entity.d.ts +8 -6
  12. package/dist/signature/entity.js +3 -1
  13. package/dist/signature/feature.js +11 -4
  14. package/dist/signature/handlers/lifecycle.write.d.ts +9 -0
  15. package/dist/signature/handlers/lifecycle.write.js +23 -1
  16. package/dist/signature/handlers/request.write.d.ts +1 -1
  17. package/dist/signature/i18n.js +1 -0
  18. package/dist/signature/list-cursor-seal.d.ts +3 -0
  19. package/dist/signature/list-cursor-seal.js +44 -0
  20. package/dist/signature/options.d.ts +2 -2
  21. package/dist/signature/payloads.d.ts +17 -1
  22. package/dist/signature/payloads.js +11 -2
  23. package/dist/signature/png.js +23 -3
  24. package/dist/signature/subject-queries.d.ts +1 -1
  25. package/dist/signature/subject-queries.js +30 -8
  26. package/dist/signature/sweep.js +26 -9
  27. package/dist/signature/web/constants.d.ts +9 -0
  28. package/dist/signature/web/constants.js +8 -0
  29. package/dist/subscription-stripe/plugin-methods.js +2 -0
  30. package/dist/subscription-stripe/verify-webhook.js +17 -16
  31. package/dist/tenant-inactivity/handlers/keep-account.write.js +5 -2
  32. package/dist/tenant-lifecycle/run-tenant-destroy.js +65 -33
  33. package/package.json +11 -11
  34. package/src/agent-tools/changes.json +6 -0
  35. package/src/cap-counter/changes.json +6 -0
  36. package/src/channel-whatsapp/changes.json +1 -1
  37. package/src/document-ingest-foundation/changes.json +6 -0
  38. package/src/signature/changes.json +18 -0
  39. package/src/subscription-paddle/changes.json +1 -1
  40. package/src/subscription-stripe/changes.json +6 -0
  41. package/src/tenant-lifecycle/changes.json +6 -0
@@ -36,6 +36,13 @@ function resolveRef(node, root) {
36
36
  function alternatives(node) {
37
37
  return [...nodeList(node["anyOf"]), ...nodeList(node["oneOf"])];
38
38
  }
39
+ function typeArrayLabel(node, type, root, depth) {
40
+ const names = type.filter((name) => typeof name === "string");
41
+ const labels = names
42
+ .filter((name) => name !== "null")
43
+ .map((name) => typeLabel({ ...node, type: name }, root, depth + 1));
44
+ return [...labels, ...(names.includes("null") ? ["null"] : [])].join(" | ") || "any";
45
+ }
39
46
  export function typeLabel(rawNode, root = rawNode, depth = 0) {
40
47
  const node = resolveRef(rawNode, root);
41
48
  if (depth > MAX_SCHEMA_DEPTH)
@@ -51,6 +58,8 @@ export function typeLabel(rawNode, root = rawNode, depth = 0) {
51
58
  if ("const" in node)
52
59
  return JSON.stringify(node["const"]);
53
60
  const type = node["type"];
61
+ if (Array.isArray(type))
62
+ return typeArrayLabel(node, type, root, depth);
54
63
  if (type === "array") {
55
64
  const items = asNode(node["items"]);
56
65
  return `array of ${items === undefined ? "any" : typeLabel(items, root, depth + 1)}`;
@@ -1,3 +1,4 @@
1
+ export { normalizeEmail } from "../shared/index.ts";
1
2
  export { hashPassword, verifyPassword } from "../shared/password-hashing.ts";
2
3
  export type { BootstrapConfigValue, BootstrapDeps, BootstrapInvite, BootstrapInviteOutcome, BootstrapPlan, BootstrapReport, BootstrapSeedDeps, BootstrapSystemAdmin, BootstrapTenant, BootstrapTenantOutcome, } from "./bootstrap.ts";
3
4
  export { BootstrapPlanError, BootstrapWriteError, bootstrapTenants } from "./bootstrap.ts";
@@ -8,6 +9,6 @@ export { AuthMailNotificationTypes } from "./mail-notifications.ts";
8
9
  export { AUTH_SELF_REGISTRATION_FEATURE, createAuthSelfRegistrationToggleFeature, } from "./self-registration-toggle.ts";
9
10
  export { signToken, TokenPurpose, type VerifyResult, verifyToken } from "./signed-token.ts";
10
11
  export { type IssuedSignupActivation, type IssueSignupActivationArgs, issueSignupActivation, SIGNUP_ACTIVATION_NOTIFICATION_TYPE, } from "./signup-activation.ts";
11
- export { invalidateExistingSignupToken, normalizeEmail, SIGNUP_TOKEN_KEY_PREFIXES, storeSignupToken, } from "./signup-token-store.ts";
12
+ export { invalidateExistingSignupToken, SIGNUP_TOKEN_KEY_PREFIXES, storeSignupToken, } from "./signup-token-store.ts";
12
13
  export { type AuthPath, type AuthPaths, DEFAULT_AUTH_PATHS, DEFAULT_FORGOT_PASSWORD_PATH, makeAuthPaths, } from "./web/auth-paths.ts";
13
14
  export { AUTH_EMAIL_PASSWORD_FEATURE, AuthErrors, AuthHandlers, AuthQueries, } from "./web/constants.ts";
@@ -1,5 +1,6 @@
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
+ export { normalizeEmail } from "../shared/index.js";
3
4
  // Kept as a public re-export (not just internal call sites) — this feature's
4
5
  // barrel is where consumers of the published package have always found
5
6
  // hashPassword/verifyPassword; removing it is a breaking change that needs
@@ -16,6 +17,6 @@ export { AUTH_SELF_REGISTRATION_FEATURE, createAuthSelfRegistrationToggleFeature
16
17
  // cross-replay between flows.
17
18
  export { signToken, TokenPurpose, verifyToken } from "./signed-token.js";
18
19
  export { issueSignupActivation, SIGNUP_ACTIVATION_NOTIFICATION_TYPE, } from "./signup-activation.js";
19
- export { invalidateExistingSignupToken, normalizeEmail, SIGNUP_TOKEN_KEY_PREFIXES, storeSignupToken, } from "./signup-token-store.js";
20
+ export { invalidateExistingSignupToken, SIGNUP_TOKEN_KEY_PREFIXES, storeSignupToken, } from "./signup-token-store.js";
20
21
  export { DEFAULT_AUTH_PATHS, DEFAULT_FORGOT_PASSWORD_PATH, makeAuthPaths, } from "./web/auth-paths.js";
21
22
  export { AUTH_EMAIL_PASSWORD_FEATURE, AuthErrors, AuthHandlers, AuthQueries, } from "./web/constants.js";
@@ -5,9 +5,10 @@
5
5
  // cannot drift between the two.
6
6
  import { generateToken } from "@cosmicdrift/kumiko-framework/api";
7
7
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
8
+ import { normalizeEmail } from "../shared/index.js";
8
9
  import { dispatchMagicLinkMail } from "./magic-link-mail.js";
9
10
  import { AuthMailNotificationTypes } from "./mail-notifications.js";
10
- import { invalidateExistingSignupToken, normalizeEmail, storeSignupToken, } from "./signup-token-store.js";
11
+ import { invalidateExistingSignupToken, storeSignupToken } from "./signup-token-store.js";
11
12
  import { AUTH_SIGNUP_DEFAULT_TTL_MINUTES } from "./web/constants.js";
12
13
  export const SIGNUP_ACTIVATION_NOTIFICATION_TYPE = AuthMailNotificationTypes.signupActivation;
13
14
  export async function issueSignupActivation(args) {
@@ -1,10 +1,5 @@
1
1
  import type { Redis } from "ioredis";
2
- import { normalizeEmail, type SignupHandoverBinding } from "../shared/index.ts";
3
- /** Email normalization — single source for every lookup layer (used
4
- * internally by the store AND by callers that need a consistent form
5
- * in the return body / mail send). Previously two places called
6
- * `.toLowerCase()` — one source means no drift. */
7
- export { normalizeEmail };
2
+ import { type SignupHandoverBinding } from "../shared/index.ts";
8
3
  export declare const SIGNUP_TOKEN_KEY_PREFIXES: {
9
4
  readonly token: "signup:by-token:";
10
5
  readonly email: "signup:by-email:";
@@ -11,11 +11,6 @@
11
11
  // `signup:`-prefix.
12
12
  import * as z from "zod";
13
13
  import { createSingleUseTokenStore, hashSingleUseToken, normalizeEmail, } from "../shared/index.js";
14
- /** Email normalization — single source for every lookup layer (used
15
- * internally by the store AND by callers that need a consistent form
16
- * in the return body / mail send). Previously two places called
17
- * `.toLowerCase()` — one source means no drift. */
18
- export { normalizeEmail };
19
14
  export const SIGNUP_TOKEN_KEY_PREFIXES = {
20
15
  token: "signup:by-token:",
21
16
  email: "signup:by-email:",
@@ -1,6 +1,8 @@
1
1
  import type { EntityTableMeta, SchemaTable, TenantDb, WhereObject } from "@cosmicdrift/kumiko-framework/db";
2
- import type { ConfigAccessor, WriteHandlerDef } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { ConfigAccessor, KumikoEventTypeMap, WriteHandlerDef, WriteHandlerDefinition } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import { type WriteFailure } from "@cosmicdrift/kumiko-framework/errors";
4
+ import type { BeforeTransactionWhenNested } from "@cosmicdrift/kumiko-types/handlers";
5
+ import type { ZodType } from "zod";
4
6
  export type CapLimitContext = {
5
7
  readonly config?: ConfigAccessor;
6
8
  };
@@ -16,8 +18,13 @@ export type StockCapSpec<TCaps> = {
16
18
  readonly field: string;
17
19
  };
18
20
  export declare function countedSetKey(spec: Pick<StockCapSpec<unknown>, "table" | "where">): string;
21
+ type WriteHandlerWithStockCap<TCaps> = {
22
+ (handler: WriteHandlerDef, spec: StockCapSpec<TCaps>): WriteHandlerDef;
23
+ <TName extends string, TSchema extends ZodType, TData, TPrepared, TWhenNested extends BeforeTransactionWhenNested | undefined>(handler: WriteHandlerDefinition<TName, TSchema, TData, KumikoEventTypeMap, TPrepared, TWhenNested>, spec: StockCapSpec<TCaps>): WriteHandlerDefinition<TName, TSchema, TData, KumikoEventTypeMap, TPrepared, TWhenNested>;
24
+ };
19
25
  export type StockCapGuard<TCaps> = {
20
26
  readonly checkStockCap: (db: TenantDb, spec: StockCapSpec<TCaps>, context?: CapLimitContext) => Promise<WriteFailure | null>;
21
- readonly withStockCap: (handler: WriteHandlerDef, spec: StockCapSpec<TCaps>) => WriteHandlerDef;
27
+ readonly withStockCap: WriteHandlerWithStockCap<TCaps>;
22
28
  };
23
29
  export declare function createStockCapGuard<TCaps>(resolveTierCaps: (db: TenantDb, context: CapLimitContext) => Promise<TCaps>): StockCapGuard<TCaps>;
30
+ export {};
@@ -45,18 +45,16 @@ export function createStockCapGuard(resolveTierCaps) {
45
45
  details: { field: spec.field, current, limit },
46
46
  }));
47
47
  }
48
- function withStockCap(handler, spec) {
49
- return {
50
- ...handler,
51
- handler: async (event, ctx) => {
52
- // ctx.db is the handler's transaction, so the xact lock releases with its commit or
53
- // rollback. A handler wrapped in several caps must list them in the same order
54
- // everywhere; Postgres aborts one side of an inverse order with a deadlock error.
55
- await ctx.db.advisoryXactLock(STOCK_CAP_LOCK_NAMESPACE, countedSetKey(spec));
56
- const failure = await checkStockCap(ctx.db, spec, { config: ctx.config });
57
- return failure ?? handler.handler(event, ctx);
58
- },
48
+ function guardHandlerFn(inner, spec) {
49
+ return async (event, ctx) => {
50
+ // ctx.db is the handler's transaction, so the xact lock releases with its commit or
51
+ // rollback. A handler wrapped in several caps must list them in the same order
52
+ // everywhere; Postgres aborts one side of an inverse order with a deadlock error.
53
+ await ctx.db.advisoryXactLock(STOCK_CAP_LOCK_NAMESPACE, countedSetKey(spec));
54
+ const failure = await checkStockCap(ctx.db, spec, { config: ctx.config });
55
+ return failure ?? inner(event, ctx);
59
56
  };
60
57
  }
58
+ const withStockCap = (handler, spec) => ({ ...handler, handler: guardHandlerFn(handler.handler, spec) });
61
59
  return { checkStockCap, withStockCap };
62
60
  }
@@ -3,7 +3,7 @@
3
3
  // Provider-driven PDF/Scan/Image → normalized-text ingest primitive. No
4
4
  // hardcoded mime allowlist or size cap — providers register via
5
5
  // EXT_DOCUMENT_INGEST_PROVIDER (see providers.ts).
6
- import { applyEntityEvent, entityEventName, upsertByPk } from "@cosmicdrift/kumiko-framework/db";
6
+ import { applyEntityEvent, entityEventName, selectMany, upsertByPk, } from "@cosmicdrift/kumiko-framework/db";
7
7
  import { access, createTenantConfig, defineFeature, EXT_TENANT_DATA, } from "@cosmicdrift/kumiko-framework/engine";
8
8
  import { normalizeMimeType } from "@cosmicdrift/kumiko-framework/files";
9
9
  import * as z from "zod";
@@ -162,6 +162,10 @@ export function createDocumentIngestFoundationFeature() {
162
162
  apply: {
163
163
  [DOCUMENT_INGEST_PROGRESS_EVENT_QN]: async (event, tx) => {
164
164
  const progress = documentIngestProgressPayloadSchema.parse(event.payload);
165
+ const [existing] = await selectMany(tx, documentIngestProgressTable, { id: event.aggregateId, tenantId: event.tenantId });
166
+ // skip: reports can land out of order, progress only moves forward
167
+ if (existing !== undefined && existing.pagesDone > progress.pagesDone)
168
+ return;
165
169
  await upsertByPk(tx, documentIngestProgressTable, {
166
170
  id: event.aggregateId,
167
171
  tenantId: event.tenantId,
@@ -1,11 +1,15 @@
1
- import { transaction } from "@cosmicdrift/kumiko-framework/db";
1
+ import { selectMany, transaction } from "@cosmicdrift/kumiko-framework/db";
2
2
  import { append, getStreamVersion, VersionConflictError, } from "@cosmicdrift/kumiko-framework/event-store";
3
3
  import { runProjectionsForEvent } from "@cosmicdrift/kumiko-framework/pipeline";
4
4
  import { documentIngestAggregateId } from "./aggregate-id.js";
5
5
  import { DOCUMENT_INGEST_AGGREGATE_TYPE, DOCUMENT_INGEST_PROGRESS_EVENT_QN, documentIngestProgressPayloadSchema, } from "./events.js";
6
- // Parallel reports for one file race on the stream version; progress is idempotent and the newest
7
- // report wins, so a lost race re-reads the version and appends again.
8
- const MAX_VERSION_CONFLICT_ATTEMPTS = 3;
6
+ import { documentIngestProgressTable } from "./tables.js";
7
+ // Parallel reports for one file race on the stream version, so a lost race re-reads the version and
8
+ // appends again. The projection keeps the highest pagesDone, so landing order does not matter. A
9
+ // conflict means another report committed, so N parallel reports need at most N-1 retries; 10
10
+ // covers the parallelism one file sees. Every conflict is retried so each report lands its event;
11
+ // only when the attempts run out, a report whose progress is already stored is treated as done.
12
+ const MAX_VERSION_CONFLICT_ATTEMPTS = 10;
9
13
  // Low-level append() does not fire projections, so they run explicitly, in the same transaction as the append.
10
14
  export async function reportIngestProgress(deps, input) {
11
15
  const payload = documentIngestProgressPayloadSchema.parse(input);
@@ -31,9 +35,18 @@ export async function reportIngestProgress(deps, input) {
31
35
  catch (e) {
32
36
  if (!(e instanceof VersionConflictError))
33
37
  throw e;
34
- // skip: a conflict after the last attempt means a newer report already landed
35
- if (attempt >= MAX_VERSION_CONFLICT_ATTEMPTS)
38
+ if (attempt < MAX_VERSION_CONFLICT_ATTEMPTS)
39
+ continue;
40
+ if (await storedProgressCovers(deps, aggregateId, payload.pagesDone))
36
41
  return;
42
+ throw e;
37
43
  }
38
44
  }
39
45
  }
46
+ async function storedProgressCovers(deps, aggregateId, pagesDone) {
47
+ const rows = await selectMany(deps.db, documentIngestProgressTable, {
48
+ id: aggregateId,
49
+ tenantId: deps.tenantId,
50
+ });
51
+ return (rows[0]?.pagesDone ?? 0) >= pagesDone;
52
+ }
@@ -43,13 +43,13 @@ export declare function createSignatureRequestEntity(retention?: SignatureRetent
43
43
  readonly status: {
44
44
  readonly type: "select";
45
45
  readonly description?: string;
46
- readonly options: readonly ["open", "all-signed", "completed", "declined", "expired", "cancelled"];
46
+ readonly options: readonly ["open", "all-signed", "completed", "declined", "expired", "failed", "cancelled"];
47
47
  readonly required?: boolean;
48
48
  readonly sortable?: boolean;
49
49
  readonly sortNulls?: import("@cosmicdrift/kumiko-types/fields").SortNulls;
50
50
  readonly filterable?: boolean;
51
51
  readonly sensitive?: boolean;
52
- readonly default?: "all-signed" | "cancelled" | "completed" | "declined" | "expired" | "open" | undefined;
52
+ readonly default?: "all-signed" | "cancelled" | "completed" | "declined" | "expired" | "failed" | "open" | undefined;
53
53
  readonly access?: import("@cosmicdrift/kumiko-types/fields").FieldAccess;
54
54
  readonly display?: "radio" | "dropdown";
55
55
  readonly optionTones?: {
@@ -58,12 +58,13 @@ export declare function createSignatureRequestEntity(retention?: SignatureRetent
58
58
  readonly completed?: "accent" | "bad" | "critical" | "neutral" | "ok" | "warn" | undefined;
59
59
  readonly declined?: "accent" | "bad" | "critical" | "neutral" | "ok" | "warn" | undefined;
60
60
  readonly expired?: "accent" | "bad" | "critical" | "neutral" | "ok" | "warn" | undefined;
61
+ readonly failed?: "accent" | "bad" | "critical" | "neutral" | "ok" | "warn" | undefined;
61
62
  readonly open?: "accent" | "bad" | "critical" | "neutral" | "ok" | "warn" | undefined;
62
63
  } | undefined;
63
64
  readonly optionsQuery?: string;
64
65
  readonly optionsQueryPayload?: import("@cosmicdrift/kumiko-types/fields").OptionsQueryPayload;
65
66
  readonly optionsAvailabilityQuery?: string;
66
- readonly conditionalOptions?: readonly import("@cosmicdrift/kumiko-types/fields").SelectConditionalOptions<"all-signed" | "cancelled" | "completed" | "declined" | "expired" | "open">[] | undefined;
67
+ readonly conditionalOptions?: readonly import("@cosmicdrift/kumiko-types/fields").SelectConditionalOptions<"all-signed" | "cancelled" | "completed" | "declined" | "expired" | "failed" | "open">[] | undefined;
67
68
  } & import("@cosmicdrift/kumiko-types/fields").ResolvedPiiFlags & import("@cosmicdrift/kumiko-types/fields").FieldStateConditions & {
68
69
  required: true;
69
70
  };
@@ -292,13 +293,13 @@ export declare const signatureRequestEntity: import("@cosmicdrift/kumiko-types/f
292
293
  readonly status: {
293
294
  readonly type: "select";
294
295
  readonly description?: string;
295
- readonly options: readonly ["open", "all-signed", "completed", "declined", "expired", "cancelled"];
296
+ readonly options: readonly ["open", "all-signed", "completed", "declined", "expired", "failed", "cancelled"];
296
297
  readonly required?: boolean;
297
298
  readonly sortable?: boolean;
298
299
  readonly sortNulls?: import("@cosmicdrift/kumiko-types/fields").SortNulls;
299
300
  readonly filterable?: boolean;
300
301
  readonly sensitive?: boolean;
301
- readonly default?: "all-signed" | "cancelled" | "completed" | "declined" | "expired" | "open" | undefined;
302
+ readonly default?: "all-signed" | "cancelled" | "completed" | "declined" | "expired" | "failed" | "open" | undefined;
302
303
  readonly access?: import("@cosmicdrift/kumiko-types/fields").FieldAccess;
303
304
  readonly display?: "radio" | "dropdown";
304
305
  readonly optionTones?: {
@@ -307,12 +308,13 @@ export declare const signatureRequestEntity: import("@cosmicdrift/kumiko-types/f
307
308
  readonly completed?: "accent" | "bad" | "critical" | "neutral" | "ok" | "warn" | undefined;
308
309
  readonly declined?: "accent" | "bad" | "critical" | "neutral" | "ok" | "warn" | undefined;
309
310
  readonly expired?: "accent" | "bad" | "critical" | "neutral" | "ok" | "warn" | undefined;
311
+ readonly failed?: "accent" | "bad" | "critical" | "neutral" | "ok" | "warn" | undefined;
310
312
  readonly open?: "accent" | "bad" | "critical" | "neutral" | "ok" | "warn" | undefined;
311
313
  } | undefined;
312
314
  readonly optionsQuery?: string;
313
315
  readonly optionsQueryPayload?: import("@cosmicdrift/kumiko-types/fields").OptionsQueryPayload;
314
316
  readonly optionsAvailabilityQuery?: string;
315
- readonly conditionalOptions?: readonly import("@cosmicdrift/kumiko-types/fields").SelectConditionalOptions<"all-signed" | "cancelled" | "completed" | "declined" | "expired" | "open">[] | undefined;
317
+ readonly conditionalOptions?: readonly import("@cosmicdrift/kumiko-types/fields").SelectConditionalOptions<"all-signed" | "cancelled" | "completed" | "declined" | "expired" | "failed" | "open">[] | undefined;
316
318
  } & import("@cosmicdrift/kumiko-types/fields").ResolvedPiiFlags & import("@cosmicdrift/kumiko-types/fields").FieldStateConditions & {
317
319
  required: true;
318
320
  };
@@ -7,6 +7,7 @@ const REQUEST_STATUS_OPTIONS = [
7
7
  SIGNATURE_REQUEST_STATUS.Completed,
8
8
  SIGNATURE_REQUEST_STATUS.Declined,
9
9
  SIGNATURE_REQUEST_STATUS.Expired,
10
+ SIGNATURE_REQUEST_STATUS.Failed,
10
11
  SIGNATURE_REQUEST_STATUS.Cancelled,
11
12
  ];
12
13
  const SIGNER_STATUS_OPTIONS = [
@@ -24,7 +25,7 @@ const SIGNER_PERSONAL = { personal: "self", find: "none" };
24
25
  export function createSignatureRequestEntity(retention = { keepFor: DEFAULT_SIGNATURE_RETENTION_KEEP_FOR }) {
25
26
  return createEntity({
26
27
  table: "read_signature_requests",
27
- description: "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.",
28
+ description: "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.",
28
29
  retention: { keepFor: retention.keepFor, strategy: "hardDelete", reference: "createdAt" },
29
30
  fields: {
30
31
  documentFileId: createTextField({
@@ -71,6 +72,7 @@ export function createSignatureRequestEntity(retention = { keepFor: DEFAULT_SIGN
71
72
  [SIGNATURE_REQUEST_STATUS.Completed]: "ok",
72
73
  [SIGNATURE_REQUEST_STATUS.Declined]: "bad",
73
74
  [SIGNATURE_REQUEST_STATUS.Expired]: "neutral",
75
+ [SIGNATURE_REQUEST_STATUS.Failed]: "bad",
74
76
  [SIGNATURE_REQUEST_STATUS.Cancelled]: "neutral",
75
77
  },
76
78
  }),
@@ -3,7 +3,7 @@ import { createSignatureRequestEntity, createSignatureSignerEntity } from "./ent
3
3
  import { createAnonymousLinkHandlers } from "./handlers/anonymous.write.js";
4
4
  import { createCancelHandler } from "./handlers/cancel.write.js";
5
5
  import { createIssueLinkHandler } from "./handlers/issue-link.write.js";
6
- import { expireHandler, finishHandler, reconcileHandler } from "./handlers/lifecycle.write.js";
6
+ import { expireHandler, failHandler, finishHandler, reconcileHandler, } from "./handlers/lifecycle.write.js";
7
7
  import { createLinkInternalHandlers } from "./handlers/link-internal.write.js";
8
8
  import { createRequestHandler } from "./handlers/request.write.js";
9
9
  import { createRevokeLinkHandler } from "./handlers/revoke-link.write.js";
@@ -11,7 +11,7 @@ import { createSignInPersonHandler } from "./handlers/sign-in-person.write.js";
11
11
  import { SIGNATURE_I18N } from "./i18n.js";
12
12
  import { DEFAULT_SIGNATURE_ACCESS } from "./lib.js";
13
13
  import { LINK_RATE_LIMIT } from "./options.js";
14
- import { SignatureCompletedEventSchema, SignatureDeclinedEventSchema, SignatureExpiredEventSchema, } from "./payloads.js";
14
+ import { SignatureCompletedEventSchema, SignatureDeclinedEventSchema, SignatureExpiredEventSchema, SignatureFailedEventSchema, } from "./payloads.js";
15
15
  import { createSignatureDetailScreen, createSignatureListScreen } from "./screens.js";
16
16
  import { scopeRequestDetail, scopeRequestList, scopeSignerList } from "./subject-queries.js";
17
17
  import { createSubjectScope } from "./subject-scope.js";
@@ -19,6 +19,9 @@ import { sweepSignatureRequests } from "./sweep.js";
19
19
  import { signatureDeleteHook, signatureExportHook } from "./user-data.js";
20
20
  import { SIGNATURE_FEATURE, SIGNATURE_REQUEST_ENTITY, SIGNATURE_SIGNER_ENTITY, } from "./web/constants.js";
21
21
  export function createSignatureFeature(opts) {
22
+ if (opts.authorizeSubject !== undefined && opts.linkSecret === "") {
23
+ throw new Error("authorizeSubject needs a non-empty linkSecret: it also seals the list cursor");
24
+ }
22
25
  const signedInAccess = opts.access ?? DEFAULT_SIGNATURE_ACCESS;
23
26
  const scope = createSubjectScope(opts);
24
27
  const requestEntity = createSignatureRequestEntity(opts.retention);
@@ -26,7 +29,7 @@ export function createSignatureFeature(opts) {
26
29
  const anonymous = createAnonymousLinkHandlers(LINK_RATE_LIMIT);
27
30
  const link = createLinkInternalHandlers(opts.linkSecret);
28
31
  return defineFeature(SIGNATURE_FEATURE, (r) => {
29
- r.describe("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.");
32
+ r.describe("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.");
30
33
  r.uiHints({ displayLabel: "Signatures", category: "data", recommended: false });
31
34
  r.requires({ features: ["files", "user-data-rights"] });
32
35
  r.adoptsBundledLists();
@@ -42,6 +45,9 @@ export function createSignatureFeature(opts) {
42
45
  r.defineEvent("expired", SignatureExpiredEventSchema, {
43
46
  piiFields: "none",
44
47
  });
48
+ r.defineEvent("failed", SignatureFailedEventSchema, {
49
+ piiFields: "none",
50
+ });
45
51
  r.writeHandler(createRequestHandler(signedInAccess, scope));
46
52
  r.writeHandler(createSignInPersonHandler(signedInAccess, scope));
47
53
  r.writeHandler(createIssueLinkHandler(signedInAccess, scope, opts));
@@ -55,6 +61,7 @@ export function createSignatureFeature(opts) {
55
61
  r.writeHandler(link.linkDecline);
56
62
  r.writeHandler(finishHandler);
57
63
  r.writeHandler(expireHandler);
64
+ r.writeHandler(failHandler);
58
65
  r.writeHandler(reconcileHandler);
59
66
  const requestList = defineEntityListHandler(SIGNATURE_REQUEST_ENTITY, requestEntity, {
60
67
  access: signedInAccess,
@@ -69,7 +76,7 @@ export function createSignatureFeature(opts) {
69
76
  agent: { expose: false },
70
77
  description: "Lists the signers of requests with their status and way of signing; carries the signers' personal data.",
71
78
  });
72
- r.queryHandler(scopeRequestList(requestList, scope));
79
+ r.queryHandler(scopeRequestList(requestList, scope, opts.linkSecret));
73
80
  r.queryHandler(scopeRequestDetail(requestDetail, scope));
74
81
  r.queryHandler(scopeSignerList(signerList, scope));
75
82
  r.useExtension(EXT_USER_DATA, SIGNATURE_SIGNER_ENTITY, {
@@ -9,6 +9,15 @@ export declare const expireHandler: import("@cosmicdrift/kumiko-types/define-han
9
9
  }, import("zod/v4/core").$strip>, {
10
10
  expired: boolean;
11
11
  }, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
12
+ export declare const failHandler: import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"fail", import("zod").ZodObject<{
13
+ requestId: import("zod").ZodUUID;
14
+ reason: import("zod").ZodEnum<{
15
+ "document-changed": "document-changed";
16
+ "signature-image-missing": "signature-image-missing";
17
+ }>;
18
+ }, import("zod/v4/core").$strip>, {
19
+ failed: boolean;
20
+ }, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
12
21
  export declare const reconcileHandler: import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"reconcile", import("zod").ZodObject<{
13
22
  requestId: import("zod").ZodUUID;
14
23
  }, import("zod/v4/core").$strip>, {
@@ -1,7 +1,7 @@
1
1
  import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { requestExecutor } from "../entity.js";
3
3
  import { advanceIfAllSigned, appendOutcomeEvent, internalAccess, isPastInstant, listSigners, setRequestStatus, } from "../lib.js";
4
- import { FinishSchema, RequestIdSchema } from "../payloads.js";
4
+ import { FailSchema, FinishSchema, RequestIdSchema } from "../payloads.js";
5
5
  import { SIGNATURE_REQUEST_STATUS, SignatureEvents } from "../web/constants.js";
6
6
  // The writes of the sweep job. They run as handlers because a job may only append its own
7
7
  // events through ctx.events, and every transition here must also hold the "exactly once" precondition.
@@ -55,6 +55,28 @@ export const expireHandler = defineWriteHandler({
55
55
  return { isSuccess: true, data: { expired: true } };
56
56
  },
57
57
  });
58
+ export const failHandler = defineWriteHandler({
59
+ name: "fail",
60
+ schema: FailSchema,
61
+ access: internalAccess,
62
+ agent: { expose: false },
63
+ description: "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.",
64
+ handler: async (event, ctx) => {
65
+ const request = await requestExecutor.detail({ id: event.payload.requestId }, event.user, ctx.db);
66
+ if (request === null)
67
+ return { isSuccess: true, data: { failed: false } };
68
+ const moved = await setRequestStatus(ctx, event.user, request.id, SIGNATURE_REQUEST_STATUS.AllSigned, { status: SIGNATURE_REQUEST_STATUS.Failed });
69
+ if (!moved.isSuccess)
70
+ return { isSuccess: true, data: { failed: false } };
71
+ await appendOutcomeEvent(ctx, SignatureEvents.failed, {
72
+ requestId: request.id,
73
+ subjectType: request.subjectType,
74
+ subjectId: request.subjectId,
75
+ reason: event.payload.reason,
76
+ });
77
+ return { isSuccess: true, data: { failed: true } };
78
+ },
79
+ });
58
80
  // Two last signers committing at the same moment can each still see the other as unsigned; the
59
81
  // sweep repeats the check so such a request cannot stay open for good.
60
82
  export const reconcileHandler = defineWriteHandler({
@@ -15,6 +15,6 @@ export declare function createRequestHandler(access: AccessRule, scope: SubjectS
15
15
  name: import("zod").ZodString;
16
16
  role: import("zod").ZodOptional<import("zod").ZodString>;
17
17
  contactId: import("zod").ZodOptional<import("zod").ZodString>;
18
- email: import("zod").ZodOptional<import("zod").ZodString>;
18
+ email: import("zod").ZodOptional<import("zod").ZodPipe<import("zod").ZodString, import("zod").ZodEmail>>;
19
19
  }, import("zod/v4/core").$strip>>;
20
20
  }, import("zod/v4/core").$strip>, RequestSignatureData, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
@@ -45,5 +45,6 @@ export const SIGNATURE_I18N = {
45
45
  [`${REQUEST}:status:option:completed`]: { en: "Completed", de: "Abgeschlossen" },
46
46
  [`${REQUEST}:status:option:declined`]: { en: "Declined", de: "Abgelehnt" },
47
47
  [`${REQUEST}:status:option:expired`]: { en: "Expired", de: "Abgelaufen" },
48
+ [`${REQUEST}:status:option:failed`]: { en: "Failed", de: "Fehlgeschlagen" },
48
49
  [`${REQUEST}:status:option:cancelled`]: { en: "Cancelled", de: "Abgebrochen" },
49
50
  };
@@ -0,0 +1,3 @@
1
+ import type { SessionUser } from "@cosmicdrift/kumiko-framework/engine";
2
+ export declare function sealListCursor(baseCursor: string, user: SessionUser, secret: string): Promise<string>;
3
+ export declare function openListCursor(sealed: string, user: SessionUser, secret: string): Promise<string | null>;
@@ -0,0 +1,44 @@
1
+ import { createHmac } from "node:crypto";
2
+ import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
3
+ import { CompactEncrypt, compactDecrypt } from "jose";
4
+ // Domain separation: the same secret also keys the link HMAC.
5
+ const CURSOR_KEY_LABEL = "signature-list-cursor";
6
+ const encoder = new TextEncoder();
7
+ const decoder = new TextDecoder();
8
+ function isSealedCursorPayload(value) {
9
+ return (isPlainObject(value) &&
10
+ typeof value["c"] === "string" &&
11
+ typeof value["u"] === "string" &&
12
+ typeof value["t"] === "string");
13
+ }
14
+ function cursorKey(secret) {
15
+ return new Uint8Array(createHmac("sha256", secret).update(CURSOR_KEY_LABEL).digest());
16
+ }
17
+ export async function sealListCursor(baseCursor, user, secret) {
18
+ const payload = {
19
+ c: baseCursor,
20
+ u: String(user.id),
21
+ t: String(user.tenantId),
22
+ };
23
+ return new CompactEncrypt(encoder.encode(JSON.stringify(payload)))
24
+ .setProtectedHeader({ alg: "dir", enc: "A256GCM" })
25
+ .encrypt(cursorKey(secret));
26
+ }
27
+ export async function openListCursor(sealed, user, secret) {
28
+ try {
29
+ // Allowlist: a foreign header such as PBES2 would cost PBKDF2 rounds per request.
30
+ const { plaintext } = await compactDecrypt(sealed, cursorKey(secret), {
31
+ keyManagementAlgorithms: ["dir"],
32
+ contentEncryptionAlgorithms: ["A256GCM"],
33
+ });
34
+ const payload = JSON.parse(decoder.decode(plaintext));
35
+ if (!isSealedCursorPayload(payload))
36
+ return null;
37
+ if (payload.u !== String(user.id) || payload.t !== String(user.tenantId))
38
+ return null;
39
+ return payload.c;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
@@ -26,13 +26,13 @@ export type SignatureOptions = {
26
26
  readonly renderHtmlToPdf: RenderSignatureHtmlToPdf;
27
27
  /** HMAC secret of the signing links. Without it every link is rejected. */
28
28
  readonly linkSecret: string;
29
- /** Sends a freshly issued link to the signer, e.g. by mail. A throw fails issue-link and leaves no link sent. */
29
+ /** 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. */
30
30
  readonly deliverLink: DeliverSignatureLink;
31
31
  /** URL of the app's signature page; the token is appended as `#<token>`. */
32
32
  readonly signaturePageUrl: string;
33
33
  /** 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. */
34
34
  readonly access?: AccessRule;
35
- /** 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. */
35
+ /** 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. */
36
36
  readonly authorizeSubject?: AuthorizeSignatureSubject;
37
37
  /** Roles that skip `authorizeSubject`, e.g. admins. */
38
38
  readonly unscopedRoles?: readonly string[];
@@ -11,7 +11,7 @@ export declare const RequestSignatureSchema: z.ZodObject<{
11
11
  name: z.ZodString;
12
12
  role: z.ZodOptional<z.ZodString>;
13
13
  contactId: z.ZodOptional<z.ZodString>;
14
- email: z.ZodOptional<z.ZodString>;
14
+ email: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodEmail>>;
15
15
  }, z.core.$strip>>;
16
16
  }, z.core.$strip>;
17
17
  export type RequestSignatureInput = z.infer<typeof RequestSignatureSchema>;
@@ -36,6 +36,13 @@ export declare const DeclineByLinkSchema: z.ZodObject<{
36
36
  token: z.ZodString;
37
37
  reason: z.ZodOptional<z.ZodString>;
38
38
  }, z.core.$strip>;
39
+ export declare const FailSchema: z.ZodObject<{
40
+ requestId: z.ZodUUID;
41
+ reason: z.ZodEnum<{
42
+ "document-changed": "document-changed";
43
+ "signature-image-missing": "signature-image-missing";
44
+ }>;
45
+ }, z.core.$strip>;
39
46
  export declare const FinishSchema: z.ZodObject<{
40
47
  requestId: z.ZodUUID;
41
48
  completedFileId: z.ZodUUID;
@@ -58,3 +65,12 @@ export declare const SignatureExpiredEventSchema: z.ZodObject<{
58
65
  subjectType: z.ZodString;
59
66
  subjectId: z.ZodString;
60
67
  }, z.core.$strip>;
68
+ export declare const SignatureFailedEventSchema: z.ZodObject<{
69
+ requestId: z.ZodString;
70
+ subjectType: z.ZodString;
71
+ subjectId: z.ZodString;
72
+ reason: z.ZodEnum<{
73
+ "document-changed": "document-changed";
74
+ "signature-image-missing": "signature-image-missing";
75
+ }>;
76
+ }, z.core.$strip>;
@@ -1,6 +1,6 @@
1
1
  import * as z from "zod";
2
2
  import { MAX_SIGNATURE_PNG_BYTES } from "./png.js";
3
- import { SIGNATURE_LEVEL } from "./web/constants.js";
3
+ import { SIGNATURE_FAILURE_REASON, SIGNATURE_LEVEL } from "./web/constants.js";
4
4
  export const MAX_SIGNERS_PER_REQUEST = 20;
5
5
  const MAX_VALIDITY_DAYS = 365;
6
6
  // Base64 inflates by 4/3; the png checks apply to the decoded bytes.
@@ -10,7 +10,7 @@ const SignerInputSchema = z.object({
10
10
  name: z.string().trim().min(1).max(200),
11
11
  role: z.string().trim().min(1).max(100).optional(),
12
12
  contactId: z.string().min(1).max(64).optional(),
13
- email: z.string().trim().min(3).max(320).optional(),
13
+ email: z.string().trim().max(320).pipe(z.email()).optional(),
14
14
  });
15
15
  export const RequestSignatureSchema = z.object({
16
16
  documentFileId: z.uuid(),
@@ -35,6 +35,11 @@ export const DeclineByLinkSchema = z.object({
35
35
  token: TokenPayload,
36
36
  reason: z.string().trim().min(1).max(1000).optional(),
37
37
  });
38
+ const FailureReasonSchema = z.enum([
39
+ SIGNATURE_FAILURE_REASON.DocumentChanged,
40
+ SIGNATURE_FAILURE_REASON.SignatureImageMissing,
41
+ ]);
42
+ export const FailSchema = z.object({ requestId: z.uuid(), reason: FailureReasonSchema });
38
43
  export const FinishSchema = z.object({ requestId: z.uuid(), completedFileId: z.uuid() });
39
44
  const OutcomeBase = {
40
45
  requestId: z.string().min(1),
@@ -51,3 +56,7 @@ export const SignatureDeclinedEventSchema = z.object({
51
56
  signerId: z.string().min(1),
52
57
  });
53
58
  export const SignatureExpiredEventSchema = z.object(OutcomeBase);
59
+ export const SignatureFailedEventSchema = z.object({
60
+ ...OutcomeBase,
61
+ reason: FailureReasonSchema,
62
+ });
@@ -105,12 +105,32 @@ function unfilterRows(raw, header) {
105
105
  return true;
106
106
  }
107
107
  function countInkPixels(raw, header) {
108
- const stride = header.width * header.bytesPerPixel + 1;
108
+ const bytesPerPixel = header.bytesPerPixel;
109
+ const stride = header.width * bytesPerPixel + 1;
110
+ const pixelStart = (row, column) => row * stride + 1 + column * bytesPerPixel;
111
+ const background = pixelStart(0, 0);
112
+ const alphaOf = (start) => raw[start + bytesPerPixel - 1] ?? 0;
113
+ const colorMatchesBackground = (start) => {
114
+ for (let i = 0; i < bytesPerPixel; i++) {
115
+ if (raw[start + i] !== raw[background + i])
116
+ return false;
117
+ }
118
+ return true;
119
+ };
120
+ // Only four identical, opaque corners mean a solid background; a single opaque pixel could be a stroke.
121
+ const corners = [
122
+ background,
123
+ pixelStart(0, header.width - 1),
124
+ pixelStart(header.height - 1, 0),
125
+ pixelStart(header.height - 1, header.width - 1),
126
+ ];
127
+ const hasSolidBackground = corners.every((corner) => alphaOf(corner) > 0 && colorMatchesBackground(corner));
109
128
  let ink = 0;
110
129
  for (let row = 0; row < header.height; row++) {
111
130
  for (let column = 0; column < header.width; column++) {
112
- const alphaIndex = row * stride + 1 + column * header.bytesPerPixel + header.bytesPerPixel - 1;
113
- if ((raw[alphaIndex] ?? 0) > 0)
131
+ const start = pixelStart(row, column);
132
+ const isInk = alphaOf(start) > 0 && (!hasSolidBackground || !colorMatchesBackground(start));
133
+ if (isInk)
114
134
  ink++;
115
135
  }
116
136
  }
@@ -1,5 +1,5 @@
1
1
  import { type QueryHandlerDef } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import type { SubjectScope } from "./subject-scope.ts";
3
- export declare function scopeRequestList(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef;
3
+ export declare function scopeRequestList(base: QueryHandlerDef, scope: SubjectScope, cursorSecret: string): QueryHandlerDef;
4
4
  export declare function scopeRequestDetail(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef;
5
5
  export declare function scopeSignerList(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef;