@cosmicdrift/kumiko-bundled-features 0.415.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 (82) 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/channel-whatsapp/constants.d.ts +1 -0
  4. package/dist/channel-whatsapp/constants.js +1 -0
  5. package/dist/channel-whatsapp/graph-client.d.ts +2 -0
  6. package/dist/channel-whatsapp/graph-client.js +29 -2
  7. package/dist/handbook-knowledge/constants.d.ts +6 -0
  8. package/dist/handbook-knowledge/constants.js +6 -0
  9. package/dist/handbook-knowledge/feature.d.ts +9 -0
  10. package/dist/handbook-knowledge/feature.js +17 -0
  11. package/dist/handbook-knowledge/handbook-index.d.ts +26 -0
  12. package/dist/handbook-knowledge/handbook-index.js +51 -0
  13. package/dist/handbook-knowledge/handlers.d.ts +28 -0
  14. package/dist/handbook-knowledge/handlers.js +67 -0
  15. package/dist/handbook-knowledge/index.d.ts +3 -0
  16. package/dist/handbook-knowledge/index.js +2 -0
  17. package/dist/signature/entity.d.ts +552 -0
  18. package/dist/signature/entity.js +156 -0
  19. package/dist/signature/feature.d.ts +3 -0
  20. package/dist/signature/feature.js +91 -0
  21. package/dist/signature/files.d.ts +23 -0
  22. package/dist/signature/files.js +64 -0
  23. package/dist/signature/grant.d.ts +32 -0
  24. package/dist/signature/grant.js +44 -0
  25. package/dist/signature/handlers/anonymous.write.d.ts +14 -0
  26. package/dist/signature/handlers/anonymous.write.js +52 -0
  27. package/dist/signature/handlers/cancel.write.d.ts +6 -0
  28. package/dist/signature/handlers/cancel.write.js +30 -0
  29. package/dist/signature/handlers/issue-link.write.d.ts +9 -0
  30. package/dist/signature/handlers/issue-link.write.js +57 -0
  31. package/dist/signature/handlers/lifecycle.write.d.ts +16 -0
  32. package/dist/signature/handlers/lifecycle.write.js +70 -0
  33. package/dist/signature/handlers/link-internal.write.d.ts +23 -0
  34. package/dist/signature/handlers/link-internal.write.js +186 -0
  35. package/dist/signature/handlers/request.write.d.ts +19 -0
  36. package/dist/signature/handlers/request.write.js +67 -0
  37. package/dist/signature/handlers/revoke-link.write.d.ts +6 -0
  38. package/dist/signature/handlers/revoke-link.write.js +18 -0
  39. package/dist/signature/handlers/sign-in-person.write.d.ts +8 -0
  40. package/dist/signature/handlers/sign-in-person.write.js +52 -0
  41. package/dist/signature/i18n.d.ts +6 -0
  42. package/dist/signature/i18n.js +49 -0
  43. package/dist/signature/index.d.ts +5 -0
  44. package/dist/signature/index.js +2 -0
  45. package/dist/signature/lib.d.ts +54 -0
  46. package/dist/signature/lib.js +68 -0
  47. package/dist/signature/options.d.ts +31 -0
  48. package/dist/signature/options.js +5 -0
  49. package/dist/signature/payloads.d.ts +60 -0
  50. package/dist/signature/payloads.js +53 -0
  51. package/dist/signature/png.d.ts +11 -0
  52. package/dist/signature/png.js +159 -0
  53. package/dist/signature/screens.d.ts +3 -0
  54. package/dist/signature/screens.js +95 -0
  55. package/dist/signature/signature-page.d.ts +25 -0
  56. package/dist/signature/signature-page.js +62 -0
  57. package/dist/signature/signing.d.ts +19 -0
  58. package/dist/signature/signing.js +46 -0
  59. package/dist/signature/static-sign.d.ts +17 -0
  60. package/dist/signature/static-sign.js +44 -0
  61. package/dist/signature/sweep.d.ts +3 -0
  62. package/dist/signature/sweep.js +113 -0
  63. package/dist/signature/user-data.d.ts +3 -0
  64. package/dist/signature/user-data.js +135 -0
  65. package/dist/signature/web/constants.d.ts +69 -0
  66. package/dist/signature/web/constants.js +68 -0
  67. package/dist/signature/web/index.d.ts +3 -0
  68. package/dist/signature/web/index.js +2 -0
  69. package/dist/signature/web/pad.d.ts +20 -0
  70. package/dist/signature/web/pad.js +104 -0
  71. package/dist/signature/web/signature-pad.d.ts +19 -0
  72. package/dist/signature/web/signature-pad.js +36 -0
  73. package/dist/subscription-stripe/feature.d.ts +6 -0
  74. package/dist/subscription-stripe/feature.js +3 -0
  75. package/dist/subscription-stripe/plugin-methods.d.ts +3 -1
  76. package/dist/subscription-stripe/plugin-methods.js +2 -1
  77. package/package.json +43 -11
  78. package/src/agent-tools/changes.json +6 -0
  79. package/src/channel-whatsapp/changes.json +6 -0
  80. package/src/handbook-knowledge/changes.json +8 -0
  81. package/src/signature/changes.json +15 -0
  82. package/src/subscription-stripe/changes.json +6 -0
@@ -0,0 +1,70 @@
1
+ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { requestExecutor } from "../entity.js";
3
+ import { advanceIfAllSigned, appendOutcomeEvent, internalAccess, isPastInstant, listSigners, setRequestStatus, } from "../lib.js";
4
+ import { FinishSchema, RequestIdSchema } from "../payloads.js";
5
+ import { SIGNATURE_REQUEST_STATUS, SignatureEvents } from "../web/constants.js";
6
+ // The writes of the sweep job. They run as handlers because a job may only append its own
7
+ // events through ctx.events, and every transition here must also hold the "exactly once" precondition.
8
+ export const finishHandler = defineWriteHandler({
9
+ name: "finish",
10
+ schema: FinishSchema,
11
+ access: internalAccess,
12
+ agent: { expose: false },
13
+ description: "Internal: marks an all-signed request completed with its final PDF and emits the completed event once.",
14
+ handler: async (event, ctx) => {
15
+ const request = await requestExecutor.detail({ id: event.payload.requestId }, event.user, ctx.db);
16
+ if (request === null)
17
+ return { isSuccess: true, data: { finished: false } };
18
+ const moved = await setRequestStatus(ctx, event.user, request.id, SIGNATURE_REQUEST_STATUS.AllSigned, {
19
+ status: SIGNATURE_REQUEST_STATUS.Completed,
20
+ completedFileId: event.payload.completedFileId,
21
+ completedAt: ctx.tz.now(),
22
+ });
23
+ if (!moved.isSuccess)
24
+ return { isSuccess: true, data: { finished: false } };
25
+ const signers = await listSigners(ctx, event.user, request.id);
26
+ await appendOutcomeEvent(ctx, SignatureEvents.completed, {
27
+ requestId: request.id,
28
+ subjectType: request.subjectType,
29
+ subjectId: request.subjectId,
30
+ completedFileId: event.payload.completedFileId,
31
+ signerCount: signers.length,
32
+ });
33
+ return { isSuccess: true, data: { finished: true } };
34
+ },
35
+ });
36
+ export const expireHandler = defineWriteHandler({
37
+ name: "expire",
38
+ schema: RequestIdSchema,
39
+ access: internalAccess,
40
+ agent: { expose: false },
41
+ description: "Internal: expires an open request whose deadline has passed and emits the expired event once.",
42
+ handler: async (event, ctx) => {
43
+ const request = await requestExecutor.detail({ id: event.payload.requestId }, event.user, ctx.db);
44
+ if (request === null || !isPastInstant(request.expiresAt, ctx.tz.now())) {
45
+ return { isSuccess: true, data: { expired: false } };
46
+ }
47
+ const moved = await setRequestStatus(ctx, event.user, request.id, SIGNATURE_REQUEST_STATUS.Open, { status: SIGNATURE_REQUEST_STATUS.Expired });
48
+ if (!moved.isSuccess)
49
+ return { isSuccess: true, data: { expired: false } };
50
+ await appendOutcomeEvent(ctx, SignatureEvents.expired, {
51
+ requestId: request.id,
52
+ subjectType: request.subjectType,
53
+ subjectId: request.subjectId,
54
+ });
55
+ return { isSuccess: true, data: { expired: true } };
56
+ },
57
+ });
58
+ // Two last signers committing at the same moment can each still see the other as unsigned; the
59
+ // sweep repeats the check so such a request cannot stay open for good.
60
+ export const reconcileHandler = defineWriteHandler({
61
+ name: "reconcile",
62
+ schema: RequestIdSchema,
63
+ access: internalAccess,
64
+ agent: { expose: false },
65
+ description: "Internal: moves an open request whose signers have all signed to all-signed.",
66
+ handler: async (event, ctx) => ({
67
+ isSuccess: true,
68
+ data: { advanced: await advanceIfAllSigned(ctx, event.user, event.payload.requestId) },
69
+ }),
70
+ });
@@ -0,0 +1,23 @@
1
+ export type LinkOpenData = {
2
+ readonly title: string;
3
+ readonly signerName: string;
4
+ readonly role: string | null;
5
+ readonly documentUrl: string | null;
6
+ };
7
+ export declare function createLinkInternalHandlers(linkSecret: string): {
8
+ linkOpen: import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"link-open", import("zod").ZodObject<{
9
+ token: import("zod").ZodString;
10
+ }, import("zod/v4/core").$strip>, LinkOpenData, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
11
+ linkSign: import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"link-sign", import("zod").ZodObject<{
12
+ token: import("zod").ZodString;
13
+ imagePngBase64: import("zod").ZodString;
14
+ }, import("zod/v4/core").$strip>, {
15
+ readonly requestStatus: string;
16
+ }, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
17
+ linkDecline: import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"link-decline", import("zod").ZodObject<{
18
+ token: import("zod").ZodString;
19
+ reason: import("zod").ZodOptional<import("zod").ZodString>;
20
+ }, import("zod/v4/core").$strip>, {
21
+ readonly declined: true;
22
+ }, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
23
+ };
@@ -0,0 +1,186 @@
1
+ import { defineWriteHandler, } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { signerExecutor } from "../entity.js";
3
+ import { discardGeneratedFile, signedDocumentUrl } from "../files.js";
4
+ import { parseSignatureLinkSubject, redeemSignatureLinkToken } from "../grant.js";
5
+ import { advanceIfAllSigned, appendOutcomeEvent, internalAccess, invalidLink, isOpenRequest, isUnsignedSigner, loadRequestOfSigner, setRequestStatus, } from "../lib.js";
6
+ import { DeclineByLinkSchema, OpenByLinkSchema, SignByLinkSchema } from "../payloads.js";
7
+ import { auditValuesOfRequest, decodeSignatureImage, invalidImage, signatureChanges, storeSignatureImage, } from "../signing.js";
8
+ import { SIGNATURE_MAX_LINK_OPENS, SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_STATUS, SignatureEvents, } from "../web/constants.js";
9
+ const NO_CONSUME_REASON = "opening a link only shows the document and counts the view; signing and declining consume the link";
10
+ // Anchor of a signer whose link may still act: unsigned, request open, link not revoked.
11
+ async function loadLiveTarget(ctx, user, signerId, now) {
12
+ const signer = await signerExecutor.detail({ id: signerId }, user, ctx.db);
13
+ if (signer === null || !isUnsignedSigner(signer) || typeof signer.linkAnchor !== "string") {
14
+ return null;
15
+ }
16
+ const request = await loadRequestOfSigner(ctx, user, signer);
17
+ return request !== null && isOpenRequest(request, now) ? { signer, request } : null;
18
+ }
19
+ function viewCountOf(signer) {
20
+ return typeof signer.viewCount === "number" ? signer.viewCount : 0;
21
+ }
22
+ function viewChanges(signer, now) {
23
+ return {
24
+ viewCount: viewCountOf(signer) + 1,
25
+ viewedAt: now,
26
+ ...(signer.status === SIGNATURE_SIGNER_STATUS.Pending && {
27
+ status: SIGNATURE_SIGNER_STATUS.Viewed,
28
+ }),
29
+ };
30
+ }
31
+ export function createLinkInternalHandlers(linkSecret) {
32
+ const linkOpen = defineWriteHandler({
33
+ name: "link-open",
34
+ schema: OpenByLinkSchema,
35
+ access: internalAccess,
36
+ agent: { expose: false },
37
+ description: "Internal: verifies a signing link inside the request's tenant, counts the view and returns what the signing page shows. Reached only through open-by-link.",
38
+ handler: async (event, ctx) => {
39
+ const user = event.user;
40
+ const now = ctx.tz.now();
41
+ const found = { target: null };
42
+ const redeemed = await redeemSignatureLinkToken({
43
+ token: event.payload.token,
44
+ secret: linkSecret,
45
+ now,
46
+ loadLinkAnchor: async (signerId) => {
47
+ const target = await loadLiveTarget(ctx, user, signerId, now);
48
+ if (target === null || viewCountOf(target.signer) >= SIGNATURE_MAX_LINK_OPENS)
49
+ return null;
50
+ found.target = target;
51
+ return typeof target.signer.linkAnchor === "string" ? target.signer.linkAnchor : null;
52
+ },
53
+ commitAnchor: { unsafeSkip: { reason: NO_CONSUME_REASON } },
54
+ });
55
+ const target = found.target;
56
+ if (!redeemed.ok || target === null)
57
+ return invalidLink();
58
+ // A concurrent sign must never be overwritten by the view count, and two simultaneous opens
59
+ // must not both pass the open limit, so status and view count are preconditions.
60
+ const counted = await signerExecutor.update({ id: target.signer.id, changes: viewChanges(target.signer, now) }, user, ctx.db, {
61
+ skipOptimisticLock: true,
62
+ expect: { status: target.signer.status, viewCount: viewCountOf(target.signer) },
63
+ });
64
+ if (!counted.isSuccess)
65
+ return invalidLink();
66
+ return {
67
+ isSuccess: true,
68
+ data: {
69
+ title: target.request.title,
70
+ signerName: target.signer.name,
71
+ role: target.signer.role ?? null,
72
+ documentUrl: await signedDocumentUrl(ctx, user, target.request.documentFileId),
73
+ },
74
+ };
75
+ },
76
+ });
77
+ const linkSign = defineWriteHandler({
78
+ name: "link-sign",
79
+ schema: SignByLinkSchema,
80
+ access: internalAccess,
81
+ agent: { expose: false },
82
+ description: "Internal: verifies a signing link inside the request's tenant and records the signature exactly once; of two simultaneous submits one wins. Reached only through sign-by-link.",
83
+ handler: async (event, ctx) => {
84
+ const user = event.user;
85
+ const now = ctx.tz.now();
86
+ const png = decodeSignatureImage(event.payload.imagePngBase64);
87
+ if (png === null)
88
+ return invalidImage();
89
+ const found = { target: null };
90
+ const redeemed = await redeemSignatureLinkToken({
91
+ token: event.payload.token,
92
+ secret: linkSecret,
93
+ now,
94
+ loadLinkAnchor: async (signerId) => {
95
+ found.target = await loadLiveTarget(ctx, user, signerId, now);
96
+ const anchor = found.target?.signer.linkAnchor;
97
+ return typeof anchor === "string" ? anchor : null;
98
+ },
99
+ // Spends the anchor and writes the signature in one conditional update, so exactly one of
100
+ // two simultaneous submits passes.
101
+ commitAnchor: async (subject, expectedAnchor) => {
102
+ const parsed = parseSignatureLinkSubject(subject);
103
+ if (parsed === null)
104
+ return false;
105
+ const image = await storeSignatureImage(ctx, user, png);
106
+ if (!image.isSuccess)
107
+ return false;
108
+ const signed = await signerExecutor.update({
109
+ id: parsed.signerId,
110
+ changes: signatureChanges({
111
+ method: SIGNATURE_METHOD.Link,
112
+ imageFileId: image.data.id,
113
+ signedAt: now,
114
+ }),
115
+ }, user, ctx.db, { skipOptimisticLock: true, expect: { linkAnchor: expectedAnchor } });
116
+ if (!signed.isSuccess)
117
+ await discardGeneratedFile(ctx, user, image.data);
118
+ return signed.isSuccess;
119
+ },
120
+ });
121
+ const target = found.target;
122
+ if (!redeemed.ok || target === null)
123
+ return invalidLink();
124
+ const allSigned = await advanceIfAllSigned(ctx, user, target.request.id);
125
+ return {
126
+ isSuccess: true,
127
+ data: {
128
+ requestStatus: allSigned
129
+ ? SIGNATURE_REQUEST_STATUS.AllSigned
130
+ : SIGNATURE_REQUEST_STATUS.Open,
131
+ },
132
+ };
133
+ },
134
+ });
135
+ const linkDecline = defineWriteHandler({
136
+ name: "link-decline",
137
+ schema: DeclineByLinkSchema,
138
+ access: internalAccess,
139
+ agent: { expose: false },
140
+ description: "Internal: verifies a signing link inside the request's tenant, records the refusal exactly once and moves the request to declined. Reached only through decline-by-link.",
141
+ handler: async (event, ctx) => {
142
+ const user = event.user;
143
+ const now = ctx.tz.now();
144
+ const found = { target: null };
145
+ const redeemed = await redeemSignatureLinkToken({
146
+ token: event.payload.token,
147
+ secret: linkSecret,
148
+ now,
149
+ loadLinkAnchor: async (signerId) => {
150
+ found.target = await loadLiveTarget(ctx, user, signerId, now);
151
+ const anchor = found.target?.signer.linkAnchor;
152
+ return typeof anchor === "string" ? anchor : null;
153
+ },
154
+ commitAnchor: async (subject, expectedAnchor) => {
155
+ const parsed = parseSignatureLinkSubject(subject);
156
+ if (parsed === null)
157
+ return false;
158
+ const declined = await signerExecutor.update({
159
+ id: parsed.signerId,
160
+ changes: {
161
+ status: SIGNATURE_SIGNER_STATUS.Declined,
162
+ linkAnchor: null,
163
+ ...(event.payload.reason !== undefined && { declineReason: event.payload.reason }),
164
+ ...auditValuesOfRequest(),
165
+ },
166
+ }, user, ctx.db, { skipOptimisticLock: true, expect: { linkAnchor: expectedAnchor } });
167
+ return declined.isSuccess;
168
+ },
169
+ });
170
+ const target = found.target;
171
+ if (!redeemed.ok || target === null)
172
+ return invalidLink();
173
+ const moved = await setRequestStatus(ctx, user, target.request.id, SIGNATURE_REQUEST_STATUS.Open, { status: SIGNATURE_REQUEST_STATUS.Declined });
174
+ if (moved.isSuccess) {
175
+ await appendOutcomeEvent(ctx, SignatureEvents.declined, {
176
+ requestId: target.request.id,
177
+ subjectType: target.request.subjectType,
178
+ subjectId: target.request.subjectId,
179
+ signerId: target.signer.id,
180
+ });
181
+ }
182
+ return { isSuccess: true, data: { declined: true } };
183
+ },
184
+ });
185
+ return { linkOpen, linkSign, linkDecline };
186
+ }
@@ -0,0 +1,19 @@
1
+ import { type AccessRule } from "@cosmicdrift/kumiko-framework/engine";
2
+ export type RequestSignatureData = {
3
+ readonly requestId: string;
4
+ readonly signerIds: readonly string[];
5
+ };
6
+ export declare function createRequestHandler(access: AccessRule): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"request", import("zod").ZodObject<{
7
+ documentFileId: import("zod").ZodUUID;
8
+ title: import("zod").ZodString;
9
+ level: import("zod").ZodDefault<import("zod").ZodLiteral<"simple">>;
10
+ subjectType: import("zod").ZodString;
11
+ subjectId: import("zod").ZodString;
12
+ expiresInDays: import("zod").ZodOptional<import("zod").ZodNumber>;
13
+ signers: import("zod").ZodArray<import("zod").ZodObject<{
14
+ name: import("zod").ZodString;
15
+ role: import("zod").ZodOptional<import("zod").ZodString>;
16
+ contactId: import("zod").ZodOptional<import("zod").ZodString>;
17
+ email: import("zod").ZodOptional<import("zod").ZodString>;
18
+ }, import("zod/v4/core").$strip>>;
19
+ }, import("zod/v4/core").$strip>, RequestSignatureData, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
@@ -0,0 +1,67 @@
1
+ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import { PDFDocument } from "pdf-lib";
4
+ import { requestExecutor, signerExecutor } from "../entity.js";
5
+ import { readTenantFile, sha256Hex } from "../files.js";
6
+ import { RequestSignatureSchema } from "../payloads.js";
7
+ import { SIGNATURE_DEFAULT_VALIDITY_DAYS, SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_STATUS, } from "../web/constants.js";
8
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
9
+ // Encrypted or unparseable PDFs would fail later when the signature page is appended and leave the
10
+ // request stuck in all-signed.
11
+ async function isLoadablePdf(bytes) {
12
+ try {
13
+ await PDFDocument.load(bytes);
14
+ return true;
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ }
20
+ export function createRequestHandler(access) {
21
+ return defineWriteHandler({
22
+ name: "request",
23
+ schema: RequestSignatureSchema,
24
+ access,
25
+ agent: { risk: "mid" },
26
+ description: "Requests signatures on one PDF document of the tenant from one or more people; each signer signs on a display in person or through a link issued later. The document is referenced by file id and hash and never changed.",
27
+ handler: async (event, ctx) => {
28
+ const payload = event.payload;
29
+ const user = event.user;
30
+ const document = await readTenantFile(ctx, user.tenantId, payload.documentFileId);
31
+ if (document === null || !(await isLoadablePdf(document.content))) {
32
+ return writeFailure(new UnprocessableError("document_not_a_pdf"));
33
+ }
34
+ const validityDays = payload.expiresInDays ?? SIGNATURE_DEFAULT_VALIDITY_DAYS;
35
+ const now = ctx.tz.now();
36
+ const created = await requestExecutor.create({
37
+ documentFileId: payload.documentFileId,
38
+ documentSha256: sha256Hex(document.content),
39
+ title: payload.title,
40
+ level: payload.level,
41
+ subjectType: payload.subjectType,
42
+ subjectId: payload.subjectId,
43
+ status: SIGNATURE_REQUEST_STATUS.Open,
44
+ expiresAt: now.add({ milliseconds: validityDays * MS_PER_DAY }),
45
+ }, user, ctx.db);
46
+ if (!created.isSuccess)
47
+ return created;
48
+ const requestId = String(created.data.id);
49
+ const signerIds = [];
50
+ for (const signer of payload.signers) {
51
+ const createdSigner = await signerExecutor.create({
52
+ requestId,
53
+ name: signer.name,
54
+ status: SIGNATURE_SIGNER_STATUS.Pending,
55
+ viewCount: 0,
56
+ ...(signer.role !== undefined && { role: signer.role }),
57
+ ...(signer.contactId !== undefined && { contactId: signer.contactId }),
58
+ ...(signer.email !== undefined && { email: signer.email.toLowerCase() }),
59
+ }, user, ctx.db);
60
+ if (!createdSigner.isSuccess)
61
+ return createdSigner;
62
+ signerIds.push(String(createdSigner.data.id));
63
+ }
64
+ return { isSuccess: true, data: { requestId, signerIds } };
65
+ },
66
+ });
67
+ }
@@ -0,0 +1,6 @@
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<{
3
+ signerId: import("zod").ZodUUID;
4
+ }, import("zod/v4/core").$strip>, {
5
+ readonly revoked: true;
6
+ }, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
@@ -0,0 +1,18 @@
1
+ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { signerExecutor } from "../entity.js";
3
+ import { SignerIdSchema } from "../payloads.js";
4
+ export function createRevokeLinkHandler(access) {
5
+ return defineWriteHandler({
6
+ name: "revoke-link",
7
+ schema: SignerIdSchema,
8
+ access,
9
+ agent: { expose: false },
10
+ description: "Revokes the signing link of one signer; the token stops working at once.",
11
+ handler: async (event, ctx) => {
12
+ const updated = await signerExecutor.update({ id: event.payload.signerId, changes: { linkAnchor: null } }, event.user, ctx.db, { skipOptimisticLock: true });
13
+ if (!updated.isSuccess)
14
+ return updated;
15
+ return { isSuccess: true, data: { revoked: true } };
16
+ },
17
+ });
18
+ }
@@ -0,0 +1,8 @@
1
+ import { type AccessRule } from "@cosmicdrift/kumiko-framework/engine";
2
+ export type SignInPersonData = {
3
+ readonly requestStatus: string;
4
+ };
5
+ export declare function createSignInPersonHandler(access: AccessRule): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"sign-in-person", import("zod").ZodObject<{
6
+ signerId: import("zod").ZodUUID;
7
+ imagePngBase64: import("zod").ZodString;
8
+ }, import("zod/v4/core").$strip>, SignInPersonData, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
@@ -0,0 +1,52 @@
1
+ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { NotFoundError, UnprocessableError, writeFailure, } from "@cosmicdrift/kumiko-framework/errors";
3
+ import { signerExecutor } from "../entity.js";
4
+ import { discardGeneratedFile } from "../files.js";
5
+ import { advanceIfAllSigned, isOpenRequest, isUnsignedSigner, loadRequestOfSigner, } from "../lib.js";
6
+ import { SignInPersonSchema } from "../payloads.js";
7
+ import { decodeSignatureImage, invalidImage, recordInPersonSignature, storeSignatureImage, } from "../signing.js";
8
+ import { SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS } from "../web/constants.js";
9
+ export function createSignInPersonHandler(access) {
10
+ return defineWriteHandler({
11
+ name: "sign-in-person",
12
+ schema: SignInPersonSchema,
13
+ access,
14
+ agent: { expose: false },
15
+ description: "Records the signature a person drew on this display for one signer of an open request; the last signature moves the request to all-signed.",
16
+ handler: async (event, ctx) => {
17
+ const user = event.user;
18
+ const signer = await signerExecutor.detail({ id: event.payload.signerId }, user, ctx.db);
19
+ if (signer === null)
20
+ return writeFailure(new NotFoundError("signer", event.payload.signerId));
21
+ const request = await loadRequestOfSigner(ctx, user, signer);
22
+ const now = ctx.tz.now();
23
+ if (request === null || !isOpenRequest(request, now) || !isUnsignedSigner(signer)) {
24
+ return writeFailure(new UnprocessableError("signature_not_possible"));
25
+ }
26
+ const png = decodeSignatureImage(event.payload.imagePngBase64);
27
+ if (png === null)
28
+ return invalidImage();
29
+ const image = await storeSignatureImage(ctx, user, png);
30
+ if (!image.isSuccess)
31
+ return image;
32
+ const recorded = await recordInPersonSignature(ctx, user, signer, {
33
+ method: SIGNATURE_METHOD.InPerson,
34
+ imageFileId: image.data.id,
35
+ signedAt: now,
36
+ });
37
+ if (!recorded.isSuccess) {
38
+ await discardGeneratedFile(ctx, user, image.data);
39
+ return recorded;
40
+ }
41
+ const allSigned = await advanceIfAllSigned(ctx, user, request.id);
42
+ return {
43
+ isSuccess: true,
44
+ data: {
45
+ requestStatus: allSigned
46
+ ? SIGNATURE_REQUEST_STATUS.AllSigned
47
+ : SIGNATURE_REQUEST_STATUS.Open,
48
+ },
49
+ };
50
+ },
51
+ });
52
+ }
@@ -0,0 +1,6 @@
1
+ type LocalizedString = {
2
+ readonly en: string;
3
+ readonly de: string;
4
+ };
5
+ export declare const SIGNATURE_I18N: Readonly<Record<string, LocalizedString>>;
6
+ export {};
@@ -0,0 +1,49 @@
1
+ const REQUEST = "signature:entity:signatureRequest:field";
2
+ const SIGNER = "signature:entity:signatureSigner:field";
3
+ export const SIGNATURE_I18N = {
4
+ "signature:feature.label": { en: "Signatures", de: "Unterschriften" },
5
+ "screen:signature-list.title": { en: "Signatures", de: "Unterschriften" },
6
+ "signature.nav.signature": { en: "Signatures", de: "Unterschriften" },
7
+ "signature.action.open": { en: "Open", de: "Öffnen" },
8
+ "signature.signers.title": { en: "Signers", de: "Unterzeichner" },
9
+ "signature.action.issueLink": { en: "Send link", de: "Link senden" },
10
+ "signature.action.revokeLink": { en: "Revoke link", de: "Link widerrufen" },
11
+ "signature.action.revokeLink.confirm": {
12
+ en: "Revoke the link of this signer?",
13
+ de: "Den Link dieses Unterzeichners widerrufen?",
14
+ },
15
+ "screen:signature-detail.title": { en: "Signature request", de: "Unterschriftsanfrage" },
16
+ "signature.action.cancel": { en: "Cancel request", de: "Anfrage abbrechen" },
17
+ "signature.action.cancel.confirm": {
18
+ en: "Cancel this request? All signing links stop working.",
19
+ de: "Diese Anfrage abbrechen? Alle Unterschrifts-Links werden ungültig.",
20
+ },
21
+ [`${SIGNER}:name`]: { en: "Name", de: "Name" },
22
+ [`${SIGNER}:role`]: { en: "Role", de: "Rolle" },
23
+ [`${SIGNER}:status`]: { en: "Status", de: "Status" },
24
+ [`${SIGNER}:method`]: { en: "Way of signing", de: "Art der Unterschrift" },
25
+ [`${SIGNER}:signedAt`]: { en: "Signed", de: "Unterschrieben" },
26
+ [`${SIGNER}:status:option:pending`]: { en: "Pending", de: "Ausstehend" },
27
+ [`${SIGNER}:status:option:viewed`]: { en: "Viewed", de: "Geöffnet" },
28
+ [`${SIGNER}:status:option:signed`]: { en: "Signed", de: "Unterschrieben" },
29
+ [`${SIGNER}:status:option:declined`]: { en: "Declined", de: "Abgelehnt" },
30
+ [`${SIGNER}:method:option:in-person`]: { en: "In person", de: "Vor Ort" },
31
+ [`${SIGNER}:method:option:link`]: { en: "Link", de: "Link" },
32
+ [`${REQUEST}:title`]: { en: "Document", de: "Dokument" },
33
+ [`${REQUEST}:status`]: { en: "Status", de: "Status" },
34
+ [`${REQUEST}:subjectType`]: { en: "Related to", de: "Gehört zu" },
35
+ [`${REQUEST}:expiresAt`]: { en: "Valid until", de: "Gültig bis" },
36
+ [`${REQUEST}:completedAt`]: { en: "Completed", de: "Abgeschlossen" },
37
+ [`${REQUEST}:documentFileId`]: { en: "Document file", de: "Dokumentdatei" },
38
+ [`${REQUEST}:documentSha256`]: { en: "Document hash", de: "Dokument-Hash" },
39
+ [`${REQUEST}:level`]: { en: "Level", de: "Stufe" },
40
+ [`${REQUEST}:subjectId`]: { en: "Related id", de: "Zugehörige ID" },
41
+ [`${REQUEST}:completedFileId`]: { en: "Signed file", de: "Signierte Datei" },
42
+ [`${REQUEST}:level:option:simple`]: { en: "Simple", de: "Einfach" },
43
+ [`${REQUEST}:status:option:open`]: { en: "Open", de: "Offen" },
44
+ [`${REQUEST}:status:option:all-signed`]: { en: "All signed", de: "Alle unterschrieben" },
45
+ [`${REQUEST}:status:option:completed`]: { en: "Completed", de: "Abgeschlossen" },
46
+ [`${REQUEST}:status:option:declined`]: { en: "Declined", de: "Abgelehnt" },
47
+ [`${REQUEST}:status:option:expired`]: { en: "Expired", de: "Abgelaufen" },
48
+ [`${REQUEST}:status:option:cancelled`]: { en: "Cancelled", de: "Abgebrochen" },
49
+ };
@@ -0,0 +1,5 @@
1
+ export type { SignatureRetention } from "./entity.ts";
2
+ export { createSignatureFeature } from "./feature.ts";
3
+ export type { DeliverSignatureLink, RenderSignatureHtmlToPdf, SignatureLinkDelivery, SignatureOptions, } from "./options.ts";
4
+ export type { SignaturePageLabels } from "./signature-page.ts";
5
+ export { SIGNATURE_DEFAULT_VALIDITY_DAYS, SIGNATURE_EVENT_SHORT, SIGNATURE_FEATURE, SIGNATURE_INVALID_IMAGE_REASON, SIGNATURE_INVALID_LINK_REASON, SIGNATURE_LEVEL, SIGNATURE_LINK_TTL_DAYS, SIGNATURE_MAX_LINK_OPENS, SIGNATURE_METHOD, SIGNATURE_REQUEST_ENTITY, SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_ENTITY, SIGNATURE_SIGNER_STATUS, SignatureEvents, SignatureHandlers, SignatureInternalHandlers, SignatureJobs, type SignatureLevel, type SignatureMethod, SignatureQueries, type SignatureRequestStatus, type SignatureSignerStatus, } from "./web/constants.ts";
@@ -0,0 +1,2 @@
1
+ export { createSignatureFeature } from "./feature.js";
2
+ export { SIGNATURE_DEFAULT_VALIDITY_DAYS, SIGNATURE_EVENT_SHORT, SIGNATURE_FEATURE, SIGNATURE_INVALID_IMAGE_REASON, SIGNATURE_INVALID_LINK_REASON, SIGNATURE_LEVEL, SIGNATURE_LINK_TTL_DAYS, SIGNATURE_MAX_LINK_OPENS, SIGNATURE_METHOD, SIGNATURE_REQUEST_ENTITY, SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_ENTITY, SIGNATURE_SIGNER_STATUS, SignatureEvents, SignatureHandlers, SignatureInternalHandlers, SignatureJobs, SignatureQueries, } from "./web/constants.js";
@@ -0,0 +1,54 @@
1
+ import type { TenantDb } from "@cosmicdrift/kumiko-framework/db";
2
+ import { type AccessRule, type HandlerContext, type SessionUser } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
4
+ import { requestExecutor, signerExecutor } from "./entity.ts";
5
+ import { type SignatureRequestStatus } from "./web/constants.ts";
6
+ export declare const DEFAULT_SIGNATURE_ACCESS: AccessRule;
7
+ export declare const internalAccess: {
8
+ readonly roles: readonly string[];
9
+ };
10
+ export declare const SIGNATURE_OUTCOME_AGGREGATE_TYPE: "signature-outcome";
11
+ export type RequestRow = NonNullable<Awaited<ReturnType<typeof requestExecutor.detail>>>;
12
+ export type SignerRow = NonNullable<Awaited<ReturnType<typeof signerExecutor.detail>>>;
13
+ export declare function invalidLink(): import("@cosmicdrift/kumiko-types/write-error-info-types").WriteFailure;
14
+ export declare function instantOrNull(value: unknown): Temporal.Instant | null;
15
+ export declare function isPastInstant(value: unknown, now: Temporal.Instant): boolean;
16
+ export declare function isOpenRequest(request: RequestRow, now: Temporal.Instant): boolean;
17
+ export declare function isUnsignedSigner(signer: SignerRow): boolean;
18
+ export declare function listSigners(ctx: {
19
+ readonly db: TenantDb;
20
+ }, user: SessionUser, requestId: string): Promise<readonly SignerRow[]>;
21
+ export declare function versionOf(row: {
22
+ readonly version?: unknown;
23
+ }): number | undefined;
24
+ export declare function setRequestStatus(ctx: {
25
+ readonly db: TenantDb;
26
+ }, user: SessionUser, requestId: string, from: SignatureRequestStatus, changes: Readonly<Record<string, unknown>>): Promise<import("@cosmicdrift/kumiko-types/handlers").WriteResult<import("@cosmicdrift/kumiko-types/hooks").SaveContext>>;
27
+ export declare function advanceIfAllSigned(ctx: {
28
+ readonly db: TenantDb;
29
+ }, user: SessionUser, requestId: string): Promise<boolean>;
30
+ export declare function loadRequestOfSigner(ctx: {
31
+ readonly db: TenantDb;
32
+ }, user: SessionUser, signer: SignerRow): Promise<{
33
+ readonly id: string;
34
+ readonly tenantId: string;
35
+ readonly version: number;
36
+ readonly insertedAt: globalThis.Temporal.Instant;
37
+ readonly modifiedAt: globalThis.Temporal.Instant | null;
38
+ readonly insertedById: string | null;
39
+ readonly modifiedById: string | null;
40
+ readonly isDeleted?: boolean | undefined;
41
+ readonly deletedAt?: globalThis.Temporal.Instant | null | undefined;
42
+ readonly deletedById?: string | null | undefined;
43
+ readonly completedAt: globalThis.Temporal.Instant | null;
44
+ readonly completedFileId: string | null;
45
+ readonly documentFileId: string;
46
+ readonly documentSha256: string;
47
+ readonly expiresAt: globalThis.Temporal.Instant;
48
+ readonly level: string;
49
+ readonly status: string;
50
+ readonly subjectId: string;
51
+ readonly subjectType: string;
52
+ readonly title: string;
53
+ } | null>;
54
+ export declare function appendOutcomeEvent(ctx: Pick<HandlerContext, "events">, type: string, payload: Readonly<Record<string, unknown>>): Promise<void>;
@@ -0,0 +1,68 @@
1
+ import { access, } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import { generateId } from "@cosmicdrift/kumiko-framework/utils";
4
+ import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
5
+ import { requestExecutor, signerExecutor } from "./entity.js";
6
+ import { SIGNATURE_INVALID_LINK_REASON, SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_STATUS, } from "./web/constants.js";
7
+ export const DEFAULT_SIGNATURE_ACCESS = { roles: ["TenantAdmin", "TenantMember"] };
8
+ export const internalAccess = { roles: access.system };
9
+ export const SIGNATURE_OUTCOME_AGGREGATE_TYPE = "signature-outcome";
10
+ // Same body and status for every link rejection: forged, expired, revoked, used up, signed already.
11
+ export function invalidLink() {
12
+ return writeFailure(new UnprocessableError(SIGNATURE_INVALID_LINK_REASON));
13
+ }
14
+ export function instantOrNull(value) {
15
+ return value instanceof Temporal.Instant ? value : null;
16
+ }
17
+ export function isPastInstant(value, now) {
18
+ const instant = instantOrNull(value);
19
+ return instant !== null && Temporal.Instant.compare(instant, now) <= 0;
20
+ }
21
+ export function isOpenRequest(request, now) {
22
+ return request.status === SIGNATURE_REQUEST_STATUS.Open && !isPastInstant(request.expiresAt, now);
23
+ }
24
+ export function isUnsignedSigner(signer) {
25
+ return (signer.status === SIGNATURE_SIGNER_STATUS.Pending ||
26
+ signer.status === SIGNATURE_SIGNER_STATUS.Viewed);
27
+ }
28
+ // Equals the executor's MAX_LIST_LIMIT.
29
+ const LIST_PAGE_SIZE = 200;
30
+ export async function listSigners(ctx, user, requestId) {
31
+ const found = await signerExecutor.list({ filter: { field: "requestId", op: "eq", value: requestId }, limit: LIST_PAGE_SIZE }, user, ctx.db);
32
+ return found.rows;
33
+ }
34
+ export function versionOf(row) {
35
+ return typeof row.version === "number" ? row.version : undefined;
36
+ }
37
+ export async function setRequestStatus(ctx, user, requestId, from, changes) {
38
+ return requestExecutor.update({ id: requestId, changes }, user, ctx.db, {
39
+ skipOptimisticLock: true,
40
+ expect: { status: from },
41
+ });
42
+ }
43
+ // Moves an open request to all-signed once every signer has signed. Two signers committing at the
44
+ // same moment can both still see the other as unsigned; the sweep job repeats this check.
45
+ export async function advanceIfAllSigned(ctx, user, requestId) {
46
+ const signers = await listSigners(ctx, user, requestId);
47
+ const allSigned = signers.length > 0 &&
48
+ signers.every((signer) => signer.status === SIGNATURE_SIGNER_STATUS.Signed);
49
+ if (!allSigned)
50
+ return false;
51
+ const moved = await setRequestStatus(ctx, user, requestId, SIGNATURE_REQUEST_STATUS.Open, {
52
+ status: SIGNATURE_REQUEST_STATUS.AllSigned,
53
+ });
54
+ return moved.isSuccess;
55
+ }
56
+ export function loadRequestOfSigner(ctx, user, signer) {
57
+ return requestExecutor.detail({ id: signer.requestId }, user, ctx.db);
58
+ }
59
+ // Each outcome is its own aggregate with a fresh id: it needs no predecessor version and cannot
60
+ // conflict with a concurrent write on the request it describes.
61
+ export function appendOutcomeEvent(ctx, type, payload) {
62
+ return ctx.events.unsafeAppend({
63
+ aggregateId: generateId(),
64
+ aggregateType: SIGNATURE_OUTCOME_AGGREGATE_TYPE,
65
+ type,
66
+ payload,
67
+ });
68
+ }