@cosmicdrift/kumiko-samples 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 (62) 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/signature/README.md +59 -0
  17. package/packages/bundled-features/src/signature/changes.json +15 -0
  18. package/packages/bundled-features/src/signature/entity.ts +192 -0
  19. package/packages/bundled-features/src/signature/feature.ts +125 -0
  20. package/packages/bundled-features/src/signature/files.ts +107 -0
  21. package/packages/bundled-features/src/signature/grant.ts +79 -0
  22. package/packages/bundled-features/src/signature/handlers/anonymous.write.ts +88 -0
  23. package/packages/bundled-features/src/signature/handlers/cancel.write.ts +40 -0
  24. package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +72 -0
  25. package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +99 -0
  26. package/packages/bundled-features/src/signature/handlers/link-internal.write.ts +261 -0
  27. package/packages/bundled-features/src/signature/handlers/request.write.ts +86 -0
  28. package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +23 -0
  29. package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +69 -0
  30. package/packages/bundled-features/src/signature/i18n.ts +52 -0
  31. package/packages/bundled-features/src/signature/index.ts +33 -0
  32. package/packages/bundled-features/src/signature/lib.ts +125 -0
  33. package/packages/bundled-features/src/signature/options.ts +49 -0
  34. package/packages/bundled-features/src/signature/payloads.ts +71 -0
  35. package/packages/bundled-features/src/signature/png.ts +169 -0
  36. package/packages/bundled-features/src/signature/screens.ts +115 -0
  37. package/packages/bundled-features/src/signature/signature-page.ts +93 -0
  38. package/packages/bundled-features/src/signature/signing.ts +77 -0
  39. package/packages/bundled-features/src/signature/static-sign.ts +98 -0
  40. package/packages/bundled-features/src/signature/sweep.ts +161 -0
  41. package/packages/bundled-features/src/signature/user-data.ts +159 -0
  42. package/packages/bundled-features/src/signature/web/constants.ts +92 -0
  43. package/packages/bundled-features/src/signature/web/index.ts +31 -0
  44. package/packages/bundled-features/src/signature/web/pad.ts +147 -0
  45. package/packages/bundled-features/src/signature/web/signature-pad.tsx +82 -0
  46. package/packages/bundled-features/src/subscription-stripe/changes.json +6 -0
  47. package/packages/bundled-features/src/subscription-stripe/feature.ts +9 -0
  48. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +7 -1
  49. package/samples/apps/use-all-bundled/feature-manifest.json +63 -1
  50. package/samples/apps/use-all-bundled/kumiko/migrations/0068_signature.rebuild.json +4 -0
  51. package/samples/apps/use-all-bundled/src/run-config.ts +35 -1
  52. package/samples/recipes/embedded/README.md +4 -0
  53. package/samples/recipes/embedded/src/entities/invoice.ts +6 -0
  54. package/samples/recipes/embedded/src/feature.ts +7 -1
  55. package/samples/recipes/embedded/src/handlers/invoice-receive.write.ts +1 -0
  56. package/samples/recipes/embedded/src/screens/invoice-receive.screen.ts +2 -0
  57. package/samples/recipes/handbook-knowledge/README.md +22 -0
  58. package/samples/recipes/handbook-knowledge/package.json +12 -0
  59. package/samples/recipes/handbook-knowledge/src/feature.ts +42 -0
  60. package/samples/recipes/signature/README.md +21 -0
  61. package/samples/recipes/signature/package.json +13 -0
  62. package/samples/recipes/signature/src/feature.ts +26 -0
@@ -0,0 +1,77 @@
1
+ import { requestContext } from "@cosmicdrift/kumiko-framework/api";
2
+ import type { TenantDb } from "@cosmicdrift/kumiko-framework/db";
3
+ import type { SessionUser } from "@cosmicdrift/kumiko-framework/engine";
4
+ import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
5
+ import type { Temporal } from "@cosmicdrift/kumiko-types/temporal";
6
+ import { signerExecutor } from "./entity.ts";
7
+ import { type GeneratedFileContext, storeGeneratedFile } from "./files.ts";
8
+ import { type SignerRow, versionOf } from "./lib.ts";
9
+ import { checkSignaturePng, decodeSignaturePngBase64 } from "./png.ts";
10
+ import {
11
+ SIGNATURE_INVALID_IMAGE_REASON,
12
+ SIGNATURE_SIGNER_STATUS,
13
+ type SignatureMethod,
14
+ } from "./web/constants.ts";
15
+
16
+ export function invalidImage() {
17
+ return writeFailure(new UnprocessableError(SIGNATURE_INVALID_IMAGE_REASON));
18
+ }
19
+
20
+ export function decodeSignatureImage(imagePngBase64: string): Uint8Array | null {
21
+ const bytes = decodeSignaturePngBase64(imagePngBase64);
22
+ if (bytes === null) return null;
23
+ return checkSignaturePng(bytes).ok ? bytes : null;
24
+ }
25
+
26
+ // IP and user agent come from the HTTP request, not from the payload, so a client cannot choose them.
27
+ export function auditValuesOfRequest(): Record<string, string> {
28
+ const scope = requestContext.get();
29
+ return {
30
+ ...(scope?.ip !== undefined && { signedFromIp: scope.ip }),
31
+ ...(scope?.userAgent !== undefined && { signedUserAgent: scope.userAgent }),
32
+ };
33
+ }
34
+
35
+ export type SignatureWrite = {
36
+ readonly method: SignatureMethod;
37
+ readonly imageFileId: string;
38
+ readonly signedAt: Temporal.Instant;
39
+ };
40
+
41
+ export function signatureChanges(write: SignatureWrite): Record<string, unknown> {
42
+ return {
43
+ status: SIGNATURE_SIGNER_STATUS.Signed,
44
+ method: write.method,
45
+ signedAt: write.signedAt,
46
+ imageFileId: write.imageFileId,
47
+ linkAnchor: null,
48
+ ...auditValuesOfRequest(),
49
+ };
50
+ }
51
+
52
+ export async function storeSignatureImage(
53
+ ctx: GeneratedFileContext,
54
+ user: SessionUser,
55
+ png: Uint8Array,
56
+ ) {
57
+ return storeGeneratedFile(ctx, user, {
58
+ fileName: "signature.png",
59
+ mimeType: "image/png",
60
+ data: png,
61
+ });
62
+ }
63
+
64
+ // Records the signature of an in-person signer. A concurrent change of the row makes the executor
65
+ // refuse the stale version, so a double submit signs once.
66
+ export function recordInPersonSignature(
67
+ ctx: { readonly db: TenantDb },
68
+ user: SessionUser,
69
+ signer: SignerRow,
70
+ write: SignatureWrite,
71
+ ) {
72
+ return signerExecutor.update(
73
+ { id: signer.id, version: versionOf(signer), changes: signatureChanges(write) },
74
+ user,
75
+ ctx.db,
76
+ );
77
+ }
@@ -0,0 +1,98 @@
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
+
5
+ import {
6
+ dispatchWrite,
7
+ type StaticRequestOptions,
8
+ type StaticResult,
9
+ staticFailure,
10
+ staticSuccess,
11
+ takeUrlToken,
12
+ } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
13
+ import { SignatureHandlers } from "./web/constants.ts";
14
+
15
+ export {
16
+ hrefWithoutUrlToken,
17
+ readUrlToken,
18
+ STATIC_NETWORK_REASON,
19
+ STATIC_RATE_LIMITED_REASON,
20
+ type StaticFailure,
21
+ type StaticRequestOptions,
22
+ type StaticResult,
23
+ type StaticSuccess,
24
+ } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
25
+ export {
26
+ bytesToBase64,
27
+ createSignaturePad,
28
+ type SignaturePad,
29
+ type SignaturePadCanvas,
30
+ type SignaturePadOptions,
31
+ } from "./web/pad.ts";
32
+
33
+ export type SignatureLinkView = {
34
+ readonly title: string;
35
+ readonly signerName: string;
36
+ readonly role: string | null;
37
+ /** Short-lived URL of the PDF; null when the storage provider cannot sign URLs. */
38
+ readonly documentUrl: string | null;
39
+ };
40
+
41
+ /** Reads `#token=` from the current page and removes it from the address bar. Browser only. */
42
+ export function takeSignatureToken(): string {
43
+ return takeUrlToken("fragment");
44
+ }
45
+
46
+ function isRecord(value: unknown): value is Record<string, unknown> {
47
+ return typeof value === "object" && value !== null;
48
+ }
49
+
50
+ function parseLinkView(data: unknown): SignatureLinkView | null {
51
+ if (!isRecord(data)) return null;
52
+ const { title, signerName, role, documentUrl } = data;
53
+ if (typeof title !== "string" || typeof signerName !== "string") return null;
54
+ return {
55
+ title,
56
+ signerName,
57
+ role: typeof role === "string" ? role : null,
58
+ documentUrl: typeof documentUrl === "string" ? documentUrl : null,
59
+ };
60
+ }
61
+
62
+ /** Counts a view but does not use up the link. A bad, used or expired link fails with `invalid_or_expired_link`. */
63
+ export async function openSignatureLink(
64
+ token: string,
65
+ options?: StaticRequestOptions,
66
+ ): Promise<StaticResult<SignatureLinkView>> {
67
+ const result = await dispatchWrite(SignatureHandlers.openByLink, { token }, options);
68
+ if (result.kind !== "success") return result;
69
+ const view = parseLinkView(result.data);
70
+ return view === null ? staticFailure("unknown") : staticSuccess(view);
71
+ }
72
+
73
+ /** `imagePngBase64` comes from `SignaturePad.toPngBase64()`. Uses up the link on success. */
74
+ export async function signByLink(
75
+ token: string,
76
+ imagePngBase64: string,
77
+ options?: StaticRequestOptions,
78
+ ): Promise<StaticResult<undefined>> {
79
+ const result = await dispatchWrite(
80
+ SignatureHandlers.signByLink,
81
+ { token, imagePngBase64 },
82
+ options,
83
+ );
84
+ return result.kind === "success" ? staticSuccess(undefined) : result;
85
+ }
86
+
87
+ export async function declineByLink(
88
+ token: string,
89
+ reason?: string,
90
+ options?: StaticRequestOptions,
91
+ ): Promise<StaticResult<undefined>> {
92
+ const result = await dispatchWrite(
93
+ SignatureHandlers.declineByLink,
94
+ { token, ...(reason !== undefined && reason !== "" && { reason }) },
95
+ options,
96
+ );
97
+ return result.kind === "success" ? staticSuccess(undefined) : result;
98
+ }
@@ -0,0 +1,161 @@
1
+ import type { JobContext } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
3
+ import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
4
+ import { requestExecutor } from "./entity.ts";
5
+ import {
6
+ discardGeneratedFile,
7
+ PDF_MIME_TYPE,
8
+ readTenantFile,
9
+ sha256Hex,
10
+ storeGeneratedFile,
11
+ } from "./files.ts";
12
+ import {
13
+ instantOrNull,
14
+ isPastInstant,
15
+ listSigners,
16
+ type RequestRow,
17
+ type SignerRow,
18
+ } from "./lib.ts";
19
+ import type { SignatureOptions } from "./options.ts";
20
+ import {
21
+ appendPdfPages,
22
+ buildSignaturePageHtml,
23
+ DEFAULT_SIGNATURE_PAGE_LABELS,
24
+ type SignaturePageEntry,
25
+ } from "./signature-page.ts";
26
+ import {
27
+ SIGNATURE_METHOD,
28
+ SIGNATURE_REQUEST_STATUS,
29
+ SignatureInternalHandlers,
30
+ } from "./web/constants.ts";
31
+
32
+ // Equals the executor's MAX_LIST_LIMIT.
33
+ const SWEEP_PAGE_SIZE = 200;
34
+
35
+ type RequestPage = Awaited<ReturnType<typeof requestExecutor.list>>;
36
+
37
+ // Keyset-paged, so rows that leave the status while the sweep works on them cannot shift the next page.
38
+ async function forEachRequestWithStatus(
39
+ ctx: JobContext,
40
+ status: string,
41
+ visit: (request: RequestRow) => Promise<void>,
42
+ ): Promise<void> {
43
+ let cursor: string | null = null;
44
+ do {
45
+ const page: RequestPage = await requestExecutor.list(
46
+ {
47
+ filter: { field: "status", op: "eq", value: status },
48
+ limit: SWEEP_PAGE_SIZE,
49
+ ...(cursor !== null && { cursor }),
50
+ },
51
+ ctx.systemUser,
52
+ ctx.db,
53
+ );
54
+ for (const request of page.rows) await visit(request);
55
+ cursor = page.nextCursor;
56
+ } while (cursor !== null);
57
+ }
58
+
59
+ function bySignedAt(left: SignerRow, right: SignerRow): number {
60
+ const a = instantOrNull(left.signedAt);
61
+ const b = instantOrNull(right.signedAt);
62
+ if (a === null || b === null) return 0;
63
+ return Temporal.Instant.compare(a, b);
64
+ }
65
+
66
+ async function signaturePageEntries(
67
+ ctx: JobContext,
68
+ signers: readonly SignerRow[],
69
+ ): Promise<readonly SignaturePageEntry[] | null> {
70
+ const entries: SignaturePageEntry[] = [];
71
+ for (const signer of [...signers].sort(bySignedAt)) {
72
+ const signedAt = instantOrNull(signer.signedAt);
73
+ if (signedAt === null || typeof signer.imageFileId !== "string") return null;
74
+ const image = await readTenantFile(ctx, ctx.systemUser.tenantId, signer.imageFileId);
75
+ if (image === null) return null;
76
+ entries.push({
77
+ name: signer.name,
78
+ role: signer.role ?? null,
79
+ signedAtIso: signedAt.toString(),
80
+ method:
81
+ signer.method === SIGNATURE_METHOD.Link ? SIGNATURE_METHOD.Link : SIGNATURE_METHOD.InPerson,
82
+ imagePng: image.content,
83
+ });
84
+ }
85
+ return entries;
86
+ }
87
+
88
+ // Appends the signature page to the unchanged original. A renderer outage throws, the request
89
+ // stays all-signed and the next run tries again.
90
+ async function finalizeRequest(
91
+ ctx: JobContext,
92
+ opts: SignatureOptions,
93
+ request: RequestRow,
94
+ ): Promise<void> {
95
+ const original = await readTenantFile(ctx, ctx.systemUser.tenantId, request.documentFileId);
96
+ if (original === null || sha256Hex(original.content) !== request.documentSha256) {
97
+ ctx.obs.log.warn("[signature:sweep] original document missing or changed, not completing", {
98
+ requestId: request.id,
99
+ });
100
+ return;
101
+ }
102
+ const entries = await signaturePageEntries(
103
+ ctx,
104
+ await listSigners(ctx, ctx.systemUser, request.id),
105
+ );
106
+ if (entries === null) {
107
+ ctx.obs.log.warn("[signature:sweep] signature image missing, not completing", {
108
+ requestId: request.id,
109
+ });
110
+ return;
111
+ }
112
+ const html = buildSignaturePageHtml({
113
+ title: request.title,
114
+ documentSha256: request.documentSha256,
115
+ entries,
116
+ labels: DEFAULT_SIGNATURE_PAGE_LABELS,
117
+ });
118
+ const signaturePages = await opts.renderHtmlToPdf(html);
119
+ const completed = await appendPdfPages(original.content, signaturePages);
120
+ const stored = await storeGeneratedFile(ctx, ctx.systemUser, {
121
+ fileName: "signed-document.pdf",
122
+ mimeType: PDF_MIME_TYPE,
123
+ data: completed,
124
+ });
125
+ if (!stored.isSuccess) {
126
+ ctx.obs.log.warn("[signature:sweep] storing the completed pdf failed", {
127
+ requestId: request.id,
128
+ });
129
+ return;
130
+ }
131
+ const finished = await ctx.dispatch.write(SignatureInternalHandlers.finish, {
132
+ requestId: request.id,
133
+ completedFileId: stored.data.id,
134
+ });
135
+ if (!finished.isSuccess || propertyOf(finished.data, "finished") !== true) {
136
+ await discardGeneratedFile(ctx, ctx.systemUser, stored.data);
137
+ }
138
+ }
139
+
140
+ export async function sweepSignatureRequests(
141
+ ctx: JobContext,
142
+ opts: SignatureOptions,
143
+ ): Promise<void> {
144
+ const now = ctx.tz.now();
145
+ await forEachRequestWithStatus(ctx, SIGNATURE_REQUEST_STATUS.Open, async (request) => {
146
+ const qn = isPastInstant(request.expiresAt, now)
147
+ ? SignatureInternalHandlers.expire
148
+ : SignatureInternalHandlers.reconcile;
149
+ await ctx.dispatch.write(qn, { requestId: request.id });
150
+ });
151
+ await forEachRequestWithStatus(ctx, SIGNATURE_REQUEST_STATUS.AllSigned, async (request) => {
152
+ try {
153
+ await finalizeRequest(ctx, opts, request);
154
+ } catch (error) {
155
+ ctx.obs.log.warn("[signature:sweep] completing failed, retrying on the next run", {
156
+ requestId: request.id,
157
+ error: error instanceof Error ? error.message : String(error),
158
+ });
159
+ }
160
+ });
161
+ }
@@ -0,0 +1,159 @@
1
+ import { configuredPiiSubjectKms } from "@cosmicdrift/kumiko-framework/crypto";
2
+ import { WritePurposes } from "@cosmicdrift/kumiko-framework/db";
3
+ import { deleteStoredFileAndDerivatives } from "@cosmicdrift/kumiko-framework/derivatives";
4
+ import {
5
+ createSystemUser,
6
+ type SessionUser,
7
+ type UserDataDeleteHook,
8
+ type UserDataExportHook,
9
+ type UserDataHookCtx,
10
+ } from "@cosmicdrift/kumiko-framework/engine";
11
+ import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
12
+ import { fileRefsTable } from "@cosmicdrift/kumiko-framework/files";
13
+ import { collectErasureFailure, throwIfErasureFailed } from "../shared/index.ts";
14
+ import { resolveVerifiedUserEmail } from "../user/index.ts";
15
+ import { requestExecutor, signatureSignerTable, signerExecutor } from "./entity.ts";
16
+ import { deleteFileRef } from "./files.ts";
17
+ import { setRequestStatus } from "./lib.ts";
18
+ import { SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_ENTITY } from "./web/constants.ts";
19
+
20
+ const PII_DECRYPT_REASON = "signature:user-data";
21
+ const ANONYMIZED_NAME = "anonymized";
22
+ const ERASE_REASON = "signature:subject-forget";
23
+
24
+ type SignerRecord = Record<string, unknown>;
25
+
26
+ // A signer has no user account: the only link to a user is the signer's email, which is stored
27
+ // lowercase and findable by exact match. Without a verified email nothing matches.
28
+ async function findSignerRows(ctx: UserDataHookCtx): Promise<readonly SignerRecord[]> {
29
+ const email = await resolveVerifiedUserEmail(ctx, PII_DECRYPT_REASON);
30
+ if (email === null) return [];
31
+ return ctx.db.selectMany<SignerRecord>(signatureSignerTable, {
32
+ tenantId: ctx.tenantId,
33
+ email: email.toLowerCase(),
34
+ });
35
+ }
36
+
37
+ function stringOrNull(value: unknown): string | null {
38
+ return typeof value === "string" ? value : null;
39
+ }
40
+
41
+ // The signer's fields belong to the row's own record key, not to the user's key, so the user
42
+ // forget run does not shred them; and anonymizing only empties the current row, the old events
43
+ // still hold the ciphertext. Without a mounted KMS this erases nothing: record-owned fields stay
44
+ // plaintext framework-wide (see notes-history-user-data), so apps that need Art. 17 coverage mount one.
45
+ async function shredSignerKey(ctx: UserDataHookCtx, signerId: string): Promise<void> {
46
+ // skip: no KMS adapter mounted, nothing is encrypted per record
47
+ await configuredPiiSubjectKms()?.eraseKey(
48
+ { kind: "record", entity: SIGNATURE_SIGNER_ENTITY, id: signerId },
49
+ { requestId: ERASE_REASON, userId: ctx.userId, eraseReason: ERASE_REASON },
50
+ );
51
+ }
52
+
53
+ export const signatureExportHook: UserDataExportHook = async (ctx) => {
54
+ const rows = await findSignerRows(ctx);
55
+ if (rows.length === 0) return null;
56
+ return {
57
+ entity: SIGNATURE_SIGNER_ENTITY,
58
+ rows: rows.map((row) => ({
59
+ requestId: row["requestId"],
60
+ name: row["name"],
61
+ role: row["role"],
62
+ status: row["status"],
63
+ method: row["method"],
64
+ signedAt: String(row["signedAt"] ?? ""),
65
+ signedFromIp: row["signedFromIp"],
66
+ signedUserAgent: row["signedUserAgent"],
67
+ declineReason: row["declineReason"],
68
+ })),
69
+ };
70
+ };
71
+
72
+ async function purgeSignatureImage(
73
+ ctx: UserDataHookCtx,
74
+ systemUser: SessionUser,
75
+ imageFileId: string,
76
+ ): Promise<void> {
77
+ const [ref] = await ctx.db.selectMany<{ id: string; storageKey: string }>(fileRefsTable, {
78
+ id: imageFileId,
79
+ });
80
+ // skip: the image is already gone, nothing left to erase
81
+ if (ref === undefined) return;
82
+ const provider = await ctx.buildStorageProvider?.(ctx.tenantId);
83
+ if (!provider) {
84
+ throw new InternalError({
85
+ message: `[signature:user-data] no file storage resolvable, signature image ${imageFileId} cannot be erased`,
86
+ });
87
+ }
88
+ const failed = await deleteStoredFileAndDerivatives(ref.storageKey, provider, PII_DECRYPT_REASON);
89
+ if (failed.length > 0) {
90
+ throw new InternalError({
91
+ message: `[signature:user-data] ${failed.length} byte delete(s) failed for signature image ${imageFileId}`,
92
+ });
93
+ }
94
+ await deleteFileRef(ctx.db, systemUser, imageFileId);
95
+ }
96
+
97
+ async function cancelUnfinishedRequest(
98
+ ctx: UserDataHookCtx,
99
+ systemUser: SessionUser,
100
+ requestId: string,
101
+ ): Promise<void> {
102
+ const request = await requestExecutor.detail({ id: requestId }, systemUser, ctx.db);
103
+ const status = request?.status;
104
+ if (status !== SIGNATURE_REQUEST_STATUS.Open && status !== SIGNATURE_REQUEST_STATUS.AllSigned) {
105
+ return;
106
+ }
107
+ await setRequestStatus(ctx, systemUser, requestId, status, {
108
+ status: SIGNATURE_REQUEST_STATUS.Cancelled,
109
+ });
110
+ }
111
+
112
+ // Erasure wins over retention for the person's own data: name, email, drawn image, IP address,
113
+ // user agent and refusal reason are removed (strategy delete: the whole row). What stays is the
114
+ // completed PDF with its signature page, which belongs to the request's owner as proof of the
115
+ // contract (Art. 17(3)(e) GDPR), and the row's status and timestamps under "anonymize". A forgotten
116
+ // signer would let the others complete the request without them (delete) or leave an all-signed
117
+ // request without the image it needs (anonymize), so an open or all-signed request is cancelled.
118
+ export const signatureDeleteHook: UserDataDeleteHook = async (ctx, strategy) => {
119
+ const systemUser = createSystemUser(ctx.tenantId);
120
+ const failures: string[] = [];
121
+ for (const row of await findSignerRows(ctx)) {
122
+ const id = stringOrNull(row["id"]);
123
+ if (id === null) continue;
124
+ const imageFileId = stringOrNull(row["imageFileId"]);
125
+ if (imageFileId !== null) await purgeSignatureImage(ctx, systemUser, imageFileId);
126
+ const requestId = stringOrNull(row["requestId"]);
127
+ if (strategy === "delete") {
128
+ const forgotten = await signerExecutor.forget({ id }, systemUser, ctx.db);
129
+ collectErasureFailure(forgotten, SIGNATURE_SIGNER_ENTITY, id, failures);
130
+ if (forgotten.isSuccess && requestId !== null) {
131
+ await cancelUnfinishedRequest(ctx, systemUser, requestId);
132
+ }
133
+ if (forgotten.isSuccess) await shredSignerKey(ctx, id);
134
+ continue;
135
+ }
136
+ const anonymized = await signerExecutor.update(
137
+ {
138
+ id,
139
+ changes: {
140
+ name: ANONYMIZED_NAME,
141
+ email: null,
142
+ imageFileId: null,
143
+ signedFromIp: null,
144
+ signedUserAgent: null,
145
+ declineReason: null,
146
+ linkAnchor: null,
147
+ },
148
+ },
149
+ systemUser,
150
+ ctx.db,
151
+ { skipOptimisticLock: true, writePurpose: WritePurposes.erasure },
152
+ );
153
+ collectErasureFailure(anonymized, SIGNATURE_SIGNER_ENTITY, id, failures);
154
+ if (!anonymized.isSuccess) continue;
155
+ if (requestId !== null) await cancelUnfinishedRequest(ctx, systemUser, requestId);
156
+ await shredSignerKey(ctx, id);
157
+ }
158
+ throwIfErasureFailed(failures);
159
+ };
@@ -0,0 +1,92 @@
1
+ // Pure string constants, safe for browser code (static-sign imports this file).
2
+ export const SIGNATURE_FEATURE = "signature" as const;
3
+
4
+ export const SIGNATURE_REQUEST_ENTITY = "signatureRequest" as const;
5
+ export const SIGNATURE_SIGNER_ENTITY = "signatureSigner" as const;
6
+
7
+ export const SIGNATURE_LEVEL = {
8
+ Simple: "simple",
9
+ } as const;
10
+
11
+ export type SignatureLevel = (typeof SIGNATURE_LEVEL)[keyof typeof SIGNATURE_LEVEL];
12
+
13
+ export const SIGNATURE_REQUEST_STATUS = {
14
+ Open: "open",
15
+ AllSigned: "all-signed",
16
+ Completed: "completed",
17
+ Declined: "declined",
18
+ Expired: "expired",
19
+ Cancelled: "cancelled",
20
+ } as const;
21
+
22
+ export type SignatureRequestStatus =
23
+ (typeof SIGNATURE_REQUEST_STATUS)[keyof typeof SIGNATURE_REQUEST_STATUS];
24
+
25
+ export const SIGNATURE_SIGNER_STATUS = {
26
+ Pending: "pending",
27
+ Viewed: "viewed",
28
+ Signed: "signed",
29
+ Declined: "declined",
30
+ } as const;
31
+
32
+ export type SignatureSignerStatus =
33
+ (typeof SIGNATURE_SIGNER_STATUS)[keyof typeof SIGNATURE_SIGNER_STATUS];
34
+
35
+ export const SIGNATURE_METHOD = {
36
+ InPerson: "in-person",
37
+ Link: "link",
38
+ } as const;
39
+
40
+ export type SignatureMethod = (typeof SIGNATURE_METHOD)[keyof typeof SIGNATURE_METHOD];
41
+
42
+ export const SignatureHandlers = {
43
+ request: `${SIGNATURE_FEATURE}:write:request`,
44
+ signInPerson: `${SIGNATURE_FEATURE}:write:sign-in-person`,
45
+ issueLink: `${SIGNATURE_FEATURE}:write:issue-link`,
46
+ revokeLink: `${SIGNATURE_FEATURE}:write:revoke-link`,
47
+ cancel: `${SIGNATURE_FEATURE}:write:cancel`,
48
+ openByLink: `${SIGNATURE_FEATURE}:write:open-by-link`,
49
+ signByLink: `${SIGNATURE_FEATURE}:write:sign-by-link`,
50
+ declineByLink: `${SIGNATURE_FEATURE}:write:decline-by-link`,
51
+ } as const;
52
+
53
+ export const SignatureQueries = {
54
+ list: `${SIGNATURE_FEATURE}:query:signature-request:list`,
55
+ detail: `${SIGNATURE_FEATURE}:query:signature-request:detail`,
56
+ signerList: `${SIGNATURE_FEATURE}:query:signature-signer:list`,
57
+ } as const;
58
+
59
+ export const SignatureJobs = {
60
+ sweep: `${SIGNATURE_FEATURE}:job:sweep`,
61
+ } as const;
62
+
63
+ export const SIGNATURE_EVENT_SHORT = {
64
+ completed: "completed",
65
+ declined: "declined",
66
+ expired: "expired",
67
+ } as const;
68
+
69
+ export const SignatureEvents = {
70
+ completed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.completed}`,
71
+ declined: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.declined}`,
72
+ expired: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.expired}`,
73
+ } as const;
74
+
75
+ // Every link rejection (forged, expired, revoked, used up, already signed) carries this reason, so
76
+ // a caller cannot tell the cases apart.
77
+ export const SIGNATURE_INVALID_LINK_REASON = "invalid_or_expired_link";
78
+
79
+ export const SIGNATURE_INVALID_IMAGE_REASON = "invalid_signature_image";
80
+
81
+ export const SIGNATURE_LINK_TTL_DAYS = 14;
82
+ export const SIGNATURE_MAX_LINK_OPENS = 20;
83
+ export const SIGNATURE_DEFAULT_VALIDITY_DAYS = 14;
84
+
85
+ export const SignatureInternalHandlers = {
86
+ linkOpen: `${SIGNATURE_FEATURE}:write:link-open`,
87
+ linkSign: `${SIGNATURE_FEATURE}:write:link-sign`,
88
+ linkDecline: `${SIGNATURE_FEATURE}:write:link-decline`,
89
+ finish: `${SIGNATURE_FEATURE}:write:finish`,
90
+ expire: `${SIGNATURE_FEATURE}:write:expire`,
91
+ reconcile: `${SIGNATURE_FEATURE}:write:reconcile`,
92
+ } as const;
@@ -0,0 +1,31 @@
1
+ export {
2
+ SIGNATURE_DEFAULT_VALIDITY_DAYS,
3
+ SIGNATURE_EVENT_SHORT,
4
+ SIGNATURE_FEATURE,
5
+ SIGNATURE_INVALID_IMAGE_REASON,
6
+ SIGNATURE_INVALID_LINK_REASON,
7
+ SIGNATURE_LEVEL,
8
+ SIGNATURE_LINK_TTL_DAYS,
9
+ SIGNATURE_MAX_LINK_OPENS,
10
+ SIGNATURE_METHOD,
11
+ SIGNATURE_REQUEST_ENTITY,
12
+ SIGNATURE_REQUEST_STATUS,
13
+ SIGNATURE_SIGNER_ENTITY,
14
+ SIGNATURE_SIGNER_STATUS,
15
+ SignatureEvents,
16
+ SignatureHandlers,
17
+ SignatureInternalHandlers,
18
+ SignatureJobs,
19
+ type SignatureLevel,
20
+ type SignatureMethod,
21
+ SignatureQueries,
22
+ type SignatureRequestStatus,
23
+ type SignatureSignerStatus,
24
+ } from "./constants.ts";
25
+ export type { SignaturePad as SignaturePadController, SignaturePadOptions } from "./pad.ts";
26
+ export {
27
+ DEFAULT_SIGNATURE_PAD_LABELS,
28
+ SignaturePad,
29
+ type SignaturePadLabels,
30
+ type SignaturePadProps,
31
+ } from "./signature-pad.tsx";