@cosmicdrift/kumiko-bundled-features 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 (174) hide show
  1. package/dist/agent-tools/tool-catalog.js +20 -1
  2. package/dist/agent-tools/tool-dispatch.js +14 -5
  3. package/dist/auth-email-password/signup-token-store.d.ts +2 -2
  4. package/dist/auth-email-password/signup-token-store.js +2 -4
  5. package/dist/auth-email-password/web/session.js +2 -1
  6. package/dist/billing-foundation/checkout-core.d.ts +2 -0
  7. package/dist/billing-foundation/checkout-core.js +9 -0
  8. package/dist/billing-foundation/checkout-ledger.d.ts +7 -0
  9. package/dist/billing-foundation/checkout-ledger.js +6 -0
  10. package/dist/billing-foundation/events.d.ts +1 -0
  11. package/dist/billing-foundation/events.js +6 -5
  12. package/dist/billing-foundation/handlers/create-checkout-session.write.js +2 -1
  13. package/dist/billing-foundation/handlers/process-event.write.d.ts +3 -1
  14. package/dist/billing-foundation/handlers/process-event.write.js +57 -32
  15. package/dist/billing-foundation/handlers/process-payment-event.write.js +5 -5
  16. package/dist/billing-foundation/handlers/start-plan-checkout.write.js +2 -1
  17. package/dist/billing-foundation/webhook-handler.js +2 -2
  18. package/dist/channel-whatsapp/constants.d.ts +1 -0
  19. package/dist/channel-whatsapp/constants.js +1 -0
  20. package/dist/channel-whatsapp/events.d.ts +3 -0
  21. package/dist/channel-whatsapp/events.js +4 -3
  22. package/dist/channel-whatsapp/graph-client.d.ts +2 -0
  23. package/dist/channel-whatsapp/graph-client.js +29 -2
  24. package/dist/channel-whatsapp/inbound-handlers.js +24 -3
  25. package/dist/channel-whatsapp/webhook-normalize.js +21 -6
  26. package/dist/compliance-profiles/handlers/set-profile.write.js +2 -0
  27. package/dist/data-retention/feature.js +1 -0
  28. package/dist/delivery/handlers/opted-in-user-ids.query.js +12 -3
  29. package/dist/document-ingest-foundation/feature.js +1 -0
  30. package/dist/document-ingest-foundation/report-ingest-progress.js +4 -1
  31. package/dist/documents/feature.d.ts +2 -2
  32. package/dist/documents/feature.js +7 -2
  33. package/dist/form-draft/feature.js +1 -0
  34. package/dist/handbook-knowledge/constants.d.ts +6 -0
  35. package/dist/handbook-knowledge/constants.js +6 -0
  36. package/dist/handbook-knowledge/feature.d.ts +9 -0
  37. package/dist/handbook-knowledge/feature.js +17 -0
  38. package/dist/handbook-knowledge/handbook-index.d.ts +26 -0
  39. package/dist/handbook-knowledge/handbook-index.js +51 -0
  40. package/dist/handbook-knowledge/handlers.d.ts +28 -0
  41. package/dist/handbook-knowledge/handlers.js +67 -0
  42. package/dist/handbook-knowledge/index.d.ts +3 -0
  43. package/dist/handbook-knowledge/index.js +2 -0
  44. package/dist/helpdesk/feature.js +1 -0
  45. package/dist/helpdesk/handlers/reply.write.js +3 -3
  46. package/dist/helpdesk/handlers/report.write.js +3 -2
  47. package/dist/helpdesk/handlers/submit.write.js +3 -2
  48. package/dist/helpdesk/legacy-contact-streams.js +5 -2
  49. package/dist/helpdesk/lib.d.ts +1 -1
  50. package/dist/helpdesk/lib.js +4 -4
  51. package/dist/inbound-mail-foundation/account-poll.js +2 -0
  52. package/dist/inbound-mail-foundation/content-refetch.d.ts +3 -0
  53. package/dist/inbound-mail-foundation/content-refetch.js +2 -6
  54. package/dist/inbound-mail-foundation/entities.js +10 -9
  55. package/dist/inbound-mail-foundation/events.js +10 -9
  56. package/dist/inbound-mail-foundation/handlers/connect-account.write.js +2 -1
  57. package/dist/inbound-mail-foundation/handlers/forget-message.write.js +4 -0
  58. package/dist/inbound-mail-foundation/handlers/ingest-message-schema.js +12 -5
  59. package/dist/inbound-mail-foundation/normalize-inbound-message.d.ts +6 -0
  60. package/dist/inbound-mail-foundation/normalize-inbound-message.js +21 -8
  61. package/dist/inbound-mail-foundation/sanitize-inbound-html.d.ts +0 -1
  62. package/dist/inbound-mail-foundation/sanitize-inbound-html.js +2 -4
  63. package/dist/managed-pages/web/page-edit-screen.js +12 -5
  64. package/dist/shared/hmac-signature.js +4 -2
  65. package/dist/shared/index.d.ts +2 -1
  66. package/dist/shared/index.js +2 -1
  67. package/dist/shared/normalize-email.d.ts +1 -0
  68. package/dist/shared/normalize-email.js +3 -0
  69. package/dist/shared/send-best-effort.d.ts +1 -0
  70. package/dist/shared/send-best-effort.js +10 -5
  71. package/dist/signature/entity.d.ts +552 -0
  72. package/dist/signature/entity.js +156 -0
  73. package/dist/signature/feature.d.ts +3 -0
  74. package/dist/signature/feature.js +91 -0
  75. package/dist/signature/files.d.ts +23 -0
  76. package/dist/signature/files.js +64 -0
  77. package/dist/signature/grant.d.ts +32 -0
  78. package/dist/signature/grant.js +44 -0
  79. package/dist/signature/handlers/anonymous.write.d.ts +14 -0
  80. package/dist/signature/handlers/anonymous.write.js +52 -0
  81. package/dist/signature/handlers/cancel.write.d.ts +6 -0
  82. package/dist/signature/handlers/cancel.write.js +30 -0
  83. package/dist/signature/handlers/issue-link.write.d.ts +9 -0
  84. package/dist/signature/handlers/issue-link.write.js +57 -0
  85. package/dist/signature/handlers/lifecycle.write.d.ts +16 -0
  86. package/dist/signature/handlers/lifecycle.write.js +70 -0
  87. package/dist/signature/handlers/link-internal.write.d.ts +23 -0
  88. package/dist/signature/handlers/link-internal.write.js +186 -0
  89. package/dist/signature/handlers/request.write.d.ts +19 -0
  90. package/dist/signature/handlers/request.write.js +67 -0
  91. package/dist/signature/handlers/revoke-link.write.d.ts +6 -0
  92. package/dist/signature/handlers/revoke-link.write.js +18 -0
  93. package/dist/signature/handlers/sign-in-person.write.d.ts +8 -0
  94. package/dist/signature/handlers/sign-in-person.write.js +52 -0
  95. package/dist/signature/i18n.d.ts +6 -0
  96. package/dist/signature/i18n.js +49 -0
  97. package/dist/signature/index.d.ts +5 -0
  98. package/dist/signature/index.js +2 -0
  99. package/dist/signature/lib.d.ts +54 -0
  100. package/dist/signature/lib.js +68 -0
  101. package/dist/signature/options.d.ts +31 -0
  102. package/dist/signature/options.js +5 -0
  103. package/dist/signature/payloads.d.ts +60 -0
  104. package/dist/signature/payloads.js +53 -0
  105. package/dist/signature/png.d.ts +11 -0
  106. package/dist/signature/png.js +159 -0
  107. package/dist/signature/screens.d.ts +3 -0
  108. package/dist/signature/screens.js +95 -0
  109. package/dist/signature/signature-page.d.ts +25 -0
  110. package/dist/signature/signature-page.js +62 -0
  111. package/dist/signature/signing.d.ts +19 -0
  112. package/dist/signature/signing.js +46 -0
  113. package/dist/signature/static-sign.d.ts +17 -0
  114. package/dist/signature/static-sign.js +44 -0
  115. package/dist/signature/sweep.d.ts +3 -0
  116. package/dist/signature/sweep.js +113 -0
  117. package/dist/signature/user-data.d.ts +3 -0
  118. package/dist/signature/user-data.js +135 -0
  119. package/dist/signature/web/constants.d.ts +69 -0
  120. package/dist/signature/web/constants.js +68 -0
  121. package/dist/signature/web/index.d.ts +3 -0
  122. package/dist/signature/web/index.js +2 -0
  123. package/dist/signature/web/pad.d.ts +20 -0
  124. package/dist/signature/web/pad.js +104 -0
  125. package/dist/signature/web/signature-pad.d.ts +19 -0
  126. package/dist/signature/web/signature-pad.js +36 -0
  127. package/dist/step-dispatcher/deliver-dispatch-request.js +5 -3
  128. package/dist/step-dispatcher/feature.js +11 -0
  129. package/dist/step-dispatcher/sweep-abandoned.d.ts +1 -0
  130. package/dist/step-dispatcher/sweep-abandoned.js +3 -0
  131. package/dist/subscription-paddle/backfill-checkout-ledger.js +2 -0
  132. package/dist/subscription-paddle/redeliver-legacy-checkout.js +19 -2
  133. package/dist/subscription-stripe/feature.d.ts +6 -0
  134. package/dist/subscription-stripe/feature.js +3 -0
  135. package/dist/subscription-stripe/plugin-methods.d.ts +3 -1
  136. package/dist/subscription-stripe/plugin-methods.js +2 -1
  137. package/dist/subscription-stripe/verify-webhook.js +16 -6
  138. package/dist/template-resolver/seeding.js +32 -7
  139. package/dist/template-resolver/web/web-preview-renderer.js +5 -1
  140. package/dist/tenant-inactivity/check-inactive-tenants.js +27 -16
  141. package/dist/tenant-inactivity/handlers/keep-account.write.js +7 -0
  142. package/dist/tenant-inactivity/state-store.d.ts +2 -1
  143. package/dist/tenant-inactivity/state-store.js +7 -0
  144. package/dist/tenant-lifecycle/feature.js +1 -0
  145. package/dist/user/resolve-verified-user-email.js +3 -3
  146. package/dist/user-data-rights/feature.js +1 -0
  147. package/dist/waitlist/handlers/reject.write.js +2 -1
  148. package/dist/waitlist/handlers/submit.write.js +2 -2
  149. package/dist/waitlist/import.js +2 -1
  150. package/dist/waitlist/lib.d.ts +0 -1
  151. package/dist/waitlist/lib.js +1 -4
  152. package/dist/waitlist/link-on-signup.js +2 -2
  153. package/dist/workflow-runner/handlers/resume-run.write.js +4 -3
  154. package/package.json +43 -11
  155. package/src/agent-tools/changes.json +6 -0
  156. package/src/auth-mfa/changes.json +6 -0
  157. package/src/billing-foundation/changes.json +24 -0
  158. package/src/channel-whatsapp/changes.json +30 -0
  159. package/src/compliance-profiles/changes.json +5 -0
  160. package/src/delivery/changes.json +6 -0
  161. package/src/document-ingest-foundation/changes.json +6 -0
  162. package/src/documents/changes.json +6 -0
  163. package/src/handbook-knowledge/changes.json +8 -0
  164. package/src/helpdesk/changes.json +6 -0
  165. package/src/inbound-mail-foundation/changes.json +6 -0
  166. package/src/shared/changes.json +6 -0
  167. package/src/signature/changes.json +15 -0
  168. package/src/step-dispatcher/changes.json +6 -0
  169. package/src/subscription-paddle/changes.json +6 -0
  170. package/src/subscription-stripe/changes.json +12 -0
  171. package/src/template-resolver/changes.json +12 -0
  172. package/src/tenant-inactivity/changes.json +6 -0
  173. package/src/tenant-lifecycle/changes.json +6 -0
  174. package/src/workflow-runner/changes.json +6 -0
@@ -0,0 +1,31 @@
1
+ import type { AccessRule, HandlerContext, SessionUser } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { RateLimitDeclaration } from "@cosmicdrift/kumiko-types/handlers";
3
+ import type { PdfOptions } from "../renderer-foundation/index.ts";
4
+ import type { SignatureRetention } from "./entity.ts";
5
+ export type RenderSignatureHtmlToPdf = (html: string, options?: PdfOptions) => Promise<Uint8Array>;
6
+ export type SignatureLinkDelivery = {
7
+ readonly signerId: string;
8
+ readonly requestId: string;
9
+ readonly name: string;
10
+ readonly email: string;
11
+ /** Signing link with the token in the fragment. */
12
+ readonly url: string;
13
+ /** Who issued the link, e.g. to pick the mailbox it is sent from. */
14
+ readonly issuedBy: SessionUser;
15
+ };
16
+ export type DeliverSignatureLink = (ctx: HandlerContext, delivery: SignatureLinkDelivery) => Promise<void>;
17
+ export type SignatureOptions = {
18
+ /** How long requests and signers are kept, data-retention keepFor syntax, counted from creation. */
19
+ readonly retention: SignatureRetention;
20
+ /** Renders the signature page (HTML) to a PDF. An outage leaves the request at `all-signed` and the sweep job retries. */
21
+ readonly renderHtmlToPdf: RenderSignatureHtmlToPdf;
22
+ /** HMAC secret of the signing links. Without it every link is rejected. */
23
+ readonly linkSecret: string;
24
+ /** Sends a freshly issued link to the signer, e.g. by mail. A throw fails issue-link and leaves no link sent. */
25
+ readonly deliverLink: DeliverSignatureLink;
26
+ /** URL of the app's signature page; the token is appended as `#<token>`. */
27
+ readonly signaturePageUrl: string;
28
+ /** 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. */
29
+ readonly access?: AccessRule;
30
+ };
31
+ export declare const LINK_RATE_LIMIT: RateLimitDeclaration;
@@ -0,0 +1,5 @@
1
+ export const LINK_RATE_LIMIT = {
2
+ per: "ip+handler",
3
+ limit: 30,
4
+ windowSeconds: 60,
5
+ };
@@ -0,0 +1,60 @@
1
+ import * as z from "zod";
2
+ export declare const MAX_SIGNERS_PER_REQUEST = 20;
3
+ export declare const RequestSignatureSchema: z.ZodObject<{
4
+ documentFileId: z.ZodUUID;
5
+ title: z.ZodString;
6
+ level: z.ZodDefault<z.ZodLiteral<"simple">>;
7
+ subjectType: z.ZodString;
8
+ subjectId: z.ZodString;
9
+ expiresInDays: z.ZodOptional<z.ZodNumber>;
10
+ signers: z.ZodArray<z.ZodObject<{
11
+ name: z.ZodString;
12
+ role: z.ZodOptional<z.ZodString>;
13
+ contactId: z.ZodOptional<z.ZodString>;
14
+ email: z.ZodOptional<z.ZodString>;
15
+ }, z.core.$strip>>;
16
+ }, z.core.$strip>;
17
+ export type RequestSignatureInput = z.infer<typeof RequestSignatureSchema>;
18
+ export declare const SignInPersonSchema: z.ZodObject<{
19
+ signerId: z.ZodUUID;
20
+ imagePngBase64: z.ZodString;
21
+ }, z.core.$strip>;
22
+ export declare const SignerIdSchema: z.ZodObject<{
23
+ signerId: z.ZodUUID;
24
+ }, z.core.$strip>;
25
+ export declare const RequestIdSchema: z.ZodObject<{
26
+ requestId: z.ZodUUID;
27
+ }, z.core.$strip>;
28
+ export declare const OpenByLinkSchema: z.ZodObject<{
29
+ token: z.ZodString;
30
+ }, z.core.$strip>;
31
+ export declare const SignByLinkSchema: z.ZodObject<{
32
+ token: z.ZodString;
33
+ imagePngBase64: z.ZodString;
34
+ }, z.core.$strip>;
35
+ export declare const DeclineByLinkSchema: z.ZodObject<{
36
+ token: z.ZodString;
37
+ reason: z.ZodOptional<z.ZodString>;
38
+ }, z.core.$strip>;
39
+ export declare const FinishSchema: z.ZodObject<{
40
+ requestId: z.ZodUUID;
41
+ completedFileId: z.ZodUUID;
42
+ }, z.core.$strip>;
43
+ export declare const SignatureCompletedEventSchema: z.ZodObject<{
44
+ requestId: z.ZodString;
45
+ subjectType: z.ZodString;
46
+ subjectId: z.ZodString;
47
+ completedFileId: z.ZodString;
48
+ signerCount: z.ZodNumber;
49
+ }, z.core.$strip>;
50
+ export declare const SignatureDeclinedEventSchema: z.ZodObject<{
51
+ requestId: z.ZodString;
52
+ subjectType: z.ZodString;
53
+ subjectId: z.ZodString;
54
+ signerId: z.ZodString;
55
+ }, z.core.$strip>;
56
+ export declare const SignatureExpiredEventSchema: z.ZodObject<{
57
+ requestId: z.ZodString;
58
+ subjectType: z.ZodString;
59
+ subjectId: z.ZodString;
60
+ }, z.core.$strip>;
@@ -0,0 +1,53 @@
1
+ import * as z from "zod";
2
+ import { MAX_SIGNATURE_PNG_BYTES } from "./png.js";
3
+ import { SIGNATURE_LEVEL } from "./web/constants.js";
4
+ export const MAX_SIGNERS_PER_REQUEST = 20;
5
+ const MAX_VALIDITY_DAYS = 365;
6
+ // Base64 inflates by 4/3; the png checks apply to the decoded bytes.
7
+ const MAX_IMAGE_BASE64_LENGTH = Math.ceil((MAX_SIGNATURE_PNG_BYTES * 4) / 3) + 4;
8
+ const MAX_TOKEN_LENGTH = 2000;
9
+ const SignerInputSchema = z.object({
10
+ name: z.string().trim().min(1).max(200),
11
+ role: z.string().trim().min(1).max(100).optional(),
12
+ contactId: z.string().min(1).max(64).optional(),
13
+ email: z.string().trim().min(3).max(320).optional(),
14
+ });
15
+ export const RequestSignatureSchema = z.object({
16
+ documentFileId: z.uuid(),
17
+ title: z.string().trim().min(1).max(200),
18
+ level: z.literal(SIGNATURE_LEVEL.Simple).default(SIGNATURE_LEVEL.Simple),
19
+ subjectType: z.string().trim().min(1).max(100),
20
+ subjectId: z.string().trim().min(1).max(100),
21
+ expiresInDays: z.number().int().min(1).max(MAX_VALIDITY_DAYS).optional(),
22
+ signers: z.array(SignerInputSchema).min(1).max(MAX_SIGNERS_PER_REQUEST),
23
+ });
24
+ const ImagePayload = z.string().min(1).max(MAX_IMAGE_BASE64_LENGTH);
25
+ export const SignInPersonSchema = z.object({
26
+ signerId: z.uuid(),
27
+ imagePngBase64: ImagePayload,
28
+ });
29
+ export const SignerIdSchema = z.object({ signerId: z.uuid() });
30
+ export const RequestIdSchema = z.object({ requestId: z.uuid() });
31
+ const TokenPayload = z.string().min(1).max(MAX_TOKEN_LENGTH);
32
+ export const OpenByLinkSchema = z.object({ token: TokenPayload });
33
+ export const SignByLinkSchema = z.object({ token: TokenPayload, imagePngBase64: ImagePayload });
34
+ export const DeclineByLinkSchema = z.object({
35
+ token: TokenPayload,
36
+ reason: z.string().trim().min(1).max(1000).optional(),
37
+ });
38
+ export const FinishSchema = z.object({ requestId: z.uuid(), completedFileId: z.uuid() });
39
+ const OutcomeBase = {
40
+ requestId: z.string().min(1),
41
+ subjectType: z.string().min(1),
42
+ subjectId: z.string().min(1),
43
+ };
44
+ export const SignatureCompletedEventSchema = z.object({
45
+ ...OutcomeBase,
46
+ completedFileId: z.string().min(1),
47
+ signerCount: z.number().int().nonnegative(),
48
+ });
49
+ export const SignatureDeclinedEventSchema = z.object({
50
+ ...OutcomeBase,
51
+ signerId: z.string().min(1),
52
+ });
53
+ export const SignatureExpiredEventSchema = z.object(OutcomeBase);
@@ -0,0 +1,11 @@
1
+ export declare const MAX_SIGNATURE_PNG_BYTES = 300000;
2
+ export type SignaturePngCheck = {
3
+ readonly ok: true;
4
+ readonly width: number;
5
+ readonly height: number;
6
+ } | {
7
+ readonly ok: false;
8
+ readonly reason: string;
9
+ };
10
+ export declare function checkSignaturePng(bytes: Uint8Array): SignaturePngCheck;
11
+ export declare function decodeSignaturePngBase64(base64: string): Uint8Array | null;
@@ -0,0 +1,159 @@
1
+ import { inflateSync } from "node:zlib";
2
+ export const MAX_SIGNATURE_PNG_BYTES = 300_000;
3
+ const MAX_DIMENSION = 3000;
4
+ const MIN_DIMENSION = 16;
5
+ const MAX_PIXELS = 4_000_000;
6
+ const MIN_INK_PIXELS = 20;
7
+ const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
8
+ const COLOR_TYPE_GRAY_ALPHA = 4;
9
+ const COLOR_TYPE_RGBA = 6;
10
+ const BYTES_PER_PIXEL = {
11
+ [COLOR_TYPE_GRAY_ALPHA]: 2,
12
+ [COLOR_TYPE_RGBA]: 4,
13
+ };
14
+ const rejected = (reason) => ({ ok: false, reason });
15
+ function hasPngSignature(bytes) {
16
+ return PNG_SIGNATURE.every((value, index) => bytes[index] === value);
17
+ }
18
+ function readHeader(view) {
19
+ const width = view.getUint32(16);
20
+ const height = view.getUint32(20);
21
+ const bitDepth = view.getUint8(24);
22
+ const colorType = view.getUint8(25);
23
+ const interlace = view.getUint8(28);
24
+ const bytesPerPixel = BYTES_PER_PIXEL[colorType];
25
+ if (bitDepth !== 8 || bytesPerPixel === undefined)
26
+ return "unsupported_pixel_format";
27
+ if (interlace !== 0)
28
+ return "interlaced";
29
+ if (width < MIN_DIMENSION || height < MIN_DIMENSION)
30
+ return "too_small";
31
+ if (width > MAX_DIMENSION || height > MAX_DIMENSION || width * height > MAX_PIXELS) {
32
+ return "too_large";
33
+ }
34
+ return { width, height, bytesPerPixel };
35
+ }
36
+ function collectImageData(bytes, view) {
37
+ const parts = [];
38
+ let offset = 8;
39
+ while (offset + 12 <= bytes.length) {
40
+ const length = view.getUint32(offset);
41
+ const type = String.fromCharCode(...bytes.subarray(offset + 4, offset + 8));
42
+ const dataStart = offset + 8;
43
+ if (dataStart + length + 4 > bytes.length)
44
+ return null;
45
+ if (type === "IDAT")
46
+ parts.push(bytes.subarray(dataStart, dataStart + length));
47
+ if (type === "IEND")
48
+ break;
49
+ offset = dataStart + length + 4;
50
+ }
51
+ if (parts.length === 0)
52
+ return null;
53
+ const joined = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
54
+ let written = 0;
55
+ for (const part of parts) {
56
+ joined.set(part, written);
57
+ written += part.length;
58
+ }
59
+ return joined;
60
+ }
61
+ function paeth(left, up, upLeft) {
62
+ const estimate = left + up - upLeft;
63
+ const distanceLeft = Math.abs(estimate - left);
64
+ const distanceUp = Math.abs(estimate - up);
65
+ const distanceUpLeft = Math.abs(estimate - upLeft);
66
+ if (distanceLeft <= distanceUp && distanceLeft <= distanceUpLeft)
67
+ return left;
68
+ return distanceUp <= distanceUpLeft ? up : upLeft;
69
+ }
70
+ // Reverses one filtered byte; null for an unknown filter type.
71
+ function unfilterByte(filter, current, left, up, upLeft) {
72
+ switch (filter) {
73
+ case 0:
74
+ return current;
75
+ case 1:
76
+ return (current + left) & 0xff;
77
+ case 2:
78
+ return (current + up) & 0xff;
79
+ case 3:
80
+ return (current + ((left + up) >> 1)) & 0xff;
81
+ case 4:
82
+ return (current + paeth(left, up, upLeft)) & 0xff;
83
+ default:
84
+ return null;
85
+ }
86
+ }
87
+ // Reverses the per-row PNG filters in place; returns false for an unknown filter type.
88
+ function unfilterRows(raw, header) {
89
+ const bpp = header.bytesPerPixel;
90
+ const rowBytes = header.width * bpp;
91
+ const stride = rowBytes + 1;
92
+ for (let row = 0; row < header.height; row++) {
93
+ const filter = raw[row * stride];
94
+ const start = row * stride + 1;
95
+ for (let i = 0; i < rowBytes; i++) {
96
+ const left = i >= bpp ? (raw[start + i - bpp] ?? 0) : 0;
97
+ const up = row > 0 ? (raw[start - stride + i] ?? 0) : 0;
98
+ const upLeft = row > 0 && i >= bpp ? (raw[start - stride + i - bpp] ?? 0) : 0;
99
+ const restored = unfilterByte(filter, raw[start + i] ?? 0, left, up, upLeft);
100
+ if (restored === null)
101
+ return false;
102
+ raw[start + i] = restored;
103
+ }
104
+ }
105
+ return true;
106
+ }
107
+ function countInkPixels(raw, header) {
108
+ const stride = header.width * header.bytesPerPixel + 1;
109
+ let ink = 0;
110
+ for (let row = 0; row < header.height; row++) {
111
+ 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)
114
+ ink++;
115
+ }
116
+ }
117
+ return ink;
118
+ }
119
+ // A real PNG with an alpha channel and at least a few drawn pixels. Dimensions and the inflated
120
+ // size are capped before anything is decoded, so a crafted file cannot exhaust memory.
121
+ export function checkSignaturePng(bytes) {
122
+ if (bytes.length > MAX_SIGNATURE_PNG_BYTES)
123
+ return rejected("too_many_bytes");
124
+ if (bytes.length < 33 || !hasPngSignature(bytes))
125
+ return rejected("not_a_png");
126
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
127
+ if (String.fromCharCode(...bytes.subarray(12, 16)) !== "IHDR")
128
+ return rejected("not_a_png");
129
+ const header = readHeader(view);
130
+ if (typeof header === "string")
131
+ return rejected(header);
132
+ const compressed = collectImageData(bytes, view);
133
+ if (compressed === null)
134
+ return rejected("no_image_data");
135
+ const expectedLength = header.height * (header.width * header.bytesPerPixel + 1);
136
+ let raw;
137
+ try {
138
+ raw = new Uint8Array(inflateSync(compressed, { maxOutputLength: expectedLength }));
139
+ }
140
+ catch {
141
+ return rejected("corrupt_image_data");
142
+ }
143
+ if (raw.length !== expectedLength)
144
+ return rejected("corrupt_image_data");
145
+ if (!unfilterRows(raw, header))
146
+ return rejected("corrupt_image_data");
147
+ if (countInkPixels(raw, header) < MIN_INK_PIXELS)
148
+ return rejected("empty");
149
+ return { ok: true, width: header.width, height: header.height };
150
+ }
151
+ const BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
152
+ // The image arrives as base64 inside the JSON payload; the cap keeps the decode bounded.
153
+ export function decodeSignaturePngBase64(base64) {
154
+ if (base64.length > Math.ceil((MAX_SIGNATURE_PNG_BYTES * 4) / 3) + 4)
155
+ return null;
156
+ if (!BASE64_PATTERN.test(base64))
157
+ return null;
158
+ return new Uint8Array(Buffer.from(base64, "base64"));
159
+ }
@@ -0,0 +1,3 @@
1
+ import { type EntityListScreenDefinition, type ProjectionDetailScreenDefinition } from "@cosmicdrift/kumiko-framework/engine";
2
+ export declare function createSignatureListScreen(access: EntityListScreenDefinition["access"]): EntityListScreenDefinition;
3
+ export declare function createSignatureDetailScreen(access: ProjectionDetailScreenDefinition["access"]): ProjectionDetailScreenDefinition;
@@ -0,0 +1,95 @@
1
+ import { i18nKey, } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { SIGNATURE_REQUEST_ENTITY, SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_ENTITY, SIGNATURE_SIGNER_STATUS, SignatureHandlers, SignatureQueries, } from "./web/constants.js";
3
+ const REQUEST = `signature:entity:${SIGNATURE_REQUEST_ENTITY}:field`;
4
+ const UNSIGNED_SIGNER = {
5
+ field: "status",
6
+ in: [SIGNATURE_SIGNER_STATUS.Pending, SIGNATURE_SIGNER_STATUS.Viewed],
7
+ };
8
+ const CANCEL_ACTION = {
9
+ id: "cancel",
10
+ label: i18nKey("signature.action.cancel"),
11
+ handler: SignatureHandlers.cancel,
12
+ payload: { map: { requestId: "id" } },
13
+ confirm: i18nKey("signature.action.cancel.confirm"),
14
+ style: "danger",
15
+ visible: { field: "status", eq: SIGNATURE_REQUEST_STATUS.Open },
16
+ };
17
+ export function createSignatureListScreen(access) {
18
+ return {
19
+ id: "signature-list",
20
+ type: "entityList",
21
+ entity: SIGNATURE_REQUEST_ENTITY,
22
+ columns: [
23
+ "title",
24
+ "status",
25
+ "subjectType",
26
+ { field: "expiresAt", hideOnNarrow: true },
27
+ { field: "completedAt", hideOnNarrow: true },
28
+ ],
29
+ defaultSort: { field: "expiresAt", dir: "desc" },
30
+ access,
31
+ searchable: true,
32
+ rowActions: [
33
+ {
34
+ kind: "navigate",
35
+ id: "open",
36
+ label: i18nKey("signature.action.open"),
37
+ screen: "signature-detail",
38
+ entityId: "id",
39
+ rowClick: true,
40
+ },
41
+ CANCEL_ACTION,
42
+ ],
43
+ };
44
+ }
45
+ // Signing in person needs the drawing pad, which a declarative screen cannot host: the app mounts
46
+ // SignaturePad on its own screen and calls sign-in-person.
47
+ export function createSignatureDetailScreen(access) {
48
+ return {
49
+ id: "signature-detail",
50
+ type: "projectionDetail",
51
+ dormant: true,
52
+ listScreenId: "signature-list",
53
+ query: SignatureQueries.detail,
54
+ access,
55
+ header: { title: "title", status: "status" },
56
+ fieldLabels: {
57
+ status: i18nKey(`${REQUEST}:status`),
58
+ subjectType: i18nKey(`${REQUEST}:subjectType`),
59
+ expiresAt: i18nKey(`${REQUEST}:expiresAt`),
60
+ completedAt: i18nKey(`${REQUEST}:completedAt`),
61
+ },
62
+ actions: [CANCEL_ACTION],
63
+ layout: {
64
+ sections: [
65
+ { fields: ["status", "subjectType", "expiresAt", "completedAt"] },
66
+ {
67
+ kind: "relatedList",
68
+ title: i18nKey("signature.signers.title"),
69
+ query: SignatureQueries.signerList,
70
+ parentFilter: { field: "requestId" },
71
+ entity: SIGNATURE_SIGNER_ENTITY,
72
+ columns: ["name", "role", "status", "method", { field: "signedAt", hideOnNarrow: true }],
73
+ rowActions: [
74
+ {
75
+ id: "issue-link",
76
+ label: i18nKey("signature.action.issueLink"),
77
+ handler: SignatureHandlers.issueLink,
78
+ payload: { map: { signerId: "id" } },
79
+ visible: UNSIGNED_SIGNER,
80
+ },
81
+ {
82
+ id: "revoke-link",
83
+ label: i18nKey("signature.action.revokeLink"),
84
+ handler: SignatureHandlers.revokeLink,
85
+ payload: { map: { signerId: "id" } },
86
+ confirm: i18nKey("signature.action.revokeLink.confirm"),
87
+ style: "danger",
88
+ visible: UNSIGNED_SIGNER,
89
+ },
90
+ ],
91
+ },
92
+ ],
93
+ },
94
+ };
95
+ }
@@ -0,0 +1,25 @@
1
+ import { type SignatureMethod } from "./web/constants.ts";
2
+ export type SignaturePageLabels = {
3
+ readonly heading: string;
4
+ readonly documentHash: string;
5
+ readonly signedAt: string;
6
+ readonly inPerson: string;
7
+ readonly link: string;
8
+ readonly noRole: string;
9
+ };
10
+ export declare const DEFAULT_SIGNATURE_PAGE_LABELS: SignaturePageLabels;
11
+ export type SignaturePageEntry = {
12
+ readonly name: string;
13
+ readonly role: string | null;
14
+ readonly signedAtIso: string;
15
+ readonly method: SignatureMethod;
16
+ readonly imagePng: Uint8Array;
17
+ };
18
+ export declare function escapeHtml(value: string): string;
19
+ export declare function buildSignaturePageHtml(args: {
20
+ readonly title: string;
21
+ readonly documentSha256: string;
22
+ readonly entries: readonly SignaturePageEntry[];
23
+ readonly labels: SignaturePageLabels;
24
+ }): string;
25
+ export declare function appendPdfPages(original: Uint8Array, appendix: Uint8Array): Promise<Uint8Array>;
@@ -0,0 +1,62 @@
1
+ import { PDFDocument } from "pdf-lib";
2
+ import { SIGNATURE_METHOD } from "./web/constants.js";
3
+ export const DEFAULT_SIGNATURE_PAGE_LABELS = {
4
+ heading: "Signature page",
5
+ documentHash: "SHA-256 of the original document",
6
+ signedAt: "Signed",
7
+ inPerson: "In person",
8
+ link: "By link",
9
+ noRole: "",
10
+ };
11
+ const HTML_ESCAPES = {
12
+ "&": "&amp;",
13
+ "<": "&lt;",
14
+ ">": "&gt;",
15
+ '"': "&quot;",
16
+ "'": "&#39;",
17
+ };
18
+ // Names and titles are free text typed by users; they reach Chromium as HTML, so every value is escaped.
19
+ export function escapeHtml(value) {
20
+ return value.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char);
21
+ }
22
+ function imageDataUri(png) {
23
+ return `data:image/png;base64,${Buffer.from(png).toString("base64")}`;
24
+ }
25
+ function entryHtml(entry, labels) {
26
+ const way = entry.method === SIGNATURE_METHOD.InPerson ? labels.inPerson : labels.link;
27
+ const role = entry.role === null ? labels.noRole : entry.role;
28
+ return `<section class="entry">
29
+ <img src="${escapeHtml(imageDataUri(entry.imagePng))}" alt="">
30
+ <div class="meta">
31
+ <strong>${escapeHtml(entry.name)}</strong>
32
+ ${role === "" ? "" : `<span>${escapeHtml(role)}</span>`}
33
+ <span>${escapeHtml(labels.signedAt)}: ${escapeHtml(entry.signedAtIso)} (${escapeHtml(way)})</span>
34
+ </div>
35
+ </section>`;
36
+ }
37
+ export function buildSignaturePageHtml(args) {
38
+ return `<!doctype html>
39
+ <html><head><meta charset="utf-8"><style>
40
+ body { font-family: sans-serif; font-size: 12px; color: #111; margin: 0; }
41
+ h1 { font-size: 20px; margin: 0 0 4px; }
42
+ h2 { font-size: 14px; font-weight: normal; margin: 0 0 24px; }
43
+ .entry { display: flex; align-items: center; gap: 24px; border-top: 1px solid #ccc; padding: 12px 0; page-break-inside: avoid; }
44
+ .entry img { width: 220px; height: 90px; object-fit: contain; }
45
+ .meta { display: flex; flex-direction: column; gap: 2px; }
46
+ .hash { margin-top: 24px; font-family: monospace; font-size: 10px; word-break: break-all; }
47
+ </style></head><body>
48
+ <h1>${escapeHtml(args.labels.heading)}</h1>
49
+ <h2>${escapeHtml(args.title)}</h2>
50
+ ${args.entries.map((entry) => entryHtml(entry, args.labels)).join("\n")}
51
+ <p class="hash">${escapeHtml(args.labels.documentHash)}: ${escapeHtml(args.documentSha256)}</p>
52
+ </body></html>`;
53
+ }
54
+ // The original pages are copied as they are; the signature pages only get appended.
55
+ export async function appendPdfPages(original, appendix) {
56
+ const merged = await PDFDocument.load(original);
57
+ const extra = await PDFDocument.load(appendix);
58
+ const pages = await merged.copyPages(extra, extra.getPageIndices());
59
+ for (const page of pages)
60
+ merged.addPage(page);
61
+ return merged.save();
62
+ }
@@ -0,0 +1,19 @@
1
+ import type { TenantDb } from "@cosmicdrift/kumiko-framework/db";
2
+ import type { SessionUser } from "@cosmicdrift/kumiko-framework/engine";
3
+ import type { Temporal } from "@cosmicdrift/kumiko-types/temporal";
4
+ import { type GeneratedFileContext } from "./files.ts";
5
+ import { type SignerRow } from "./lib.ts";
6
+ import { type SignatureMethod } from "./web/constants.ts";
7
+ export declare function invalidImage(): import("@cosmicdrift/kumiko-types/write-error-info-types").WriteFailure;
8
+ export declare function decodeSignatureImage(imagePngBase64: string): Uint8Array | null;
9
+ export declare function auditValuesOfRequest(): Record<string, string>;
10
+ export type SignatureWrite = {
11
+ readonly method: SignatureMethod;
12
+ readonly imageFileId: string;
13
+ readonly signedAt: Temporal.Instant;
14
+ };
15
+ export declare function signatureChanges(write: SignatureWrite): Record<string, unknown>;
16
+ export declare function storeSignatureImage(ctx: GeneratedFileContext, user: SessionUser, png: Uint8Array): Promise<import("@cosmicdrift/kumiko-types/handlers").WriteResult<import("@cosmicdrift/kumiko-framework/files").CreatedFileRef>>;
17
+ export declare function recordInPersonSignature(ctx: {
18
+ readonly db: TenantDb;
19
+ }, user: SessionUser, signer: SignerRow, write: SignatureWrite): Promise<import("@cosmicdrift/kumiko-types/handlers").WriteResult<import("@cosmicdrift/kumiko-types/hooks").SaveContext>>;
@@ -0,0 +1,46 @@
1
+ import { requestContext } from "@cosmicdrift/kumiko-framework/api";
2
+ import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import { signerExecutor } from "./entity.js";
4
+ import { storeGeneratedFile } from "./files.js";
5
+ import { versionOf } from "./lib.js";
6
+ import { checkSignaturePng, decodeSignaturePngBase64 } from "./png.js";
7
+ import { SIGNATURE_INVALID_IMAGE_REASON, SIGNATURE_SIGNER_STATUS, } from "./web/constants.js";
8
+ export function invalidImage() {
9
+ return writeFailure(new UnprocessableError(SIGNATURE_INVALID_IMAGE_REASON));
10
+ }
11
+ export function decodeSignatureImage(imagePngBase64) {
12
+ const bytes = decodeSignaturePngBase64(imagePngBase64);
13
+ if (bytes === null)
14
+ return null;
15
+ return checkSignaturePng(bytes).ok ? bytes : null;
16
+ }
17
+ // IP and user agent come from the HTTP request, not from the payload, so a client cannot choose them.
18
+ export function auditValuesOfRequest() {
19
+ const scope = requestContext.get();
20
+ return {
21
+ ...(scope?.ip !== undefined && { signedFromIp: scope.ip }),
22
+ ...(scope?.userAgent !== undefined && { signedUserAgent: scope.userAgent }),
23
+ };
24
+ }
25
+ export function signatureChanges(write) {
26
+ return {
27
+ status: SIGNATURE_SIGNER_STATUS.Signed,
28
+ method: write.method,
29
+ signedAt: write.signedAt,
30
+ imageFileId: write.imageFileId,
31
+ linkAnchor: null,
32
+ ...auditValuesOfRequest(),
33
+ };
34
+ }
35
+ export async function storeSignatureImage(ctx, user, png) {
36
+ return storeGeneratedFile(ctx, user, {
37
+ fileName: "signature.png",
38
+ mimeType: "image/png",
39
+ data: png,
40
+ });
41
+ }
42
+ // Records the signature of an in-person signer. A concurrent change of the row makes the executor
43
+ // refuse the stale version, so a double submit signs once.
44
+ export function recordInPersonSignature(ctx, user, signer, write) {
45
+ return signerExecutor.update({ id: signer.id, version: versionOf(signer), changes: signatureChanges(write) }, user, ctx.db);
46
+ }
@@ -0,0 +1,17 @@
1
+ import { type StaticRequestOptions, type StaticResult } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
2
+ export { hrefWithoutUrlToken, readUrlToken, STATIC_NETWORK_REASON, STATIC_RATE_LIMITED_REASON, type StaticFailure, type StaticRequestOptions, type StaticResult, type StaticSuccess, } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
3
+ export { bytesToBase64, createSignaturePad, type SignaturePad, type SignaturePadCanvas, type SignaturePadOptions, } from "./web/pad.ts";
4
+ export type SignatureLinkView = {
5
+ readonly title: string;
6
+ readonly signerName: string;
7
+ readonly role: string | null;
8
+ /** Short-lived URL of the PDF; null when the storage provider cannot sign URLs. */
9
+ readonly documentUrl: string | null;
10
+ };
11
+ /** Reads `#token=` from the current page and removes it from the address bar. Browser only. */
12
+ export declare function takeSignatureToken(): string;
13
+ /** Counts a view but does not use up the link. A bad, used or expired link fails with `invalid_or_expired_link`. */
14
+ export declare function openSignatureLink(token: string, options?: StaticRequestOptions): Promise<StaticResult<SignatureLinkView>>;
15
+ /** `imagePngBase64` comes from `SignaturePad.toPngBase64()`. Uses up the link on success. */
16
+ export declare function signByLink(token: string, imagePngBase64: string, options?: StaticRequestOptions): Promise<StaticResult<undefined>>;
17
+ export declare function declineByLink(token: string, reason?: string, options?: StaticRequestOptions): Promise<StaticResult<undefined>>;
@@ -0,0 +1,44 @@
1
+ // DOM-free signing page for static sites: fetch, canvas and Pointer Events only, no React. The link
2
+ // a signer receives carries the token in the URL fragment (`#token=`), which browsers never send to a
3
+ // server or in a Referer.
4
+ import { dispatchWrite, staticFailure, staticSuccess, takeUrlToken, } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
5
+ import { SignatureHandlers } from "./web/constants.js";
6
+ export { hrefWithoutUrlToken, readUrlToken, STATIC_NETWORK_REASON, STATIC_RATE_LIMITED_REASON, } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
7
+ export { bytesToBase64, createSignaturePad, } from "./web/pad.js";
8
+ /** Reads `#token=` from the current page and removes it from the address bar. Browser only. */
9
+ export function takeSignatureToken() {
10
+ return takeUrlToken("fragment");
11
+ }
12
+ function isRecord(value) {
13
+ return typeof value === "object" && value !== null;
14
+ }
15
+ function parseLinkView(data) {
16
+ if (!isRecord(data))
17
+ return null;
18
+ const { title, signerName, role, documentUrl } = data;
19
+ if (typeof title !== "string" || typeof signerName !== "string")
20
+ return null;
21
+ return {
22
+ title,
23
+ signerName,
24
+ role: typeof role === "string" ? role : null,
25
+ documentUrl: typeof documentUrl === "string" ? documentUrl : null,
26
+ };
27
+ }
28
+ /** Counts a view but does not use up the link. A bad, used or expired link fails with `invalid_or_expired_link`. */
29
+ export async function openSignatureLink(token, options) {
30
+ const result = await dispatchWrite(SignatureHandlers.openByLink, { token }, options);
31
+ if (result.kind !== "success")
32
+ return result;
33
+ const view = parseLinkView(result.data);
34
+ return view === null ? staticFailure("unknown") : staticSuccess(view);
35
+ }
36
+ /** `imagePngBase64` comes from `SignaturePad.toPngBase64()`. Uses up the link on success. */
37
+ export async function signByLink(token, imagePngBase64, options) {
38
+ const result = await dispatchWrite(SignatureHandlers.signByLink, { token, imagePngBase64 }, options);
39
+ return result.kind === "success" ? staticSuccess(undefined) : result;
40
+ }
41
+ export async function declineByLink(token, reason, options) {
42
+ const result = await dispatchWrite(SignatureHandlers.declineByLink, { token, ...(reason !== undefined && reason !== "" && { reason }) }, options);
43
+ return result.kind === "success" ? staticSuccess(undefined) : result;
44
+ }
@@ -0,0 +1,3 @@
1
+ import type { JobContext } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { SignatureOptions } from "./options.ts";
3
+ export declare function sweepSignatureRequests(ctx: JobContext, opts: SignatureOptions): Promise<void>;