@cosmicdrift/kumiko-samples 0.415.0 → 0.417.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 (78) 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/channel-whatsapp/changes.json +6 -0
  7. package/packages/bundled-features/src/channel-whatsapp/constants.ts +1 -0
  8. package/packages/bundled-features/src/channel-whatsapp/graph-client.ts +37 -1
  9. package/packages/bundled-features/src/handbook-knowledge/README.md +64 -0
  10. package/packages/bundled-features/src/handbook-knowledge/changes.json +8 -0
  11. package/packages/bundled-features/src/handbook-knowledge/constants.ts +8 -0
  12. package/packages/bundled-features/src/handbook-knowledge/feature.ts +34 -0
  13. package/packages/bundled-features/src/handbook-knowledge/handbook-index.ts +66 -0
  14. package/packages/bundled-features/src/handbook-knowledge/handlers.ts +77 -0
  15. package/packages/bundled-features/src/handbook-knowledge/index.ts +10 -0
  16. package/packages/bundled-features/src/helpdesk/screens.ts +5 -1
  17. package/packages/bundled-features/src/signature/README.md +66 -0
  18. package/packages/bundled-features/src/signature/changes.json +22 -0
  19. package/packages/bundled-features/src/signature/entity.ts +192 -0
  20. package/packages/bundled-features/src/signature/feature.ts +125 -0
  21. package/packages/bundled-features/src/signature/files.ts +107 -0
  22. package/packages/bundled-features/src/signature/grant.ts +79 -0
  23. package/packages/bundled-features/src/signature/handlers/anonymous.write.ts +88 -0
  24. package/packages/bundled-features/src/signature/handlers/cancel.write.ts +48 -0
  25. package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +77 -0
  26. package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +99 -0
  27. package/packages/bundled-features/src/signature/handlers/link-internal.write.ts +261 -0
  28. package/packages/bundled-features/src/signature/handlers/request.write.ts +120 -0
  29. package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +37 -0
  30. package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +73 -0
  31. package/packages/bundled-features/src/signature/i18n.ts +52 -0
  32. package/packages/bundled-features/src/signature/index.ts +35 -0
  33. package/packages/bundled-features/src/signature/lib.ts +125 -0
  34. package/packages/bundled-features/src/signature/options.ts +64 -0
  35. package/packages/bundled-features/src/signature/payloads.ts +71 -0
  36. package/packages/bundled-features/src/signature/png.ts +169 -0
  37. package/packages/bundled-features/src/signature/screens.ts +117 -0
  38. package/packages/bundled-features/src/signature/signature-page.ts +93 -0
  39. package/packages/bundled-features/src/signature/signing.ts +77 -0
  40. package/packages/bundled-features/src/signature/static-sign.ts +99 -0
  41. package/packages/bundled-features/src/signature/subject-queries.ts +144 -0
  42. package/packages/bundled-features/src/signature/subject-scope.ts +43 -0
  43. package/packages/bundled-features/src/signature/sweep.ts +161 -0
  44. package/packages/bundled-features/src/signature/user-data.ts +159 -0
  45. package/packages/bundled-features/src/signature/web/constants.ts +92 -0
  46. package/packages/bundled-features/src/signature/web/index.ts +31 -0
  47. package/packages/bundled-features/src/signature/web/pad.ts +147 -0
  48. package/packages/bundled-features/src/signature/web/signature-pad.tsx +82 -0
  49. package/packages/bundled-features/src/subscription-stripe/changes.json +6 -0
  50. package/packages/bundled-features/src/subscription-stripe/feature.ts +9 -0
  51. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +7 -1
  52. package/samples/apps/use-all-bundled/feature-manifest.json +63 -1
  53. package/samples/apps/use-all-bundled/kumiko/migrations/0068_signature.rebuild.json +4 -0
  54. package/samples/apps/use-all-bundled/src/run-config.ts +35 -1
  55. package/samples/recipes/dashboard-stats/README.md +4 -0
  56. package/samples/recipes/dashboard-stats/src/feature.ts +47 -0
  57. package/samples/recipes/embedded/README.md +4 -0
  58. package/samples/recipes/embedded/src/entities/invoice.ts +6 -0
  59. package/samples/recipes/embedded/src/feature.ts +7 -1
  60. package/samples/recipes/embedded/src/handlers/invoice-receive.write.ts +1 -0
  61. package/samples/recipes/embedded/src/screens/invoice-receive.screen.ts +2 -0
  62. package/samples/recipes/event-sourcing/src/feature.ts +31 -0
  63. package/samples/recipes/handbook-knowledge/README.md +22 -0
  64. package/samples/recipes/handbook-knowledge/package.json +12 -0
  65. package/samples/recipes/handbook-knowledge/src/feature.ts +42 -0
  66. package/samples/recipes/list-table-options/README.md +9 -0
  67. package/samples/recipes/list-table-options/src/feature.ts +47 -2
  68. package/samples/recipes/managed-config/src/feature.ts +9 -1
  69. package/samples/recipes/record-detail-layout/README.md +7 -0
  70. package/samples/recipes/record-detail-layout/src/feature.ts +40 -2
  71. package/samples/recipes/record-detail-layout/src/order-board.ts +1 -0
  72. package/samples/recipes/secrets-demo/README.md +1 -1
  73. package/samples/recipes/secrets-demo/src/feature.ts +2 -0
  74. package/samples/recipes/signature/README.md +21 -0
  75. package/samples/recipes/signature/package.json +13 -0
  76. package/samples/recipes/signature/src/feature.ts +26 -0
  77. package/samples/recipes/writeform-section/README.md +4 -0
  78. package/samples/recipes/writeform-section/src/feature.ts +97 -0
@@ -0,0 +1,77 @@
1
+ import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import {
3
+ NotFoundError,
4
+ UnprocessableError,
5
+ writeFailure,
6
+ } from "@cosmicdrift/kumiko-framework/errors";
7
+ import { generateId } from "@cosmicdrift/kumiko-framework/utils";
8
+ import { signerExecutor } from "../entity.ts";
9
+ import { signSignatureLinkToken } from "../grant.ts";
10
+ import { isOpenRequest, isUnsignedSigner, loadRequestOfSigner } from "../lib.ts";
11
+ import type { SignatureOptions } from "../options.ts";
12
+ import { SignerIdSchema } from "../payloads.ts";
13
+ import type { SubjectScope } from "../subject-scope.ts";
14
+
15
+ export type IssueLinkData = { readonly signerId: string; readonly linkSentAt: string };
16
+
17
+ // A new link replaces the previous one: the anchor moves on, so the old token stops verifying.
18
+ export function createIssueLinkHandler(
19
+ access: AccessRule,
20
+ scope: SubjectScope,
21
+ opts: Pick<SignatureOptions, "linkSecret" | "deliverLink" | "signaturePageUrl">,
22
+ ) {
23
+ return defineWriteHandler<"issue-link", typeof SignerIdSchema, IssueLinkData>({
24
+ name: "issue-link",
25
+ schema: SignerIdSchema,
26
+ access,
27
+ agent: { risk: "mid" },
28
+ description:
29
+ "Sends a signing link to one signer of an open request, to the signer's own address; the link is never part of the result. An earlier link of that signer stops working. The link is valid for 14 days and a limited number of opens.",
30
+ handler: async (event, ctx) => {
31
+ const user = event.user;
32
+ const signer = await signerExecutor.detail({ id: event.payload.signerId }, user, ctx.db);
33
+ if (signer === null) return writeFailure(new NotFoundError("signer", event.payload.signerId));
34
+ const request = await loadRequestOfSigner(ctx, user, signer);
35
+ if (request !== null && !(await scope.allowsRequest(ctx, user, request))) {
36
+ return writeFailure(new NotFoundError("signer", event.payload.signerId));
37
+ }
38
+ const now = ctx.tz.now();
39
+ if (request === null || !isOpenRequest(request, now) || !isUnsignedSigner(signer)) {
40
+ return writeFailure(new UnprocessableError("link_not_possible"));
41
+ }
42
+ if (typeof signer.email !== "string" || signer.email === "") {
43
+ return writeFailure(new UnprocessableError("signer_without_email"));
44
+ }
45
+ const linkAnchor = generateId();
46
+ const updated = await signerExecutor.update(
47
+ {
48
+ id: signer.id,
49
+ changes: { linkAnchor, linkSentAt: now, viewCount: 0 },
50
+ },
51
+ user,
52
+ ctx.db,
53
+ { skipOptimisticLock: true },
54
+ );
55
+ if (!updated.isSuccess) return updated;
56
+ const grant = signSignatureLinkToken({
57
+ tenantId: user.tenantId,
58
+ signerId: signer.id,
59
+ linkAnchor,
60
+ secret: opts.linkSecret,
61
+ now,
62
+ });
63
+ await opts.deliverLink(ctx, {
64
+ signerId: String(signer.id),
65
+ requestId: String(request.id),
66
+ name: signer.name,
67
+ email: signer.email,
68
+ url: `${opts.signaturePageUrl}#${grant.token}`,
69
+ issuedBy: user,
70
+ });
71
+ return {
72
+ isSuccess: true,
73
+ data: { signerId: String(signer.id), linkSentAt: now.toString() },
74
+ };
75
+ },
76
+ });
77
+ }
@@ -0,0 +1,99 @@
1
+ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { requestExecutor } from "../entity.ts";
3
+ import {
4
+ advanceIfAllSigned,
5
+ appendOutcomeEvent,
6
+ internalAccess,
7
+ isPastInstant,
8
+ listSigners,
9
+ setRequestStatus,
10
+ } from "../lib.ts";
11
+ import { FinishSchema, RequestIdSchema } from "../payloads.ts";
12
+ import { SIGNATURE_REQUEST_STATUS, SignatureEvents } from "../web/constants.ts";
13
+
14
+ // The writes of the sweep job. They run as handlers because a job may only append its own
15
+ // events through ctx.events, and every transition here must also hold the "exactly once" precondition.
16
+ export const finishHandler = defineWriteHandler({
17
+ name: "finish",
18
+ schema: FinishSchema,
19
+ access: internalAccess,
20
+ agent: { expose: false },
21
+ description:
22
+ "Internal: marks an all-signed request completed with its final PDF and emits the completed event once.",
23
+ handler: async (event, ctx) => {
24
+ const request = await requestExecutor.detail(
25
+ { id: event.payload.requestId },
26
+ event.user,
27
+ ctx.db,
28
+ );
29
+ if (request === null) return { isSuccess: true, data: { finished: false } };
30
+ const moved = await setRequestStatus(
31
+ ctx,
32
+ event.user,
33
+ request.id,
34
+ SIGNATURE_REQUEST_STATUS.AllSigned,
35
+ {
36
+ status: SIGNATURE_REQUEST_STATUS.Completed,
37
+ completedFileId: event.payload.completedFileId,
38
+ completedAt: ctx.tz.now(),
39
+ },
40
+ );
41
+ if (!moved.isSuccess) return { isSuccess: true, data: { finished: false } };
42
+ const signers = await listSigners(ctx, event.user, request.id);
43
+ await appendOutcomeEvent(ctx, SignatureEvents.completed, {
44
+ requestId: request.id,
45
+ subjectType: request.subjectType,
46
+ subjectId: request.subjectId,
47
+ completedFileId: event.payload.completedFileId,
48
+ signerCount: signers.length,
49
+ });
50
+ return { isSuccess: true, data: { finished: true } };
51
+ },
52
+ });
53
+
54
+ export const expireHandler = defineWriteHandler({
55
+ name: "expire",
56
+ schema: RequestIdSchema,
57
+ access: internalAccess,
58
+ agent: { expose: false },
59
+ description:
60
+ "Internal: expires an open request whose deadline has passed and emits the expired event once.",
61
+ handler: async (event, ctx) => {
62
+ const request = await requestExecutor.detail(
63
+ { id: event.payload.requestId },
64
+ event.user,
65
+ ctx.db,
66
+ );
67
+ if (request === null || !isPastInstant(request.expiresAt, ctx.tz.now())) {
68
+ return { isSuccess: true, data: { expired: false } };
69
+ }
70
+ const moved = await setRequestStatus(
71
+ ctx,
72
+ event.user,
73
+ request.id,
74
+ SIGNATURE_REQUEST_STATUS.Open,
75
+ { status: SIGNATURE_REQUEST_STATUS.Expired },
76
+ );
77
+ if (!moved.isSuccess) return { isSuccess: true, data: { expired: false } };
78
+ await appendOutcomeEvent(ctx, SignatureEvents.expired, {
79
+ requestId: request.id,
80
+ subjectType: request.subjectType,
81
+ subjectId: request.subjectId,
82
+ });
83
+ return { isSuccess: true, data: { expired: true } };
84
+ },
85
+ });
86
+
87
+ // Two last signers committing at the same moment can each still see the other as unsigned; the
88
+ // sweep repeats the check so such a request cannot stay open for good.
89
+ export const reconcileHandler = defineWriteHandler({
90
+ name: "reconcile",
91
+ schema: RequestIdSchema,
92
+ access: internalAccess,
93
+ agent: { expose: false },
94
+ description: "Internal: moves an open request whose signers have all signed to all-signed.",
95
+ handler: async (event, ctx) => ({
96
+ isSuccess: true,
97
+ data: { advanced: await advanceIfAllSigned(ctx, event.user, event.payload.requestId) },
98
+ }),
99
+ });
@@ -0,0 +1,261 @@
1
+ import {
2
+ defineWriteHandler,
3
+ type HandlerContext,
4
+ type SessionUser,
5
+ } from "@cosmicdrift/kumiko-framework/engine";
6
+ import type { Temporal } from "@cosmicdrift/kumiko-types/temporal";
7
+ import { signerExecutor } from "../entity.ts";
8
+ import { discardGeneratedFile, signedDocumentUrl } from "../files.ts";
9
+ import { parseSignatureLinkSubject, redeemSignatureLinkToken } from "../grant.ts";
10
+ import {
11
+ advanceIfAllSigned,
12
+ appendOutcomeEvent,
13
+ internalAccess,
14
+ invalidLink,
15
+ isOpenRequest,
16
+ isUnsignedSigner,
17
+ loadRequestOfSigner,
18
+ type RequestRow,
19
+ type SignerRow,
20
+ setRequestStatus,
21
+ } from "../lib.ts";
22
+ import { DeclineByLinkSchema, OpenByLinkSchema, SignByLinkSchema } from "../payloads.ts";
23
+ import {
24
+ auditValuesOfRequest,
25
+ decodeSignatureImage,
26
+ invalidImage,
27
+ signatureChanges,
28
+ storeSignatureImage,
29
+ } from "../signing.ts";
30
+ import {
31
+ SIGNATURE_MAX_LINK_OPENS,
32
+ SIGNATURE_METHOD,
33
+ SIGNATURE_REQUEST_STATUS,
34
+ SIGNATURE_SIGNER_STATUS,
35
+ SignatureEvents,
36
+ } from "../web/constants.ts";
37
+
38
+ export type LinkOpenData = {
39
+ readonly title: string;
40
+ readonly signerName: string;
41
+ readonly role: string | null;
42
+ readonly documentUrl: string | null;
43
+ };
44
+
45
+ type LinkTarget = { readonly signer: SignerRow; readonly request: RequestRow };
46
+
47
+ const NO_CONSUME_REASON =
48
+ "opening a link only shows the document and counts the view; signing and declining consume the link";
49
+
50
+ // Anchor of a signer whose link may still act: unsigned, request open, link not revoked.
51
+ async function loadLiveTarget(
52
+ ctx: Pick<HandlerContext, "db">,
53
+ user: SessionUser,
54
+ signerId: string,
55
+ now: Temporal.Instant,
56
+ ): Promise<LinkTarget | null> {
57
+ const signer = await signerExecutor.detail({ id: signerId }, user, ctx.db);
58
+ if (signer === null || !isUnsignedSigner(signer) || typeof signer.linkAnchor !== "string") {
59
+ return null;
60
+ }
61
+ const request = await loadRequestOfSigner(ctx, user, signer);
62
+ return request !== null && isOpenRequest(request, now) ? { signer, request } : null;
63
+ }
64
+
65
+ function viewCountOf(signer: SignerRow): number {
66
+ return typeof signer.viewCount === "number" ? signer.viewCount : 0;
67
+ }
68
+
69
+ function viewChanges(signer: SignerRow, now: Temporal.Instant): Record<string, unknown> {
70
+ return {
71
+ viewCount: viewCountOf(signer) + 1,
72
+ viewedAt: now,
73
+ ...(signer.status === SIGNATURE_SIGNER_STATUS.Pending && {
74
+ status: SIGNATURE_SIGNER_STATUS.Viewed,
75
+ }),
76
+ };
77
+ }
78
+
79
+ export function createLinkInternalHandlers(linkSecret: string) {
80
+ const linkOpen = defineWriteHandler<"link-open", typeof OpenByLinkSchema, LinkOpenData>({
81
+ name: "link-open",
82
+ schema: OpenByLinkSchema,
83
+ access: internalAccess,
84
+ agent: { expose: false },
85
+ description:
86
+ "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.",
87
+ handler: async (event, ctx) => {
88
+ const user = event.user;
89
+ const now = ctx.tz.now();
90
+ const found: { target: LinkTarget | null } = { target: null };
91
+ const redeemed = await redeemSignatureLinkToken({
92
+ token: event.payload.token,
93
+ secret: linkSecret,
94
+ now,
95
+ loadLinkAnchor: async (signerId) => {
96
+ const target = await loadLiveTarget(ctx, user, signerId, now);
97
+ if (target === null || viewCountOf(target.signer) >= SIGNATURE_MAX_LINK_OPENS)
98
+ return null;
99
+ found.target = target;
100
+ return typeof target.signer.linkAnchor === "string" ? target.signer.linkAnchor : null;
101
+ },
102
+ commitAnchor: { unsafeSkip: { reason: NO_CONSUME_REASON } },
103
+ });
104
+ const target = found.target;
105
+ if (!redeemed.ok || target === null) return invalidLink();
106
+
107
+ // A concurrent sign must never be overwritten by the view count, and two simultaneous opens
108
+ // must not both pass the open limit, so status and view count are preconditions.
109
+ const counted = await signerExecutor.update(
110
+ { id: target.signer.id, changes: viewChanges(target.signer, now) },
111
+ user,
112
+ ctx.db,
113
+ {
114
+ skipOptimisticLock: true,
115
+ expect: { status: target.signer.status, viewCount: viewCountOf(target.signer) },
116
+ },
117
+ );
118
+ if (!counted.isSuccess) return invalidLink();
119
+ return {
120
+ isSuccess: true,
121
+ data: {
122
+ title: target.request.title,
123
+ signerName: target.signer.name,
124
+ role: target.signer.role ?? null,
125
+ documentUrl: await signedDocumentUrl(ctx, user, target.request.documentFileId),
126
+ },
127
+ };
128
+ },
129
+ });
130
+
131
+ const linkSign = defineWriteHandler<
132
+ "link-sign",
133
+ typeof SignByLinkSchema,
134
+ { readonly requestStatus: string }
135
+ >({
136
+ name: "link-sign",
137
+ schema: SignByLinkSchema,
138
+ access: internalAccess,
139
+ agent: { expose: false },
140
+ description:
141
+ "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.",
142
+ handler: async (event, ctx) => {
143
+ const user = event.user;
144
+ const now = ctx.tz.now();
145
+ const png = decodeSignatureImage(event.payload.imagePngBase64);
146
+ if (png === null) return invalidImage();
147
+ const found: { target: LinkTarget | null } = { target: null };
148
+ const redeemed = await redeemSignatureLinkToken({
149
+ token: event.payload.token,
150
+ secret: linkSecret,
151
+ now,
152
+ loadLinkAnchor: async (signerId) => {
153
+ found.target = await loadLiveTarget(ctx, user, signerId, now);
154
+ const anchor = found.target?.signer.linkAnchor;
155
+ return typeof anchor === "string" ? anchor : null;
156
+ },
157
+ // Spends the anchor and writes the signature in one conditional update, so exactly one of
158
+ // two simultaneous submits passes.
159
+ commitAnchor: async (subject, expectedAnchor) => {
160
+ const parsed = parseSignatureLinkSubject(subject);
161
+ if (parsed === null) return false;
162
+ const image = await storeSignatureImage(ctx, user, png);
163
+ if (!image.isSuccess) return false;
164
+ const signed = await signerExecutor.update(
165
+ {
166
+ id: parsed.signerId,
167
+ changes: signatureChanges({
168
+ method: SIGNATURE_METHOD.Link,
169
+ imageFileId: image.data.id,
170
+ signedAt: now,
171
+ }),
172
+ },
173
+ user,
174
+ ctx.db,
175
+ { skipOptimisticLock: true, expect: { linkAnchor: expectedAnchor } },
176
+ );
177
+ if (!signed.isSuccess) await discardGeneratedFile(ctx, user, image.data);
178
+ return signed.isSuccess;
179
+ },
180
+ });
181
+ const target = found.target;
182
+ if (!redeemed.ok || target === null) return invalidLink();
183
+ const allSigned = await advanceIfAllSigned(ctx, user, target.request.id);
184
+ return {
185
+ isSuccess: true,
186
+ data: {
187
+ requestStatus: allSigned
188
+ ? SIGNATURE_REQUEST_STATUS.AllSigned
189
+ : SIGNATURE_REQUEST_STATUS.Open,
190
+ },
191
+ };
192
+ },
193
+ });
194
+
195
+ const linkDecline = defineWriteHandler<
196
+ "link-decline",
197
+ typeof DeclineByLinkSchema,
198
+ { readonly declined: true }
199
+ >({
200
+ name: "link-decline",
201
+ schema: DeclineByLinkSchema,
202
+ access: internalAccess,
203
+ agent: { expose: false },
204
+ description:
205
+ "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.",
206
+ handler: async (event, ctx) => {
207
+ const user = event.user;
208
+ const now = ctx.tz.now();
209
+ const found: { target: LinkTarget | null } = { target: null };
210
+ const redeemed = await redeemSignatureLinkToken({
211
+ token: event.payload.token,
212
+ secret: linkSecret,
213
+ now,
214
+ loadLinkAnchor: async (signerId) => {
215
+ found.target = await loadLiveTarget(ctx, user, signerId, now);
216
+ const anchor = found.target?.signer.linkAnchor;
217
+ return typeof anchor === "string" ? anchor : null;
218
+ },
219
+ commitAnchor: async (subject, expectedAnchor) => {
220
+ const parsed = parseSignatureLinkSubject(subject);
221
+ if (parsed === null) return false;
222
+ const declined = await signerExecutor.update(
223
+ {
224
+ id: parsed.signerId,
225
+ changes: {
226
+ status: SIGNATURE_SIGNER_STATUS.Declined,
227
+ linkAnchor: null,
228
+ ...(event.payload.reason !== undefined && { declineReason: event.payload.reason }),
229
+ ...auditValuesOfRequest(),
230
+ },
231
+ },
232
+ user,
233
+ ctx.db,
234
+ { skipOptimisticLock: true, expect: { linkAnchor: expectedAnchor } },
235
+ );
236
+ return declined.isSuccess;
237
+ },
238
+ });
239
+ const target = found.target;
240
+ if (!redeemed.ok || target === null) return invalidLink();
241
+ const moved = await setRequestStatus(
242
+ ctx,
243
+ user,
244
+ target.request.id,
245
+ SIGNATURE_REQUEST_STATUS.Open,
246
+ { status: SIGNATURE_REQUEST_STATUS.Declined },
247
+ );
248
+ if (moved.isSuccess) {
249
+ await appendOutcomeEvent(ctx, SignatureEvents.declined, {
250
+ requestId: target.request.id,
251
+ subjectType: target.request.subjectType,
252
+ subjectId: target.request.subjectId,
253
+ signerId: target.signer.id,
254
+ });
255
+ }
256
+ return { isSuccess: true, data: { declined: true } };
257
+ },
258
+ });
259
+
260
+ return { linkOpen, linkSign, linkDecline };
261
+ }
@@ -0,0 +1,120 @@
1
+ import { selectMany } from "@cosmicdrift/kumiko-framework/db";
2
+ import {
3
+ type AccessRule,
4
+ defineWriteHandler,
5
+ type HandlerContext,
6
+ isUuid,
7
+ } from "@cosmicdrift/kumiko-framework/engine";
8
+ import {
9
+ NotFoundError,
10
+ UnprocessableError,
11
+ writeFailure,
12
+ } from "@cosmicdrift/kumiko-framework/errors";
13
+ import {
14
+ canCallerReadFileRef,
15
+ type FileRef,
16
+ fileRefsTable,
17
+ } from "@cosmicdrift/kumiko-framework/files";
18
+ import { PDFDocument } from "pdf-lib";
19
+ import { requestExecutor, signerExecutor } from "../entity.ts";
20
+ import { readTenantFile, sha256Hex } from "../files.ts";
21
+ import { RequestSignatureSchema } from "../payloads.ts";
22
+ import type { SubjectScope } from "../subject-scope.ts";
23
+ import {
24
+ SIGNATURE_DEFAULT_VALIDITY_DAYS,
25
+ SIGNATURE_REQUEST_ENTITY,
26
+ SIGNATURE_REQUEST_STATUS,
27
+ SIGNATURE_SIGNER_STATUS,
28
+ } from "../web/constants.ts";
29
+
30
+ export type RequestSignatureData = {
31
+ readonly requestId: string;
32
+ readonly signerIds: readonly string[];
33
+ };
34
+
35
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
36
+
37
+ // Encrypted or unparseable PDFs would fail later when the signature page is appended and leave the
38
+ // request stuck in all-signed.
39
+ async function isLoadablePdf(bytes: Uint8Array): Promise<boolean> {
40
+ try {
41
+ await PDFDocument.load(bytes);
42
+ return true;
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
47
+
48
+ // A file the caller may not open through GET /files/:id answers like an unknown id, so ids cannot be probed.
49
+ async function isReadableTenantFile(ctx: HandlerContext, fileRefId: string): Promise<boolean> {
50
+ if (!isUuid(fileRefId)) return false;
51
+ const [fileRef] = await selectMany<FileRef>(ctx.db, fileRefsTable, {
52
+ id: fileRefId,
53
+ tenantId: ctx.user.tenantId,
54
+ isDeleted: false,
55
+ });
56
+ return fileRef !== undefined && (await canCallerReadFileRef(ctx, fileRef));
57
+ }
58
+
59
+ export function createRequestHandler(access: AccessRule, scope: SubjectScope) {
60
+ return defineWriteHandler<"request", typeof RequestSignatureSchema, RequestSignatureData>({
61
+ name: "request",
62
+ schema: RequestSignatureSchema,
63
+ access,
64
+ agent: { risk: "mid" },
65
+ description:
66
+ "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.",
67
+ handler: async (event, ctx) => {
68
+ const payload = event.payload;
69
+ const user = event.user;
70
+ if (!(await scope.allows(ctx, user, payload.subjectType, payload.subjectId))) {
71
+ return writeFailure(new NotFoundError(SIGNATURE_REQUEST_ENTITY));
72
+ }
73
+ if (!(await isReadableTenantFile(ctx, payload.documentFileId))) {
74
+ return writeFailure(new UnprocessableError("document_not_a_pdf"));
75
+ }
76
+ const document = await readTenantFile(ctx, user.tenantId, payload.documentFileId);
77
+ if (document === null || !(await isLoadablePdf(document.content))) {
78
+ return writeFailure(new UnprocessableError("document_not_a_pdf"));
79
+ }
80
+ const validityDays = payload.expiresInDays ?? SIGNATURE_DEFAULT_VALIDITY_DAYS;
81
+ const now = ctx.tz.now();
82
+ const created = await requestExecutor.create(
83
+ {
84
+ documentFileId: payload.documentFileId,
85
+ documentSha256: sha256Hex(document.content),
86
+ title: payload.title,
87
+ level: payload.level,
88
+ subjectType: payload.subjectType,
89
+ subjectId: payload.subjectId,
90
+ status: SIGNATURE_REQUEST_STATUS.Open,
91
+ expiresAt: now.add({ milliseconds: validityDays * MS_PER_DAY }),
92
+ },
93
+ user,
94
+ ctx.db,
95
+ );
96
+ if (!created.isSuccess) return created;
97
+ const requestId = String(created.data.id);
98
+
99
+ const signerIds: string[] = [];
100
+ for (const signer of payload.signers) {
101
+ const createdSigner = await signerExecutor.create(
102
+ {
103
+ requestId,
104
+ name: signer.name,
105
+ status: SIGNATURE_SIGNER_STATUS.Pending,
106
+ viewCount: 0,
107
+ ...(signer.role !== undefined && { role: signer.role }),
108
+ ...(signer.contactId !== undefined && { contactId: signer.contactId }),
109
+ ...(signer.email !== undefined && { email: signer.email.toLowerCase() }),
110
+ },
111
+ user,
112
+ ctx.db,
113
+ );
114
+ if (!createdSigner.isSuccess) return createdSigner;
115
+ signerIds.push(String(createdSigner.data.id));
116
+ }
117
+ return { isSuccess: true, data: { requestId, signerIds } };
118
+ },
119
+ });
120
+ }
@@ -0,0 +1,37 @@
1
+ import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { NotFoundError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import { signerExecutor } from "../entity.ts";
4
+ import { loadRequestOfSigner } from "../lib.ts";
5
+ import { SignerIdSchema } from "../payloads.ts";
6
+ import type { SubjectScope } from "../subject-scope.ts";
7
+
8
+ export function createRevokeLinkHandler(access: AccessRule, scope: SubjectScope) {
9
+ return defineWriteHandler<"revoke-link", typeof SignerIdSchema, { readonly revoked: true }>({
10
+ name: "revoke-link",
11
+ schema: SignerIdSchema,
12
+ access,
13
+ agent: { expose: false },
14
+ description: "Revokes the signing link of one signer; the token stops working at once.",
15
+ handler: async (event, ctx) => {
16
+ if (scope.isScoped(event.user)) {
17
+ const signer = await signerExecutor.detail(
18
+ { id: event.payload.signerId },
19
+ event.user,
20
+ ctx.db,
21
+ );
22
+ const request = signer === null ? null : await loadRequestOfSigner(ctx, event.user, signer);
23
+ if (request === null || !(await scope.allowsRequest(ctx, event.user, request))) {
24
+ return writeFailure(new NotFoundError("signer", event.payload.signerId));
25
+ }
26
+ }
27
+ const updated = await signerExecutor.update(
28
+ { id: event.payload.signerId, changes: { linkAnchor: null } },
29
+ event.user,
30
+ ctx.db,
31
+ { skipOptimisticLock: true },
32
+ );
33
+ if (!updated.isSuccess) return updated;
34
+ return { isSuccess: true, data: { revoked: true } };
35
+ },
36
+ });
37
+ }
@@ -0,0 +1,73 @@
1
+ import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import {
3
+ NotFoundError,
4
+ UnprocessableError,
5
+ writeFailure,
6
+ } from "@cosmicdrift/kumiko-framework/errors";
7
+ import { signerExecutor } from "../entity.ts";
8
+ import { discardGeneratedFile } from "../files.ts";
9
+ import {
10
+ advanceIfAllSigned,
11
+ isOpenRequest,
12
+ isUnsignedSigner,
13
+ loadRequestOfSigner,
14
+ } from "../lib.ts";
15
+ import { SignInPersonSchema } from "../payloads.ts";
16
+ import {
17
+ decodeSignatureImage,
18
+ invalidImage,
19
+ recordInPersonSignature,
20
+ storeSignatureImage,
21
+ } from "../signing.ts";
22
+ import type { SubjectScope } from "../subject-scope.ts";
23
+ import { SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS } from "../web/constants.ts";
24
+
25
+ export type SignInPersonData = { readonly requestStatus: string };
26
+
27
+ export function createSignInPersonHandler(access: AccessRule, scope: SubjectScope) {
28
+ return defineWriteHandler<"sign-in-person", typeof SignInPersonSchema, SignInPersonData>({
29
+ name: "sign-in-person",
30
+ schema: SignInPersonSchema,
31
+ access,
32
+ agent: { expose: false },
33
+ description:
34
+ "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.",
35
+ handler: async (event, ctx) => {
36
+ const user = event.user;
37
+ const signer = await signerExecutor.detail({ id: event.payload.signerId }, user, ctx.db);
38
+ if (signer === null) return writeFailure(new NotFoundError("signer", event.payload.signerId));
39
+ const request = await loadRequestOfSigner(ctx, user, signer);
40
+ if (request !== null && !(await scope.allowsRequest(ctx, user, request))) {
41
+ return writeFailure(new NotFoundError("signer", event.payload.signerId));
42
+ }
43
+ const now = ctx.tz.now();
44
+ if (request === null || !isOpenRequest(request, now) || !isUnsignedSigner(signer)) {
45
+ return writeFailure(new UnprocessableError("signature_not_possible"));
46
+ }
47
+ const png = decodeSignatureImage(event.payload.imagePngBase64);
48
+ if (png === null) return invalidImage();
49
+
50
+ const image = await storeSignatureImage(ctx, user, png);
51
+ if (!image.isSuccess) return image;
52
+ const recorded = await recordInPersonSignature(ctx, user, signer, {
53
+ method: SIGNATURE_METHOD.InPerson,
54
+ imageFileId: image.data.id,
55
+ signedAt: now,
56
+ });
57
+ if (!recorded.isSuccess) {
58
+ await discardGeneratedFile(ctx, user, image.data);
59
+ return recorded;
60
+ }
61
+
62
+ const allSigned = await advanceIfAllSigned(ctx, user, request.id);
63
+ return {
64
+ isSuccess: true,
65
+ data: {
66
+ requestStatus: allSigned
67
+ ? SIGNATURE_REQUEST_STATUS.AllSigned
68
+ : SIGNATURE_REQUEST_STATUS.Open,
69
+ },
70
+ };
71
+ },
72
+ });
73
+ }