@cosmicdrift/kumiko-samples 0.414.0 → 0.416.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 (142) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +21 -1
  3. package/packages/bundled-features/src/agent-tools/changes.json +6 -0
  4. package/packages/bundled-features/src/agent-tools/tool-catalog.ts +20 -1
  5. package/packages/bundled-features/src/agent-tools/tool-dispatch.ts +19 -5
  6. package/packages/bundled-features/src/auth-email-password/signup-token-store.ts +2 -3
  7. package/packages/bundled-features/src/auth-email-password/web/session.tsx +2 -1
  8. package/packages/bundled-features/src/auth-mfa/changes.json +6 -0
  9. package/packages/bundled-features/src/billing-foundation/changes.json +24 -0
  10. package/packages/bundled-features/src/billing-foundation/checkout-core.ts +11 -0
  11. package/packages/bundled-features/src/billing-foundation/checkout-ledger.ts +8 -0
  12. package/packages/bundled-features/src/billing-foundation/events.ts +7 -5
  13. package/packages/bundled-features/src/billing-foundation/handlers/create-checkout-session.write.ts +2 -0
  14. package/packages/bundled-features/src/billing-foundation/handlers/process-event.write.ts +76 -24
  15. package/packages/bundled-features/src/billing-foundation/handlers/process-payment-event.write.ts +5 -4
  16. package/packages/bundled-features/src/billing-foundation/handlers/start-plan-checkout.write.ts +2 -0
  17. package/packages/bundled-features/src/billing-foundation/webhook-handler.ts +2 -2
  18. package/packages/bundled-features/src/channel-whatsapp/changes.json +30 -0
  19. package/packages/bundled-features/src/channel-whatsapp/constants.ts +1 -0
  20. package/packages/bundled-features/src/channel-whatsapp/events.ts +4 -3
  21. package/packages/bundled-features/src/channel-whatsapp/graph-client.ts +37 -1
  22. package/packages/bundled-features/src/channel-whatsapp/inbound-handlers.ts +23 -2
  23. package/packages/bundled-features/src/channel-whatsapp/webhook-normalize.ts +27 -6
  24. package/packages/bundled-features/src/compliance-profiles/changes.json +5 -0
  25. package/packages/bundled-features/src/compliance-profiles/handlers/set-profile.write.ts +2 -0
  26. package/packages/bundled-features/src/data-retention/feature.ts +1 -0
  27. package/packages/bundled-features/src/delivery/changes.json +6 -0
  28. package/packages/bundled-features/src/delivery/handlers/opted-in-user-ids.query.ts +12 -3
  29. package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
  30. package/packages/bundled-features/src/document-ingest-foundation/feature.ts +1 -0
  31. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +3 -1
  32. package/packages/bundled-features/src/documents/changes.json +6 -0
  33. package/packages/bundled-features/src/documents/feature.ts +10 -5
  34. package/packages/bundled-features/src/form-draft/feature.ts +1 -0
  35. package/packages/bundled-features/src/handbook-knowledge/README.md +64 -0
  36. package/packages/bundled-features/src/handbook-knowledge/changes.json +8 -0
  37. package/packages/bundled-features/src/handbook-knowledge/constants.ts +8 -0
  38. package/packages/bundled-features/src/handbook-knowledge/feature.ts +34 -0
  39. package/packages/bundled-features/src/handbook-knowledge/handbook-index.ts +66 -0
  40. package/packages/bundled-features/src/handbook-knowledge/handlers.ts +77 -0
  41. package/packages/bundled-features/src/handbook-knowledge/index.ts +10 -0
  42. package/packages/bundled-features/src/helpdesk/changes.json +6 -0
  43. package/packages/bundled-features/src/helpdesk/feature.ts +1 -0
  44. package/packages/bundled-features/src/helpdesk/handlers/reply.write.ts +3 -3
  45. package/packages/bundled-features/src/helpdesk/handlers/report.write.ts +3 -2
  46. package/packages/bundled-features/src/helpdesk/handlers/submit.write.ts +3 -2
  47. package/packages/bundled-features/src/helpdesk/legacy-contact-streams.ts +3 -1
  48. package/packages/bundled-features/src/helpdesk/lib.ts +9 -4
  49. package/packages/bundled-features/src/inbound-mail-foundation/account-poll.ts +4 -1
  50. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +6 -0
  51. package/packages/bundled-features/src/inbound-mail-foundation/content-refetch.ts +11 -4
  52. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +18 -9
  53. package/packages/bundled-features/src/inbound-mail-foundation/events.ts +18 -9
  54. package/packages/bundled-features/src/inbound-mail-foundation/handlers/connect-account.write.ts +2 -1
  55. package/packages/bundled-features/src/inbound-mail-foundation/handlers/forget-message.write.ts +6 -0
  56. package/packages/bundled-features/src/inbound-mail-foundation/handlers/ingest-message-schema.ts +18 -5
  57. package/packages/bundled-features/src/inbound-mail-foundation/normalize-inbound-message.ts +22 -8
  58. package/packages/bundled-features/src/inbound-mail-foundation/sanitize-inbound-html.ts +2 -5
  59. package/packages/bundled-features/src/managed-pages/web/page-edit-screen.tsx +11 -5
  60. package/packages/bundled-features/src/shared/changes.json +6 -0
  61. package/packages/bundled-features/src/shared/hmac-signature.ts +4 -2
  62. package/packages/bundled-features/src/shared/index.ts +2 -1
  63. package/packages/bundled-features/src/shared/normalize-email.ts +3 -0
  64. package/packages/bundled-features/src/shared/send-best-effort.ts +16 -6
  65. package/packages/bundled-features/src/signature/README.md +59 -0
  66. package/packages/bundled-features/src/signature/changes.json +15 -0
  67. package/packages/bundled-features/src/signature/entity.ts +192 -0
  68. package/packages/bundled-features/src/signature/feature.ts +125 -0
  69. package/packages/bundled-features/src/signature/files.ts +107 -0
  70. package/packages/bundled-features/src/signature/grant.ts +79 -0
  71. package/packages/bundled-features/src/signature/handlers/anonymous.write.ts +88 -0
  72. package/packages/bundled-features/src/signature/handlers/cancel.write.ts +40 -0
  73. package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +72 -0
  74. package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +99 -0
  75. package/packages/bundled-features/src/signature/handlers/link-internal.write.ts +261 -0
  76. package/packages/bundled-features/src/signature/handlers/request.write.ts +86 -0
  77. package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +23 -0
  78. package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +69 -0
  79. package/packages/bundled-features/src/signature/i18n.ts +52 -0
  80. package/packages/bundled-features/src/signature/index.ts +33 -0
  81. package/packages/bundled-features/src/signature/lib.ts +125 -0
  82. package/packages/bundled-features/src/signature/options.ts +49 -0
  83. package/packages/bundled-features/src/signature/payloads.ts +71 -0
  84. package/packages/bundled-features/src/signature/png.ts +169 -0
  85. package/packages/bundled-features/src/signature/screens.ts +115 -0
  86. package/packages/bundled-features/src/signature/signature-page.ts +93 -0
  87. package/packages/bundled-features/src/signature/signing.ts +77 -0
  88. package/packages/bundled-features/src/signature/static-sign.ts +98 -0
  89. package/packages/bundled-features/src/signature/sweep.ts +161 -0
  90. package/packages/bundled-features/src/signature/user-data.ts +159 -0
  91. package/packages/bundled-features/src/signature/web/constants.ts +92 -0
  92. package/packages/bundled-features/src/signature/web/index.ts +31 -0
  93. package/packages/bundled-features/src/signature/web/pad.ts +147 -0
  94. package/packages/bundled-features/src/signature/web/signature-pad.tsx +82 -0
  95. package/packages/bundled-features/src/step-dispatcher/changes.json +6 -0
  96. package/packages/bundled-features/src/step-dispatcher/deliver-dispatch-request.ts +5 -2
  97. package/packages/bundled-features/src/step-dispatcher/feature.ts +14 -0
  98. package/packages/bundled-features/src/step-dispatcher/sweep-abandoned.ts +4 -0
  99. package/packages/bundled-features/src/subscription-paddle/backfill-checkout-ledger.ts +2 -0
  100. package/packages/bundled-features/src/subscription-paddle/changes.json +6 -0
  101. package/packages/bundled-features/src/subscription-paddle/redeliver-legacy-checkout.ts +23 -2
  102. package/packages/bundled-features/src/subscription-stripe/changes.json +12 -0
  103. package/packages/bundled-features/src/subscription-stripe/feature.ts +9 -0
  104. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +7 -1
  105. package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +19 -5
  106. package/packages/bundled-features/src/template-resolver/changes.json +12 -0
  107. package/packages/bundled-features/src/template-resolver/seeding.ts +37 -7
  108. package/packages/bundled-features/src/template-resolver/web/web-preview-renderer.tsx +7 -1
  109. package/packages/bundled-features/src/tenant-inactivity/changes.json +6 -0
  110. package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +34 -16
  111. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +6 -0
  112. package/packages/bundled-features/src/tenant-inactivity/state-store.ts +12 -1
  113. package/packages/bundled-features/src/tenant-lifecycle/changes.json +6 -0
  114. package/packages/bundled-features/src/tenant-lifecycle/feature.ts +1 -0
  115. package/packages/bundled-features/src/user/resolve-verified-user-email.ts +3 -3
  116. package/packages/bundled-features/src/user-data-rights/feature.ts +1 -0
  117. package/packages/bundled-features/src/waitlist/handlers/reject.write.ts +1 -1
  118. package/packages/bundled-features/src/waitlist/handlers/submit.write.ts +2 -2
  119. package/packages/bundled-features/src/waitlist/import.ts +2 -1
  120. package/packages/bundled-features/src/waitlist/lib.ts +1 -5
  121. package/packages/bundled-features/src/waitlist/link-on-signup.ts +2 -2
  122. package/packages/bundled-features/src/workflow-runner/changes.json +6 -0
  123. package/packages/bundled-features/src/workflow-runner/handlers/resume-run.write.ts +4 -2
  124. package/samples/apps/admin-console/src/app/shell.tsx +1 -0
  125. package/samples/apps/use-all-bundled/feature-manifest.json +63 -1
  126. package/samples/apps/use-all-bundled/kumiko/migrations/0068_signature.rebuild.json +4 -0
  127. package/samples/apps/use-all-bundled/src/run-config.ts +35 -1
  128. package/samples/recipes/crypto-shredding-hr/README.md +11 -0
  129. package/samples/recipes/crypto-shredding-hr/src/feature.ts +27 -0
  130. package/samples/recipes/embedded/README.md +4 -0
  131. package/samples/recipes/embedded/src/entities/invoice.ts +6 -0
  132. package/samples/recipes/embedded/src/feature.ts +7 -1
  133. package/samples/recipes/embedded/src/handlers/invoice-receive.write.ts +1 -0
  134. package/samples/recipes/embedded/src/screens/invoice-receive.screen.ts +2 -0
  135. package/samples/recipes/handbook-knowledge/README.md +22 -0
  136. package/samples/recipes/handbook-knowledge/package.json +12 -0
  137. package/samples/recipes/handbook-knowledge/src/feature.ts +42 -0
  138. package/samples/recipes/record-detail-layout/src/feature.ts +36 -5
  139. package/samples/recipes/record-detail-layout/src/order-board.ts +10 -2
  140. package/samples/recipes/signature/README.md +21 -0
  141. package/samples/recipes/signature/package.json +13 -0
  142. package/samples/recipes/signature/src/feature.ts +26 -0
@@ -0,0 +1,159 @@
1
+ import { configuredPiiSubjectKms } from "@cosmicdrift/kumiko-framework/crypto";
2
+ import { WritePurposes } from "@cosmicdrift/kumiko-framework/db";
3
+ import { deleteStoredFileAndDerivatives } from "@cosmicdrift/kumiko-framework/derivatives";
4
+ import {
5
+ createSystemUser,
6
+ type SessionUser,
7
+ type UserDataDeleteHook,
8
+ type UserDataExportHook,
9
+ type UserDataHookCtx,
10
+ } from "@cosmicdrift/kumiko-framework/engine";
11
+ import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
12
+ import { fileRefsTable } from "@cosmicdrift/kumiko-framework/files";
13
+ import { collectErasureFailure, throwIfErasureFailed } from "../shared/index.ts";
14
+ import { resolveVerifiedUserEmail } from "../user/index.ts";
15
+ import { requestExecutor, signatureSignerTable, signerExecutor } from "./entity.ts";
16
+ import { deleteFileRef } from "./files.ts";
17
+ import { setRequestStatus } from "./lib.ts";
18
+ import { SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_ENTITY } from "./web/constants.ts";
19
+
20
+ const PII_DECRYPT_REASON = "signature:user-data";
21
+ const ANONYMIZED_NAME = "anonymized";
22
+ const ERASE_REASON = "signature:subject-forget";
23
+
24
+ type SignerRecord = Record<string, unknown>;
25
+
26
+ // A signer has no user account: the only link to a user is the signer's email, which is stored
27
+ // lowercase and findable by exact match. Without a verified email nothing matches.
28
+ async function findSignerRows(ctx: UserDataHookCtx): Promise<readonly SignerRecord[]> {
29
+ const email = await resolveVerifiedUserEmail(ctx, PII_DECRYPT_REASON);
30
+ if (email === null) return [];
31
+ return ctx.db.selectMany<SignerRecord>(signatureSignerTable, {
32
+ tenantId: ctx.tenantId,
33
+ email: email.toLowerCase(),
34
+ });
35
+ }
36
+
37
+ function stringOrNull(value: unknown): string | null {
38
+ return typeof value === "string" ? value : null;
39
+ }
40
+
41
+ // The signer's fields belong to the row's own record key, not to the user's key, so the user
42
+ // forget run does not shred them; and anonymizing only empties the current row, the old events
43
+ // still hold the ciphertext. Without a mounted KMS this erases nothing: record-owned fields stay
44
+ // plaintext framework-wide (see notes-history-user-data), so apps that need Art. 17 coverage mount one.
45
+ async function shredSignerKey(ctx: UserDataHookCtx, signerId: string): Promise<void> {
46
+ // skip: no KMS adapter mounted, nothing is encrypted per record
47
+ await configuredPiiSubjectKms()?.eraseKey(
48
+ { kind: "record", entity: SIGNATURE_SIGNER_ENTITY, id: signerId },
49
+ { requestId: ERASE_REASON, userId: ctx.userId, eraseReason: ERASE_REASON },
50
+ );
51
+ }
52
+
53
+ export const signatureExportHook: UserDataExportHook = async (ctx) => {
54
+ const rows = await findSignerRows(ctx);
55
+ if (rows.length === 0) return null;
56
+ return {
57
+ entity: SIGNATURE_SIGNER_ENTITY,
58
+ rows: rows.map((row) => ({
59
+ requestId: row["requestId"],
60
+ name: row["name"],
61
+ role: row["role"],
62
+ status: row["status"],
63
+ method: row["method"],
64
+ signedAt: String(row["signedAt"] ?? ""),
65
+ signedFromIp: row["signedFromIp"],
66
+ signedUserAgent: row["signedUserAgent"],
67
+ declineReason: row["declineReason"],
68
+ })),
69
+ };
70
+ };
71
+
72
+ async function purgeSignatureImage(
73
+ ctx: UserDataHookCtx,
74
+ systemUser: SessionUser,
75
+ imageFileId: string,
76
+ ): Promise<void> {
77
+ const [ref] = await ctx.db.selectMany<{ id: string; storageKey: string }>(fileRefsTable, {
78
+ id: imageFileId,
79
+ });
80
+ // skip: the image is already gone, nothing left to erase
81
+ if (ref === undefined) return;
82
+ const provider = await ctx.buildStorageProvider?.(ctx.tenantId);
83
+ if (!provider) {
84
+ throw new InternalError({
85
+ message: `[signature:user-data] no file storage resolvable, signature image ${imageFileId} cannot be erased`,
86
+ });
87
+ }
88
+ const failed = await deleteStoredFileAndDerivatives(ref.storageKey, provider, PII_DECRYPT_REASON);
89
+ if (failed.length > 0) {
90
+ throw new InternalError({
91
+ message: `[signature:user-data] ${failed.length} byte delete(s) failed for signature image ${imageFileId}`,
92
+ });
93
+ }
94
+ await deleteFileRef(ctx.db, systemUser, imageFileId);
95
+ }
96
+
97
+ async function cancelUnfinishedRequest(
98
+ ctx: UserDataHookCtx,
99
+ systemUser: SessionUser,
100
+ requestId: string,
101
+ ): Promise<void> {
102
+ const request = await requestExecutor.detail({ id: requestId }, systemUser, ctx.db);
103
+ const status = request?.status;
104
+ if (status !== SIGNATURE_REQUEST_STATUS.Open && status !== SIGNATURE_REQUEST_STATUS.AllSigned) {
105
+ return;
106
+ }
107
+ await setRequestStatus(ctx, systemUser, requestId, status, {
108
+ status: SIGNATURE_REQUEST_STATUS.Cancelled,
109
+ });
110
+ }
111
+
112
+ // Erasure wins over retention for the person's own data: name, email, drawn image, IP address,
113
+ // user agent and refusal reason are removed (strategy delete: the whole row). What stays is the
114
+ // completed PDF with its signature page, which belongs to the request's owner as proof of the
115
+ // contract (Art. 17(3)(e) GDPR), and the row's status and timestamps under "anonymize". A forgotten
116
+ // signer would let the others complete the request without them (delete) or leave an all-signed
117
+ // request without the image it needs (anonymize), so an open or all-signed request is cancelled.
118
+ export const signatureDeleteHook: UserDataDeleteHook = async (ctx, strategy) => {
119
+ const systemUser = createSystemUser(ctx.tenantId);
120
+ const failures: string[] = [];
121
+ for (const row of await findSignerRows(ctx)) {
122
+ const id = stringOrNull(row["id"]);
123
+ if (id === null) continue;
124
+ const imageFileId = stringOrNull(row["imageFileId"]);
125
+ if (imageFileId !== null) await purgeSignatureImage(ctx, systemUser, imageFileId);
126
+ const requestId = stringOrNull(row["requestId"]);
127
+ if (strategy === "delete") {
128
+ const forgotten = await signerExecutor.forget({ id }, systemUser, ctx.db);
129
+ collectErasureFailure(forgotten, SIGNATURE_SIGNER_ENTITY, id, failures);
130
+ if (forgotten.isSuccess && requestId !== null) {
131
+ await cancelUnfinishedRequest(ctx, systemUser, requestId);
132
+ }
133
+ if (forgotten.isSuccess) await shredSignerKey(ctx, id);
134
+ continue;
135
+ }
136
+ const anonymized = await signerExecutor.update(
137
+ {
138
+ id,
139
+ changes: {
140
+ name: ANONYMIZED_NAME,
141
+ email: null,
142
+ imageFileId: null,
143
+ signedFromIp: null,
144
+ signedUserAgent: null,
145
+ declineReason: null,
146
+ linkAnchor: null,
147
+ },
148
+ },
149
+ systemUser,
150
+ ctx.db,
151
+ { skipOptimisticLock: true, writePurpose: WritePurposes.erasure },
152
+ );
153
+ collectErasureFailure(anonymized, SIGNATURE_SIGNER_ENTITY, id, failures);
154
+ if (!anonymized.isSuccess) continue;
155
+ if (requestId !== null) await cancelUnfinishedRequest(ctx, systemUser, requestId);
156
+ await shredSignerKey(ctx, id);
157
+ }
158
+ throwIfErasureFailed(failures);
159
+ };
@@ -0,0 +1,92 @@
1
+ // Pure string constants, safe for browser code (static-sign imports this file).
2
+ export const SIGNATURE_FEATURE = "signature" as const;
3
+
4
+ export const SIGNATURE_REQUEST_ENTITY = "signatureRequest" as const;
5
+ export const SIGNATURE_SIGNER_ENTITY = "signatureSigner" as const;
6
+
7
+ export const SIGNATURE_LEVEL = {
8
+ Simple: "simple",
9
+ } as const;
10
+
11
+ export type SignatureLevel = (typeof SIGNATURE_LEVEL)[keyof typeof SIGNATURE_LEVEL];
12
+
13
+ export const SIGNATURE_REQUEST_STATUS = {
14
+ Open: "open",
15
+ AllSigned: "all-signed",
16
+ Completed: "completed",
17
+ Declined: "declined",
18
+ Expired: "expired",
19
+ Cancelled: "cancelled",
20
+ } as const;
21
+
22
+ export type SignatureRequestStatus =
23
+ (typeof SIGNATURE_REQUEST_STATUS)[keyof typeof SIGNATURE_REQUEST_STATUS];
24
+
25
+ export const SIGNATURE_SIGNER_STATUS = {
26
+ Pending: "pending",
27
+ Viewed: "viewed",
28
+ Signed: "signed",
29
+ Declined: "declined",
30
+ } as const;
31
+
32
+ export type SignatureSignerStatus =
33
+ (typeof SIGNATURE_SIGNER_STATUS)[keyof typeof SIGNATURE_SIGNER_STATUS];
34
+
35
+ export const SIGNATURE_METHOD = {
36
+ InPerson: "in-person",
37
+ Link: "link",
38
+ } as const;
39
+
40
+ export type SignatureMethod = (typeof SIGNATURE_METHOD)[keyof typeof SIGNATURE_METHOD];
41
+
42
+ export const SignatureHandlers = {
43
+ request: `${SIGNATURE_FEATURE}:write:request`,
44
+ signInPerson: `${SIGNATURE_FEATURE}:write:sign-in-person`,
45
+ issueLink: `${SIGNATURE_FEATURE}:write:issue-link`,
46
+ revokeLink: `${SIGNATURE_FEATURE}:write:revoke-link`,
47
+ cancel: `${SIGNATURE_FEATURE}:write:cancel`,
48
+ openByLink: `${SIGNATURE_FEATURE}:write:open-by-link`,
49
+ signByLink: `${SIGNATURE_FEATURE}:write:sign-by-link`,
50
+ declineByLink: `${SIGNATURE_FEATURE}:write:decline-by-link`,
51
+ } as const;
52
+
53
+ export const SignatureQueries = {
54
+ list: `${SIGNATURE_FEATURE}:query:signature-request:list`,
55
+ detail: `${SIGNATURE_FEATURE}:query:signature-request:detail`,
56
+ signerList: `${SIGNATURE_FEATURE}:query:signature-signer:list`,
57
+ } as const;
58
+
59
+ export const SignatureJobs = {
60
+ sweep: `${SIGNATURE_FEATURE}:job:sweep`,
61
+ } as const;
62
+
63
+ export const SIGNATURE_EVENT_SHORT = {
64
+ completed: "completed",
65
+ declined: "declined",
66
+ expired: "expired",
67
+ } as const;
68
+
69
+ export const SignatureEvents = {
70
+ completed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.completed}`,
71
+ declined: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.declined}`,
72
+ expired: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.expired}`,
73
+ } as const;
74
+
75
+ // Every link rejection (forged, expired, revoked, used up, already signed) carries this reason, so
76
+ // a caller cannot tell the cases apart.
77
+ export const SIGNATURE_INVALID_LINK_REASON = "invalid_or_expired_link";
78
+
79
+ export const SIGNATURE_INVALID_IMAGE_REASON = "invalid_signature_image";
80
+
81
+ export const SIGNATURE_LINK_TTL_DAYS = 14;
82
+ export const SIGNATURE_MAX_LINK_OPENS = 20;
83
+ export const SIGNATURE_DEFAULT_VALIDITY_DAYS = 14;
84
+
85
+ export const SignatureInternalHandlers = {
86
+ linkOpen: `${SIGNATURE_FEATURE}:write:link-open`,
87
+ linkSign: `${SIGNATURE_FEATURE}:write:link-sign`,
88
+ linkDecline: `${SIGNATURE_FEATURE}:write:link-decline`,
89
+ finish: `${SIGNATURE_FEATURE}:write:finish`,
90
+ expire: `${SIGNATURE_FEATURE}:write:expire`,
91
+ reconcile: `${SIGNATURE_FEATURE}:write:reconcile`,
92
+ } as const;
@@ -0,0 +1,31 @@
1
+ export {
2
+ SIGNATURE_DEFAULT_VALIDITY_DAYS,
3
+ SIGNATURE_EVENT_SHORT,
4
+ SIGNATURE_FEATURE,
5
+ SIGNATURE_INVALID_IMAGE_REASON,
6
+ SIGNATURE_INVALID_LINK_REASON,
7
+ SIGNATURE_LEVEL,
8
+ SIGNATURE_LINK_TTL_DAYS,
9
+ SIGNATURE_MAX_LINK_OPENS,
10
+ SIGNATURE_METHOD,
11
+ SIGNATURE_REQUEST_ENTITY,
12
+ SIGNATURE_REQUEST_STATUS,
13
+ SIGNATURE_SIGNER_ENTITY,
14
+ SIGNATURE_SIGNER_STATUS,
15
+ SignatureEvents,
16
+ SignatureHandlers,
17
+ SignatureInternalHandlers,
18
+ SignatureJobs,
19
+ type SignatureLevel,
20
+ type SignatureMethod,
21
+ SignatureQueries,
22
+ type SignatureRequestStatus,
23
+ type SignatureSignerStatus,
24
+ } from "./constants.ts";
25
+ export type { SignaturePad as SignaturePadController, SignaturePadOptions } from "./pad.ts";
26
+ export {
27
+ DEFAULT_SIGNATURE_PAD_LABELS,
28
+ SignaturePad,
29
+ type SignaturePadLabels,
30
+ type SignaturePadProps,
31
+ } from "./signature-pad.tsx";
@@ -0,0 +1,147 @@
1
+ // Framework-free signature field: Pointer Events (finger, pen, mouse) on a canvas. Imports nothing,
2
+ // so the static-sign entry stays free of React and of any runtime dependency.
3
+
4
+ export type SignaturePadCanvas = Pick<
5
+ HTMLCanvasElement,
6
+ | "width"
7
+ | "height"
8
+ | "addEventListener"
9
+ | "removeEventListener"
10
+ | "getBoundingClientRect"
11
+ | "getContext"
12
+ | "toBlob"
13
+ | "setPointerCapture"
14
+ | "releasePointerCapture"
15
+ > & { readonly style: Pick<CSSStyleDeclaration, "touchAction"> };
16
+
17
+ export type SignaturePadOptions = {
18
+ /** Stroke width in canvas pixels. Default 3. */
19
+ readonly lineWidth?: number;
20
+ /** Stroke colour. Default near-black. */
21
+ readonly strokeStyle?: string;
22
+ /** Called whenever the field switches between empty and drawn. */
23
+ readonly onChange?: (isEmpty: boolean) => void;
24
+ };
25
+
26
+ export type SignaturePad = {
27
+ readonly clear: () => void;
28
+ readonly isEmpty: () => boolean;
29
+ /** PNG with transparent background as base64 without the data-URL prefix. */
30
+ readonly toPngBase64: () => Promise<string>;
31
+ readonly destroy: () => void;
32
+ };
33
+
34
+ const DEFAULT_LINE_WIDTH = 3;
35
+ const DEFAULT_STROKE_STYLE = "#111111";
36
+ const BASE64_CHUNK_SIZE = 0x8000;
37
+
38
+ export function bytesToBase64(bytes: Uint8Array): string {
39
+ let binary = "";
40
+ for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK_SIZE) {
41
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK_SIZE));
42
+ }
43
+ return btoa(binary);
44
+ }
45
+
46
+ type Point = { readonly x: number; readonly y: number };
47
+
48
+ // Closures of the pad need the non-null context; narrowing a const does not carry into them.
49
+ function requireContext(canvas: SignaturePadCanvas): CanvasRenderingContext2D {
50
+ const context = canvas.getContext("2d");
51
+ if (context === null) throw new Error("createSignaturePad: the canvas has no 2d context");
52
+ return context;
53
+ }
54
+
55
+ export function createSignaturePad(
56
+ canvas: SignaturePadCanvas,
57
+ options: SignaturePadOptions = {},
58
+ ): SignaturePad {
59
+ const context = requireContext(canvas);
60
+ const lineWidth = options.lineWidth ?? DEFAULT_LINE_WIDTH;
61
+ context.lineWidth = lineWidth;
62
+ context.lineCap = "round";
63
+ context.lineJoin = "round";
64
+ context.strokeStyle = options.strokeStyle ?? DEFAULT_STROKE_STYLE;
65
+ context.fillStyle = options.strokeStyle ?? DEFAULT_STROKE_STYLE;
66
+ canvas.style.touchAction = "none";
67
+
68
+ let drawnAny = false;
69
+ let activePointerId: number | null = null;
70
+ let lastPoint: Point | null = null;
71
+
72
+ function setDrawn(next: boolean): void {
73
+ if (drawnAny === next) return;
74
+ drawnAny = next;
75
+ options.onChange?.(!next);
76
+ }
77
+
78
+ // The canvas may be displayed at another size than its pixel size (CSS scaling).
79
+ function pointOf(event: PointerEvent): Point {
80
+ const rect = canvas.getBoundingClientRect();
81
+ const scaleX = rect.width > 0 ? canvas.width / rect.width : 1;
82
+ const scaleY = rect.height > 0 ? canvas.height / rect.height : 1;
83
+ return { x: (event.clientX - rect.left) * scaleX, y: (event.clientY - rect.top) * scaleY };
84
+ }
85
+
86
+ function onPointerDown(event: PointerEvent): void {
87
+ if (activePointerId !== null) return;
88
+ activePointerId = event.pointerId;
89
+ canvas.setPointerCapture(event.pointerId);
90
+ const point = pointOf(event);
91
+ lastPoint = point;
92
+ context.beginPath();
93
+ context.arc(point.x, point.y, lineWidth / 2, 0, Math.PI * 2);
94
+ context.fill();
95
+ setDrawn(true);
96
+ event.preventDefault();
97
+ }
98
+
99
+ function onPointerMove(event: PointerEvent): void {
100
+ if (event.pointerId !== activePointerId || lastPoint === null) return;
101
+ const point = pointOf(event);
102
+ context.beginPath();
103
+ context.moveTo(lastPoint.x, lastPoint.y);
104
+ context.lineTo(point.x, point.y);
105
+ context.stroke();
106
+ lastPoint = point;
107
+ event.preventDefault();
108
+ }
109
+
110
+ function onPointerEnd(event: PointerEvent): void {
111
+ if (event.pointerId !== activePointerId) return;
112
+ canvas.releasePointerCapture(event.pointerId);
113
+ activePointerId = null;
114
+ lastPoint = null;
115
+ }
116
+
117
+ canvas.addEventListener("pointerdown", onPointerDown);
118
+ canvas.addEventListener("pointermove", onPointerMove);
119
+ canvas.addEventListener("pointerup", onPointerEnd);
120
+ canvas.addEventListener("pointercancel", onPointerEnd);
121
+
122
+ return {
123
+ clear: () => {
124
+ context.clearRect(0, 0, canvas.width, canvas.height);
125
+ setDrawn(false);
126
+ },
127
+ isEmpty: () => !drawnAny,
128
+ toPngBase64: () =>
129
+ new Promise((resolve, reject) => {
130
+ canvas.toBlob((blob) => {
131
+ if (blob === null) {
132
+ reject(new Error("createSignaturePad: the canvas could not be exported as PNG"));
133
+ return;
134
+ }
135
+ blob
136
+ .arrayBuffer()
137
+ .then((buffer) => resolve(bytesToBase64(new Uint8Array(buffer))), reject);
138
+ }, "image/png");
139
+ }),
140
+ destroy: () => {
141
+ canvas.removeEventListener("pointerdown", onPointerDown);
142
+ canvas.removeEventListener("pointermove", onPointerMove);
143
+ canvas.removeEventListener("pointerup", onPointerEnd);
144
+ canvas.removeEventListener("pointercancel", onPointerEnd);
145
+ },
146
+ };
147
+ }
@@ -0,0 +1,82 @@
1
+ import { usePrimitives } from "@cosmicdrift/kumiko-renderer";
2
+ import { useCallback, useRef, useState } from "react";
3
+ import { createSignaturePad, type SignaturePad as SignaturePadController } from "./pad.ts";
4
+
5
+ export type SignaturePadLabels = {
6
+ readonly fieldLabel: string;
7
+ readonly clear: string;
8
+ readonly signOnPaper: string;
9
+ };
10
+
11
+ export const DEFAULT_SIGNATURE_PAD_LABELS: SignaturePadLabels = {
12
+ fieldLabel: "Signature field: draw your signature with finger, pen or mouse",
13
+ clear: "Clear",
14
+ signOnPaper: "Sign on paper instead",
15
+ };
16
+
17
+ export type SignaturePadProps = {
18
+ /** Gets the controller once the canvas is mounted and null on unmount; read `toPngBase64()` from it on submit. Keep it referentially stable, a new function recreates the field. */
19
+ readonly onPadReady: (pad: SignaturePadController | null) => void;
20
+ /** Same stability requirement as `onPadReady`. */
21
+ readonly onChange?: (isEmpty: boolean) => void;
22
+ /** Shows the "sign on paper" exit; the signer who cannot draw must always have a way out. */
23
+ readonly onSignOnPaper?: () => void;
24
+ readonly labels?: Partial<SignaturePadLabels>;
25
+ readonly width?: number;
26
+ readonly height?: number;
27
+ };
28
+
29
+ const DEFAULT_WIDTH = 600;
30
+ const DEFAULT_HEIGHT = 240;
31
+
32
+ // Drawing needs a pointer; everything else (clear, the paper exit) is a plain focusable button.
33
+ // The pad lives in a callback ref instead of an effect: it follows the canvas element's mount and unmount.
34
+ export function SignaturePad(props: SignaturePadProps) {
35
+ const { Button } = usePrimitives();
36
+ const labels = { ...DEFAULT_SIGNATURE_PAD_LABELS, ...props.labels };
37
+ const padRef = useRef<SignaturePadController | null>(null);
38
+ const [isEmpty, setIsEmpty] = useState(true);
39
+ const { onPadReady, onChange } = props;
40
+
41
+ const mountPad = useCallback(
42
+ (canvas: HTMLCanvasElement) => {
43
+ const pad = createSignaturePad(canvas, {
44
+ onChange: (empty) => {
45
+ setIsEmpty(empty);
46
+ onChange?.(empty);
47
+ },
48
+ });
49
+ padRef.current = pad;
50
+ onPadReady(pad);
51
+ return () => {
52
+ pad.destroy();
53
+ padRef.current = null;
54
+ onPadReady(null);
55
+ };
56
+ },
57
+ [onPadReady, onChange],
58
+ );
59
+
60
+ return (
61
+ <div className="flex flex-col gap-2">
62
+ <canvas
63
+ ref={mountPad}
64
+ width={props.width ?? DEFAULT_WIDTH}
65
+ height={props.height ?? DEFAULT_HEIGHT}
66
+ role="img"
67
+ aria-label={labels.fieldLabel}
68
+ className="w-full rounded border border-input bg-white"
69
+ />
70
+ <div className="flex gap-2">
71
+ <Button variant="secondary" disabled={isEmpty} onClick={() => padRef.current?.clear()}>
72
+ {labels.clear}
73
+ </Button>
74
+ {props.onSignOnPaper === undefined ? null : (
75
+ <Button variant="ghost" onClick={props.onSignOnPaper}>
76
+ {labels.signOnPaper}
77
+ </Button>
78
+ )}
79
+ </div>
80
+ </div>
81
+ );
82
+ }
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.415.0",
4
+ "type": "fix",
5
+ "title": "Abandoned-dispatch sweep skips live deliver jobs and cannot overwrite a concurrent outcome",
6
+ "detail": "Before closing a request older than 24 h the sweep asks the job runner whether its deliver job is still waiting, delayed, active, paused or prioritized and skips it until a later run. A runner that cannot report job state makes the sweep skip everything and warn. The failure event is appended with the stream version that was loaded, so a delivery recording its outcome in between causes a version conflict (reported through the close-failure log) and the payload key is not erased. `JobRunner` and `JobRunnerRef` gain an optional `isJobPending(jobName, jobId)`, and `MultiStreamApplyContext.unsafeAppendEvent` accepts an optional `expectedVersion`."
7
+ },
2
8
  {
3
9
  "version": "0.414.0",
4
10
  "type": "fix",
@@ -141,6 +141,7 @@ function createOutcomeRecorder(
141
141
  ctx: MultiStreamApplyContext,
142
142
  aggregateId: string,
143
143
  attempt: number,
144
+ expectedVersion?: number,
144
145
  ): OutcomeRecorder {
145
146
  const record: OutcomeRecorder["record"] = async (type, payload) => {
146
147
  await ctx.unsafeAppendEvent({
@@ -148,6 +149,7 @@ function createOutcomeRecorder(
148
149
  aggregateType: STEP_DISPATCH_AGGREGATE_TYPE,
149
150
  type,
150
151
  payload,
152
+ ...(expectedVersion !== undefined && { expectedVersion }),
151
153
  });
152
154
  await eraseDispatchKey(aggregateId);
153
155
  };
@@ -160,7 +162,8 @@ function createOutcomeRecorder(
160
162
 
161
163
  // For a deliver job that ended terminally without an outcome (BullMQ stall, lost job): the
162
164
  // request is closed as failed and its key erased. A stream that already has an outcome only
163
- // repeats the erase.
165
+ // repeats the erase. The failure is pinned to the loaded version: a delivery that records its
166
+ // outcome in between makes the append throw VersionConflictError and the key stays.
164
167
  export async function closeAbandonedDispatch(
165
168
  ctx: MultiStreamApplyContext,
166
169
  aggregateId: string,
@@ -171,7 +174,7 @@ export async function closeAbandonedDispatch(
171
174
  return "already-closed";
172
175
  }
173
176
  const requested = stream.find((e) => e.type === STEP_DISPATCH_REQUESTED_TYPE);
174
- await createOutcomeRecorder(ctx, aggregateId, 0).recordFailure(
177
+ await createOutcomeRecorder(ctx, aggregateId, 0, stream.at(-1)?.version).recordFailure(
175
178
  rawStepKindOf(requested?.payload),
176
179
  DISPATCH_ABANDONED_ERROR,
177
180
  );
@@ -77,6 +77,7 @@ export function createStepDispatcherFeature(): FeatureDefinition {
77
77
  "deliver",
78
78
  {
79
79
  trigger: { manual: true },
80
+ irreversibleWithoutEntryHandler: "per-dispatch-record-key",
80
81
  retries: DELIVER_RETRIES,
81
82
  backoff: "exponential",
82
83
  maxPerTenant: { limit: DELIVER_MAX_PER_TENANT, onLimit: "defer" },
@@ -110,13 +111,25 @@ export function createStepDispatcherFeature(): FeatureDefinition {
110
111
  "sweep-abandoned",
111
112
  {
112
113
  trigger: { cron: "17 3 * * *", wakesSleepingApp: false },
114
+ irreversibleWithoutEntryHandler: "per-dispatch-record-key",
113
115
  concurrency: "skip",
114
116
  escapeHatch: { reason: SWEEP_ESCAPE_HATCH_REASON },
115
117
  },
116
118
  async (_payload, ctx) => {
119
+ const runner = ctx.services.jobRunner;
120
+ const isJobPending = runner?.isJobPending?.bind(runner);
121
+ if (!isJobPending) {
122
+ // Fail closed: closing would erase the PII key of a delivery that may still run.
123
+ ctx.obs.log.warn(
124
+ "job runner cannot report job state, abandoned dispatches are not swept",
125
+ );
126
+ return;
127
+ }
117
128
  await sweepAbandonedDispatches({
118
129
  db: ctx.db.unsafeRaw(),
119
130
  registry: ctx.registry,
131
+ isDeliverJobPending: (aggregateId) =>
132
+ isJobPending(StepDispatcherJobs.deliver, deliverJobId(aggregateId)),
120
133
  startedBeforeIso: ctx.tz
121
134
  .now()
122
135
  .subtract({ hours: ABANDON_DISPATCH_AFTER_HOURS })
@@ -129,6 +142,7 @@ export function createStepDispatcherFeature(): FeatureDefinition {
129
142
 
130
143
  r.multiStreamProjection({
131
144
  name: "step-dispatcher",
145
+ irreversibleWithoutEntryHandler: "per-dispatch-record-key",
132
146
  apply: {
133
147
  [STEP_DISPATCH_REQUESTED_TYPE]: async (event, _tx, ctx) => {
134
148
  const stream = await ctx.loadAggregate(event.aggregateId);
@@ -16,6 +16,8 @@ export type SweepAbandonedArgs = {
16
16
  readonly db: DbRunner;
17
17
  readonly registry: Registry;
18
18
  readonly startedBeforeIso: string;
19
+ // A stream whose deliver job is still queued or running is alive, not abandoned.
20
+ readonly isDeliverJobPending: (aggregateId: string) => Promise<boolean>;
19
21
  readonly onCloseFailure: (aggregateId: string, errorName: string) => void;
20
22
  readonly batchSize?: number;
21
23
  };
@@ -43,6 +45,8 @@ export async function sweepAbandonedDispatches(args: SweepAbandonedArgs): Promis
43
45
  callerFeature: STEP_DISPATCHER_FEATURE,
44
46
  });
45
47
  try {
48
+ // skip: the next run checks the stream again
49
+ if (await args.isDeliverJobPending(aggregateId)) continue;
46
50
  await closeAbandonedDispatch(applyContext, aggregateId);
47
51
  } catch (err) {
48
52
  // One broken stream must not keep the others open; the next run retries it.
@@ -2,6 +2,8 @@
2
2
  // existed: their custom_data still carries the old tenantBinding. Once the
3
3
  // first sweep is done the job keeps sweeping for an hour (checkouts opened by
4
4
  // the previous release can still be paid), then does nothing.
5
+ // The tenant in custom_data is unverified: the key that signed the binding no longer exists.
6
+ // Only origin "api" and the one hour window bound that; losing a paid checkout would be worse.
5
7
 
6
8
  import {
7
9
  parseProviderConsentId,
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.415.0",
4
+ "type": "fix",
5
+ "title": "unreadable ledger backfill marker no longer causes endless 503",
6
+ "detail": "shouldRedeliverLegacyCheckout answers 200 and logs when the marker dispatch fails, because custom_data.tenantBinding is client-settable."
7
+ },
2
8
  {
3
9
  "version": "0.414.0",
4
10
  "type": "breaking",