@cosmicdrift/kumiko-bundled-features 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 (57) 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/helpdesk/screens.js +5 -1
  12. package/dist/signature/entity.d.ts +8 -6
  13. package/dist/signature/entity.js +3 -1
  14. package/dist/signature/feature.js +27 -14
  15. package/dist/signature/handlers/cancel.write.d.ts +2 -1
  16. package/dist/signature/handlers/cancel.write.js +10 -3
  17. package/dist/signature/handlers/issue-link.write.d.ts +2 -1
  18. package/dist/signature/handlers/issue-link.write.js +4 -1
  19. package/dist/signature/handlers/lifecycle.write.d.ts +9 -0
  20. package/dist/signature/handlers/lifecycle.write.js +23 -1
  21. package/dist/signature/handlers/request.write.d.ts +3 -2
  22. package/dist/signature/handlers/request.write.js +23 -4
  23. package/dist/signature/handlers/revoke-link.write.d.ts +2 -1
  24. package/dist/signature/handlers/revoke-link.write.js +10 -1
  25. package/dist/signature/handlers/sign-in-person.write.d.ts +2 -1
  26. package/dist/signature/handlers/sign-in-person.write.js +4 -1
  27. package/dist/signature/i18n.js +1 -0
  28. package/dist/signature/index.d.ts +1 -1
  29. package/dist/signature/list-cursor-seal.d.ts +3 -0
  30. package/dist/signature/list-cursor-seal.js +44 -0
  31. package/dist/signature/options.d.ts +10 -1
  32. package/dist/signature/payloads.d.ts +17 -1
  33. package/dist/signature/payloads.js +11 -2
  34. package/dist/signature/png.js +23 -3
  35. package/dist/signature/screens.js +2 -0
  36. package/dist/signature/static-sign.d.ts +2 -0
  37. package/dist/signature/static-sign.js +2 -1
  38. package/dist/signature/subject-queries.d.ts +5 -0
  39. package/dist/signature/subject-queries.js +135 -0
  40. package/dist/signature/subject-scope.d.ts +11 -0
  41. package/dist/signature/subject-scope.js +20 -0
  42. package/dist/signature/sweep.js +26 -9
  43. package/dist/signature/web/constants.d.ts +9 -0
  44. package/dist/signature/web/constants.js +8 -0
  45. package/dist/subscription-stripe/plugin-methods.js +2 -0
  46. package/dist/subscription-stripe/verify-webhook.js +17 -16
  47. package/dist/tenant-inactivity/handlers/keep-account.write.js +5 -2
  48. package/dist/tenant-lifecycle/run-tenant-destroy.js +65 -33
  49. package/package.json +11 -11
  50. package/src/agent-tools/changes.json +6 -0
  51. package/src/cap-counter/changes.json +6 -0
  52. package/src/channel-whatsapp/changes.json +1 -1
  53. package/src/document-ingest-foundation/changes.json +6 -0
  54. package/src/signature/changes.json +25 -0
  55. package/src/subscription-paddle/changes.json +1 -1
  56. package/src/subscription-stripe/changes.json +6 -0
  57. 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
+ }
@@ -286,7 +286,11 @@ function createRequestDetailScreen(opts, settings) {
286
286
  field: "authorName",
287
287
  label: `${HELPDESK_FEATURE}:entity:helpdesk-reply:field:authorName`,
288
288
  },
289
- { field: "message", label: `${HELPDESK_FEATURE}:entity:helpdesk-reply:field:message` },
289
+ {
290
+ field: "message",
291
+ label: `${HELPDESK_FEATURE}:entity:helpdesk-reply:field:message`,
292
+ multiline: true,
293
+ },
290
294
  ],
291
295
  },
292
296
  {
@@ -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,19 +11,25 @@ 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
+ import { scopeRequestDetail, scopeRequestList, scopeSignerList } from "./subject-queries.js";
17
+ import { createSubjectScope } from "./subject-scope.js";
16
18
  import { sweepSignatureRequests } from "./sweep.js";
17
19
  import { signatureDeleteHook, signatureExportHook } from "./user-data.js";
18
20
  import { SIGNATURE_FEATURE, SIGNATURE_REQUEST_ENTITY, SIGNATURE_SIGNER_ENTITY, } from "./web/constants.js";
19
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
+ }
20
25
  const signedInAccess = opts.access ?? DEFAULT_SIGNATURE_ACCESS;
26
+ const scope = createSubjectScope(opts);
21
27
  const requestEntity = createSignatureRequestEntity(opts.retention);
22
28
  const signerEntity = createSignatureSignerEntity(opts.retention);
23
29
  const anonymous = createAnonymousLinkHandlers(LINK_RATE_LIMIT);
24
30
  const link = createLinkInternalHandlers(opts.linkSecret);
25
31
  return defineFeature(SIGNATURE_FEATURE, (r) => {
26
- 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.");
27
33
  r.uiHints({ displayLabel: "Signatures", category: "data", recommended: false });
28
34
  r.requires({ features: ["files", "user-data-rights"] });
29
35
  r.adoptsBundledLists();
@@ -39,11 +45,14 @@ export function createSignatureFeature(opts) {
39
45
  r.defineEvent("expired", SignatureExpiredEventSchema, {
40
46
  piiFields: "none",
41
47
  });
42
- r.writeHandler(createRequestHandler(signedInAccess));
43
- r.writeHandler(createSignInPersonHandler(signedInAccess));
44
- r.writeHandler(createIssueLinkHandler(signedInAccess, opts));
45
- r.writeHandler(createRevokeLinkHandler(signedInAccess));
46
- r.writeHandler(createCancelHandler(signedInAccess));
48
+ r.defineEvent("failed", SignatureFailedEventSchema, {
49
+ piiFields: "none",
50
+ });
51
+ r.writeHandler(createRequestHandler(signedInAccess, scope));
52
+ r.writeHandler(createSignInPersonHandler(signedInAccess, scope));
53
+ r.writeHandler(createIssueLinkHandler(signedInAccess, scope, opts));
54
+ r.writeHandler(createRevokeLinkHandler(signedInAccess, scope));
55
+ r.writeHandler(createCancelHandler(signedInAccess, scope));
47
56
  r.writeHandler(anonymous.openByLink);
48
57
  r.writeHandler(anonymous.signByLink);
49
58
  r.writeHandler(anonymous.declineByLink);
@@ -52,20 +61,24 @@ export function createSignatureFeature(opts) {
52
61
  r.writeHandler(link.linkDecline);
53
62
  r.writeHandler(finishHandler);
54
63
  r.writeHandler(expireHandler);
64
+ r.writeHandler(failHandler);
55
65
  r.writeHandler(reconcileHandler);
56
- r.queryHandler(defineEntityListHandler(SIGNATURE_REQUEST_ENTITY, requestEntity, {
66
+ const requestList = defineEntityListHandler(SIGNATURE_REQUEST_ENTITY, requestEntity, {
57
67
  access: signedInAccess,
58
68
  description: "Lists signature requests with status, deadline and the object they belong to; paging, search over the title and sorting.",
59
- }));
60
- r.queryHandler(defineEntityDetailHandler(SIGNATURE_REQUEST_ENTITY, requestEntity, {
69
+ });
70
+ const requestDetail = defineEntityDetailHandler(SIGNATURE_REQUEST_ENTITY, requestEntity, {
61
71
  access: signedInAccess,
62
72
  description: "Returns one signature request.",
63
- }));
64
- r.queryHandler(defineEntityListHandler(SIGNATURE_SIGNER_ENTITY, signerEntity, {
73
+ });
74
+ const signerList = defineEntityListHandler(SIGNATURE_SIGNER_ENTITY, signerEntity, {
65
75
  access: signedInAccess,
66
76
  agent: { expose: false },
67
77
  description: "Lists the signers of requests with their status and way of signing; carries the signers' personal data.",
68
- }));
78
+ });
79
+ r.queryHandler(scopeRequestList(requestList, scope, opts.linkSecret));
80
+ r.queryHandler(scopeRequestDetail(requestDetail, scope));
81
+ r.queryHandler(scopeSignerList(signerList, scope));
69
82
  r.useExtension(EXT_USER_DATA, SIGNATURE_SIGNER_ENTITY, {
70
83
  export: signatureExportHook,
71
84
  delete: signatureDeleteHook,
@@ -1,5 +1,6 @@
1
1
  import { type AccessRule } from "@cosmicdrift/kumiko-framework/engine";
2
- export declare function createCancelHandler(access: AccessRule): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"cancel", import("zod").ZodObject<{
2
+ import type { SubjectScope } from "../subject-scope.ts";
3
+ export declare function createCancelHandler(access: AccessRule, scope: SubjectScope): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"cancel", import("zod").ZodObject<{
3
4
  requestId: import("zod").ZodUUID;
4
5
  }, import("zod/v4/core").$strip>, {
5
6
  readonly cancelled: true;
@@ -1,11 +1,12 @@
1
1
  import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
- import { signerExecutor } from "../entity.js";
2
+ import { NotFoundError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import { requestExecutor, signerExecutor } from "../entity.js";
3
4
  import { isUnsignedSigner, listSigners, setRequestStatus } from "../lib.js";
4
5
  import { RequestIdSchema } from "../payloads.js";
5
- import { SIGNATURE_REQUEST_STATUS } from "../web/constants.js";
6
+ import { SIGNATURE_REQUEST_ENTITY, SIGNATURE_REQUEST_STATUS } from "../web/constants.js";
6
7
  // Cancelling moves the request out of `open`, which already makes every link of it fail; the
7
8
  // anchors are cleared as well so no token verifies against a cancelled request.
8
- export function createCancelHandler(access) {
9
+ export function createCancelHandler(access, scope) {
9
10
  return defineWriteHandler({
10
11
  name: "cancel",
11
12
  schema: RequestIdSchema,
@@ -14,6 +15,12 @@ export function createCancelHandler(access) {
14
15
  description: "Cancels an open signature request; all its signing links stop working. Signatures already given stay on record.",
15
16
  handler: async (event, ctx) => {
16
17
  const user = event.user;
18
+ if (scope.isScoped(user)) {
19
+ const request = await requestExecutor.detail({ id: event.payload.requestId }, user, ctx.db);
20
+ if (request === null || !(await scope.allowsRequest(ctx, user, request))) {
21
+ return writeFailure(new NotFoundError(SIGNATURE_REQUEST_ENTITY, event.payload.requestId));
22
+ }
23
+ }
17
24
  const moved = await setRequestStatus(ctx, user, event.payload.requestId, SIGNATURE_REQUEST_STATUS.Open, { status: SIGNATURE_REQUEST_STATUS.Cancelled });
18
25
  if (!moved.isSuccess)
19
26
  return moved;
@@ -1,9 +1,10 @@
1
1
  import { type AccessRule } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import type { SignatureOptions } from "../options.ts";
3
+ import type { SubjectScope } from "../subject-scope.ts";
3
4
  export type IssueLinkData = {
4
5
  readonly signerId: string;
5
6
  readonly linkSentAt: string;
6
7
  };
7
- export declare function createIssueLinkHandler(access: AccessRule, opts: Pick<SignatureOptions, "linkSecret" | "deliverLink" | "signaturePageUrl">): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"issue-link", import("zod").ZodObject<{
8
+ export declare function createIssueLinkHandler(access: AccessRule, scope: SubjectScope, opts: Pick<SignatureOptions, "linkSecret" | "deliverLink" | "signaturePageUrl">): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"issue-link", import("zod").ZodObject<{
8
9
  signerId: import("zod").ZodUUID;
9
10
  }, import("zod/v4/core").$strip>, IssueLinkData, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
@@ -6,7 +6,7 @@ import { signSignatureLinkToken } from "../grant.js";
6
6
  import { isOpenRequest, isUnsignedSigner, loadRequestOfSigner } from "../lib.js";
7
7
  import { SignerIdSchema } from "../payloads.js";
8
8
  // A new link replaces the previous one: the anchor moves on, so the old token stops verifying.
9
- export function createIssueLinkHandler(access, opts) {
9
+ export function createIssueLinkHandler(access, scope, opts) {
10
10
  return defineWriteHandler({
11
11
  name: "issue-link",
12
12
  schema: SignerIdSchema,
@@ -19,6 +19,9 @@ export function createIssueLinkHandler(access, opts) {
19
19
  if (signer === null)
20
20
  return writeFailure(new NotFoundError("signer", event.payload.signerId));
21
21
  const request = await loadRequestOfSigner(ctx, user, signer);
22
+ if (request !== null && !(await scope.allowsRequest(ctx, user, request))) {
23
+ return writeFailure(new NotFoundError("signer", event.payload.signerId));
24
+ }
22
25
  const now = ctx.tz.now();
23
26
  if (request === null || !isOpenRequest(request, now) || !isUnsignedSigner(signer)) {
24
27
  return writeFailure(new UnprocessableError("link_not_possible"));
@@ -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({
@@ -1,9 +1,10 @@
1
1
  import { type AccessRule } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { SubjectScope } from "../subject-scope.ts";
2
3
  export type RequestSignatureData = {
3
4
  readonly requestId: string;
4
5
  readonly signerIds: readonly string[];
5
6
  };
6
- export declare function createRequestHandler(access: AccessRule): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"request", import("zod").ZodObject<{
7
+ export declare function createRequestHandler(access: AccessRule, scope: SubjectScope): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"request", import("zod").ZodObject<{
7
8
  documentFileId: import("zod").ZodUUID;
8
9
  title: import("zod").ZodString;
9
10
  level: import("zod").ZodDefault<import("zod").ZodLiteral<"simple">>;
@@ -14,6 +15,6 @@ export declare function createRequestHandler(access: AccessRule): import("@cosmi
14
15
  name: import("zod").ZodString;
15
16
  role: import("zod").ZodOptional<import("zod").ZodString>;
16
17
  contactId: import("zod").ZodOptional<import("zod").ZodString>;
17
- email: import("zod").ZodOptional<import("zod").ZodString>;
18
+ email: import("zod").ZodOptional<import("zod").ZodPipe<import("zod").ZodString, import("zod").ZodEmail>>;
18
19
  }, import("zod/v4/core").$strip>>;
19
20
  }, import("zod/v4/core").$strip>, RequestSignatureData, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
@@ -1,10 +1,12 @@
1
- import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
- import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
1
+ import { selectMany } from "@cosmicdrift/kumiko-framework/db";
2
+ import { defineWriteHandler, isUuid, } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { NotFoundError, UnprocessableError, writeFailure, } from "@cosmicdrift/kumiko-framework/errors";
4
+ import { canCallerReadFileRef, fileRefsTable, } from "@cosmicdrift/kumiko-framework/files";
3
5
  import { PDFDocument } from "pdf-lib";
4
6
  import { requestExecutor, signerExecutor } from "../entity.js";
5
7
  import { readTenantFile, sha256Hex } from "../files.js";
6
8
  import { RequestSignatureSchema } from "../payloads.js";
7
- import { SIGNATURE_DEFAULT_VALIDITY_DAYS, SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_STATUS, } from "../web/constants.js";
9
+ import { SIGNATURE_DEFAULT_VALIDITY_DAYS, SIGNATURE_REQUEST_ENTITY, SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_STATUS, } from "../web/constants.js";
8
10
  const MS_PER_DAY = 24 * 60 * 60 * 1000;
9
11
  // Encrypted or unparseable PDFs would fail later when the signature page is appended and leave the
10
12
  // request stuck in all-signed.
@@ -17,7 +19,18 @@ async function isLoadablePdf(bytes) {
17
19
  return false;
18
20
  }
19
21
  }
20
- export function createRequestHandler(access) {
22
+ // A file the caller may not open through GET /files/:id answers like an unknown id, so ids cannot be probed.
23
+ async function isReadableTenantFile(ctx, fileRefId) {
24
+ if (!isUuid(fileRefId))
25
+ return false;
26
+ const [fileRef] = await selectMany(ctx.db, fileRefsTable, {
27
+ id: fileRefId,
28
+ tenantId: ctx.user.tenantId,
29
+ isDeleted: false,
30
+ });
31
+ return fileRef !== undefined && (await canCallerReadFileRef(ctx, fileRef));
32
+ }
33
+ export function createRequestHandler(access, scope) {
21
34
  return defineWriteHandler({
22
35
  name: "request",
23
36
  schema: RequestSignatureSchema,
@@ -27,6 +40,12 @@ export function createRequestHandler(access) {
27
40
  handler: async (event, ctx) => {
28
41
  const payload = event.payload;
29
42
  const user = event.user;
43
+ if (!(await scope.allows(ctx, user, payload.subjectType, payload.subjectId))) {
44
+ return writeFailure(new NotFoundError(SIGNATURE_REQUEST_ENTITY));
45
+ }
46
+ if (!(await isReadableTenantFile(ctx, payload.documentFileId))) {
47
+ return writeFailure(new UnprocessableError("document_not_a_pdf"));
48
+ }
30
49
  const document = await readTenantFile(ctx, user.tenantId, payload.documentFileId);
31
50
  if (document === null || !(await isLoadablePdf(document.content))) {
32
51
  return writeFailure(new UnprocessableError("document_not_a_pdf"));
@@ -1,5 +1,6 @@
1
1
  import { type AccessRule } from "@cosmicdrift/kumiko-framework/engine";
2
- export declare function createRevokeLinkHandler(access: AccessRule): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"revoke-link", import("zod").ZodObject<{
2
+ import type { SubjectScope } from "../subject-scope.ts";
3
+ export declare function createRevokeLinkHandler(access: AccessRule, scope: SubjectScope): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"revoke-link", import("zod").ZodObject<{
3
4
  signerId: import("zod").ZodUUID;
4
5
  }, import("zod/v4/core").$strip>, {
5
6
  readonly revoked: true;