@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,113 @@
1
+ import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
2
+ import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
3
+ import { requestExecutor } from "./entity.js";
4
+ import { discardGeneratedFile, PDF_MIME_TYPE, readTenantFile, sha256Hex, storeGeneratedFile, } from "./files.js";
5
+ import { instantOrNull, isPastInstant, listSigners, } from "./lib.js";
6
+ import { appendPdfPages, buildSignaturePageHtml, DEFAULT_SIGNATURE_PAGE_LABELS, } from "./signature-page.js";
7
+ import { SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS, SignatureInternalHandlers, } from "./web/constants.js";
8
+ // Equals the executor's MAX_LIST_LIMIT.
9
+ const SWEEP_PAGE_SIZE = 200;
10
+ // Keyset-paged, so rows that leave the status while the sweep works on them cannot shift the next page.
11
+ async function forEachRequestWithStatus(ctx, status, visit) {
12
+ let cursor = null;
13
+ do {
14
+ const page = await requestExecutor.list({
15
+ filter: { field: "status", op: "eq", value: status },
16
+ limit: SWEEP_PAGE_SIZE,
17
+ ...(cursor !== null && { cursor }),
18
+ }, ctx.systemUser, ctx.db);
19
+ for (const request of page.rows)
20
+ await visit(request);
21
+ cursor = page.nextCursor;
22
+ } while (cursor !== null);
23
+ }
24
+ function bySignedAt(left, right) {
25
+ const a = instantOrNull(left.signedAt);
26
+ const b = instantOrNull(right.signedAt);
27
+ if (a === null || b === null)
28
+ return 0;
29
+ return Temporal.Instant.compare(a, b);
30
+ }
31
+ async function signaturePageEntries(ctx, signers) {
32
+ const entries = [];
33
+ for (const signer of [...signers].sort(bySignedAt)) {
34
+ const signedAt = instantOrNull(signer.signedAt);
35
+ if (signedAt === null || typeof signer.imageFileId !== "string")
36
+ return null;
37
+ const image = await readTenantFile(ctx, ctx.systemUser.tenantId, signer.imageFileId);
38
+ if (image === null)
39
+ return null;
40
+ entries.push({
41
+ name: signer.name,
42
+ role: signer.role ?? null,
43
+ signedAtIso: signedAt.toString(),
44
+ method: signer.method === SIGNATURE_METHOD.Link ? SIGNATURE_METHOD.Link : SIGNATURE_METHOD.InPerson,
45
+ imagePng: image.content,
46
+ });
47
+ }
48
+ return entries;
49
+ }
50
+ // Appends the signature page to the unchanged original. A renderer outage throws, the request
51
+ // stays all-signed and the next run tries again.
52
+ async function finalizeRequest(ctx, opts, request) {
53
+ const original = await readTenantFile(ctx, ctx.systemUser.tenantId, request.documentFileId);
54
+ if (original === null || sha256Hex(original.content) !== request.documentSha256) {
55
+ ctx.obs.log.warn("[signature:sweep] original document missing or changed, not completing", {
56
+ requestId: request.id,
57
+ });
58
+ return;
59
+ }
60
+ const entries = await signaturePageEntries(ctx, await listSigners(ctx, ctx.systemUser, request.id));
61
+ if (entries === null) {
62
+ ctx.obs.log.warn("[signature:sweep] signature image missing, not completing", {
63
+ requestId: request.id,
64
+ });
65
+ return;
66
+ }
67
+ const html = buildSignaturePageHtml({
68
+ title: request.title,
69
+ documentSha256: request.documentSha256,
70
+ entries,
71
+ labels: DEFAULT_SIGNATURE_PAGE_LABELS,
72
+ });
73
+ const signaturePages = await opts.renderHtmlToPdf(html);
74
+ const completed = await appendPdfPages(original.content, signaturePages);
75
+ const stored = await storeGeneratedFile(ctx, ctx.systemUser, {
76
+ fileName: "signed-document.pdf",
77
+ mimeType: PDF_MIME_TYPE,
78
+ data: completed,
79
+ });
80
+ if (!stored.isSuccess) {
81
+ ctx.obs.log.warn("[signature:sweep] storing the completed pdf failed", {
82
+ requestId: request.id,
83
+ });
84
+ return;
85
+ }
86
+ const finished = await ctx.dispatch.write(SignatureInternalHandlers.finish, {
87
+ requestId: request.id,
88
+ completedFileId: stored.data.id,
89
+ });
90
+ if (!finished.isSuccess || propertyOf(finished.data, "finished") !== true) {
91
+ await discardGeneratedFile(ctx, ctx.systemUser, stored.data);
92
+ }
93
+ }
94
+ export async function sweepSignatureRequests(ctx, opts) {
95
+ const now = ctx.tz.now();
96
+ await forEachRequestWithStatus(ctx, SIGNATURE_REQUEST_STATUS.Open, async (request) => {
97
+ const qn = isPastInstant(request.expiresAt, now)
98
+ ? SignatureInternalHandlers.expire
99
+ : SignatureInternalHandlers.reconcile;
100
+ await ctx.dispatch.write(qn, { requestId: request.id });
101
+ });
102
+ await forEachRequestWithStatus(ctx, SIGNATURE_REQUEST_STATUS.AllSigned, async (request) => {
103
+ try {
104
+ await finalizeRequest(ctx, opts, request);
105
+ }
106
+ catch (error) {
107
+ ctx.obs.log.warn("[signature:sweep] completing failed, retrying on the next run", {
108
+ requestId: request.id,
109
+ error: error instanceof Error ? error.message : String(error),
110
+ });
111
+ }
112
+ });
113
+ }
@@ -0,0 +1,3 @@
1
+ import { type UserDataDeleteHook, type UserDataExportHook } from "@cosmicdrift/kumiko-framework/engine";
2
+ export declare const signatureExportHook: UserDataExportHook;
3
+ export declare const signatureDeleteHook: UserDataDeleteHook;
@@ -0,0 +1,135 @@
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 { createSystemUser, } from "@cosmicdrift/kumiko-framework/engine";
5
+ import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
6
+ import { fileRefsTable } from "@cosmicdrift/kumiko-framework/files";
7
+ import { collectErasureFailure, throwIfErasureFailed } from "../shared/index.js";
8
+ import { resolveVerifiedUserEmail } from "../user/index.js";
9
+ import { requestExecutor, signatureSignerTable, signerExecutor } from "./entity.js";
10
+ import { deleteFileRef } from "./files.js";
11
+ import { setRequestStatus } from "./lib.js";
12
+ import { SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_ENTITY } from "./web/constants.js";
13
+ const PII_DECRYPT_REASON = "signature:user-data";
14
+ const ANONYMIZED_NAME = "anonymized";
15
+ const ERASE_REASON = "signature:subject-forget";
16
+ // A signer has no user account: the only link to a user is the signer's email, which is stored
17
+ // lowercase and findable by exact match. Without a verified email nothing matches.
18
+ async function findSignerRows(ctx) {
19
+ const email = await resolveVerifiedUserEmail(ctx, PII_DECRYPT_REASON);
20
+ if (email === null)
21
+ return [];
22
+ return ctx.db.selectMany(signatureSignerTable, {
23
+ tenantId: ctx.tenantId,
24
+ email: email.toLowerCase(),
25
+ });
26
+ }
27
+ function stringOrNull(value) {
28
+ return typeof value === "string" ? value : null;
29
+ }
30
+ // The signer's fields belong to the row's own record key, not to the user's key, so the user
31
+ // forget run does not shred them; and anonymizing only empties the current row, the old events
32
+ // still hold the ciphertext. Without a mounted KMS this erases nothing: record-owned fields stay
33
+ // plaintext framework-wide (see notes-history-user-data), so apps that need Art. 17 coverage mount one.
34
+ async function shredSignerKey(ctx, signerId) {
35
+ // skip: no KMS adapter mounted, nothing is encrypted per record
36
+ await configuredPiiSubjectKms()?.eraseKey({ kind: "record", entity: SIGNATURE_SIGNER_ENTITY, id: signerId }, { requestId: ERASE_REASON, userId: ctx.userId, eraseReason: ERASE_REASON });
37
+ }
38
+ export const signatureExportHook = async (ctx) => {
39
+ const rows = await findSignerRows(ctx);
40
+ if (rows.length === 0)
41
+ return null;
42
+ return {
43
+ entity: SIGNATURE_SIGNER_ENTITY,
44
+ rows: rows.map((row) => ({
45
+ requestId: row["requestId"],
46
+ name: row["name"],
47
+ role: row["role"],
48
+ status: row["status"],
49
+ method: row["method"],
50
+ signedAt: String(row["signedAt"] ?? ""),
51
+ signedFromIp: row["signedFromIp"],
52
+ signedUserAgent: row["signedUserAgent"],
53
+ declineReason: row["declineReason"],
54
+ })),
55
+ };
56
+ };
57
+ async function purgeSignatureImage(ctx, systemUser, imageFileId) {
58
+ const [ref] = await ctx.db.selectMany(fileRefsTable, {
59
+ id: imageFileId,
60
+ });
61
+ // skip: the image is already gone, nothing left to erase
62
+ if (ref === undefined)
63
+ return;
64
+ const provider = await ctx.buildStorageProvider?.(ctx.tenantId);
65
+ if (!provider) {
66
+ throw new InternalError({
67
+ message: `[signature:user-data] no file storage resolvable, signature image ${imageFileId} cannot be erased`,
68
+ });
69
+ }
70
+ const failed = await deleteStoredFileAndDerivatives(ref.storageKey, provider, PII_DECRYPT_REASON);
71
+ if (failed.length > 0) {
72
+ throw new InternalError({
73
+ message: `[signature:user-data] ${failed.length} byte delete(s) failed for signature image ${imageFileId}`,
74
+ });
75
+ }
76
+ await deleteFileRef(ctx.db, systemUser, imageFileId);
77
+ }
78
+ async function cancelUnfinishedRequest(ctx, systemUser, requestId) {
79
+ const request = await requestExecutor.detail({ id: requestId }, systemUser, ctx.db);
80
+ const status = request?.status;
81
+ if (status !== SIGNATURE_REQUEST_STATUS.Open && status !== SIGNATURE_REQUEST_STATUS.AllSigned) {
82
+ return;
83
+ }
84
+ await setRequestStatus(ctx, systemUser, requestId, status, {
85
+ status: SIGNATURE_REQUEST_STATUS.Cancelled,
86
+ });
87
+ }
88
+ // Erasure wins over retention for the person's own data: name, email, drawn image, IP address,
89
+ // user agent and refusal reason are removed (strategy delete: the whole row). What stays is the
90
+ // completed PDF with its signature page, which belongs to the request's owner as proof of the
91
+ // contract (Art. 17(3)(e) GDPR), and the row's status and timestamps under "anonymize". A forgotten
92
+ // signer would let the others complete the request without them (delete) or leave an all-signed
93
+ // request without the image it needs (anonymize), so an open or all-signed request is cancelled.
94
+ export const signatureDeleteHook = async (ctx, strategy) => {
95
+ const systemUser = createSystemUser(ctx.tenantId);
96
+ const failures = [];
97
+ for (const row of await findSignerRows(ctx)) {
98
+ const id = stringOrNull(row["id"]);
99
+ if (id === null)
100
+ continue;
101
+ const imageFileId = stringOrNull(row["imageFileId"]);
102
+ if (imageFileId !== null)
103
+ await purgeSignatureImage(ctx, systemUser, imageFileId);
104
+ const requestId = stringOrNull(row["requestId"]);
105
+ if (strategy === "delete") {
106
+ const forgotten = await signerExecutor.forget({ id }, systemUser, ctx.db);
107
+ collectErasureFailure(forgotten, SIGNATURE_SIGNER_ENTITY, id, failures);
108
+ if (forgotten.isSuccess && requestId !== null) {
109
+ await cancelUnfinishedRequest(ctx, systemUser, requestId);
110
+ }
111
+ if (forgotten.isSuccess)
112
+ await shredSignerKey(ctx, id);
113
+ continue;
114
+ }
115
+ const anonymized = await signerExecutor.update({
116
+ id,
117
+ changes: {
118
+ name: ANONYMIZED_NAME,
119
+ email: null,
120
+ imageFileId: null,
121
+ signedFromIp: null,
122
+ signedUserAgent: null,
123
+ declineReason: null,
124
+ linkAnchor: null,
125
+ },
126
+ }, systemUser, ctx.db, { skipOptimisticLock: true, writePurpose: WritePurposes.erasure });
127
+ collectErasureFailure(anonymized, SIGNATURE_SIGNER_ENTITY, id, failures);
128
+ if (!anonymized.isSuccess)
129
+ continue;
130
+ if (requestId !== null)
131
+ await cancelUnfinishedRequest(ctx, systemUser, requestId);
132
+ await shredSignerKey(ctx, id);
133
+ }
134
+ throwIfErasureFailed(failures);
135
+ };
@@ -0,0 +1,69 @@
1
+ export declare const SIGNATURE_FEATURE: "signature";
2
+ export declare const SIGNATURE_REQUEST_ENTITY: "signatureRequest";
3
+ export declare const SIGNATURE_SIGNER_ENTITY: "signatureSigner";
4
+ export declare const SIGNATURE_LEVEL: {
5
+ readonly Simple: "simple";
6
+ };
7
+ export type SignatureLevel = (typeof SIGNATURE_LEVEL)[keyof typeof SIGNATURE_LEVEL];
8
+ export declare const SIGNATURE_REQUEST_STATUS: {
9
+ readonly Open: "open";
10
+ readonly AllSigned: "all-signed";
11
+ readonly Completed: "completed";
12
+ readonly Declined: "declined";
13
+ readonly Expired: "expired";
14
+ readonly Cancelled: "cancelled";
15
+ };
16
+ export type SignatureRequestStatus = (typeof SIGNATURE_REQUEST_STATUS)[keyof typeof SIGNATURE_REQUEST_STATUS];
17
+ export declare const SIGNATURE_SIGNER_STATUS: {
18
+ readonly Pending: "pending";
19
+ readonly Viewed: "viewed";
20
+ readonly Signed: "signed";
21
+ readonly Declined: "declined";
22
+ };
23
+ export type SignatureSignerStatus = (typeof SIGNATURE_SIGNER_STATUS)[keyof typeof SIGNATURE_SIGNER_STATUS];
24
+ export declare const SIGNATURE_METHOD: {
25
+ readonly InPerson: "in-person";
26
+ readonly Link: "link";
27
+ };
28
+ export type SignatureMethod = (typeof SIGNATURE_METHOD)[keyof typeof SIGNATURE_METHOD];
29
+ export declare const SignatureHandlers: {
30
+ readonly request: "signature:write:request";
31
+ readonly signInPerson: "signature:write:sign-in-person";
32
+ readonly issueLink: "signature:write:issue-link";
33
+ readonly revokeLink: "signature:write:revoke-link";
34
+ readonly cancel: "signature:write:cancel";
35
+ readonly openByLink: "signature:write:open-by-link";
36
+ readonly signByLink: "signature:write:sign-by-link";
37
+ readonly declineByLink: "signature:write:decline-by-link";
38
+ };
39
+ export declare const SignatureQueries: {
40
+ readonly list: "signature:query:signature-request:list";
41
+ readonly detail: "signature:query:signature-request:detail";
42
+ readonly signerList: "signature:query:signature-signer:list";
43
+ };
44
+ export declare const SignatureJobs: {
45
+ readonly sweep: "signature:job:sweep";
46
+ };
47
+ export declare const SIGNATURE_EVENT_SHORT: {
48
+ readonly completed: "completed";
49
+ readonly declined: "declined";
50
+ readonly expired: "expired";
51
+ };
52
+ export declare const SignatureEvents: {
53
+ readonly completed: "signature:event:completed";
54
+ readonly declined: "signature:event:declined";
55
+ readonly expired: "signature:event:expired";
56
+ };
57
+ export declare const SIGNATURE_INVALID_LINK_REASON = "invalid_or_expired_link";
58
+ export declare const SIGNATURE_INVALID_IMAGE_REASON = "invalid_signature_image";
59
+ export declare const SIGNATURE_LINK_TTL_DAYS = 14;
60
+ export declare const SIGNATURE_MAX_LINK_OPENS = 20;
61
+ export declare const SIGNATURE_DEFAULT_VALIDITY_DAYS = 14;
62
+ export declare const SignatureInternalHandlers: {
63
+ readonly linkOpen: "signature:write:link-open";
64
+ readonly linkSign: "signature:write:link-sign";
65
+ readonly linkDecline: "signature:write:link-decline";
66
+ readonly finish: "signature:write:finish";
67
+ readonly expire: "signature:write:expire";
68
+ readonly reconcile: "signature:write:reconcile";
69
+ };
@@ -0,0 +1,68 @@
1
+ // Pure string constants, safe for browser code (static-sign imports this file).
2
+ export const SIGNATURE_FEATURE = "signature";
3
+ export const SIGNATURE_REQUEST_ENTITY = "signatureRequest";
4
+ export const SIGNATURE_SIGNER_ENTITY = "signatureSigner";
5
+ export const SIGNATURE_LEVEL = {
6
+ Simple: "simple",
7
+ };
8
+ export const SIGNATURE_REQUEST_STATUS = {
9
+ Open: "open",
10
+ AllSigned: "all-signed",
11
+ Completed: "completed",
12
+ Declined: "declined",
13
+ Expired: "expired",
14
+ Cancelled: "cancelled",
15
+ };
16
+ export const SIGNATURE_SIGNER_STATUS = {
17
+ Pending: "pending",
18
+ Viewed: "viewed",
19
+ Signed: "signed",
20
+ Declined: "declined",
21
+ };
22
+ export const SIGNATURE_METHOD = {
23
+ InPerson: "in-person",
24
+ Link: "link",
25
+ };
26
+ export const SignatureHandlers = {
27
+ request: `${SIGNATURE_FEATURE}:write:request`,
28
+ signInPerson: `${SIGNATURE_FEATURE}:write:sign-in-person`,
29
+ issueLink: `${SIGNATURE_FEATURE}:write:issue-link`,
30
+ revokeLink: `${SIGNATURE_FEATURE}:write:revoke-link`,
31
+ cancel: `${SIGNATURE_FEATURE}:write:cancel`,
32
+ openByLink: `${SIGNATURE_FEATURE}:write:open-by-link`,
33
+ signByLink: `${SIGNATURE_FEATURE}:write:sign-by-link`,
34
+ declineByLink: `${SIGNATURE_FEATURE}:write:decline-by-link`,
35
+ };
36
+ export const SignatureQueries = {
37
+ list: `${SIGNATURE_FEATURE}:query:signature-request:list`,
38
+ detail: `${SIGNATURE_FEATURE}:query:signature-request:detail`,
39
+ signerList: `${SIGNATURE_FEATURE}:query:signature-signer:list`,
40
+ };
41
+ export const SignatureJobs = {
42
+ sweep: `${SIGNATURE_FEATURE}:job:sweep`,
43
+ };
44
+ export const SIGNATURE_EVENT_SHORT = {
45
+ completed: "completed",
46
+ declined: "declined",
47
+ expired: "expired",
48
+ };
49
+ export const SignatureEvents = {
50
+ completed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.completed}`,
51
+ declined: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.declined}`,
52
+ expired: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.expired}`,
53
+ };
54
+ // Every link rejection (forged, expired, revoked, used up, already signed) carries this reason, so
55
+ // a caller cannot tell the cases apart.
56
+ export const SIGNATURE_INVALID_LINK_REASON = "invalid_or_expired_link";
57
+ export const SIGNATURE_INVALID_IMAGE_REASON = "invalid_signature_image";
58
+ export const SIGNATURE_LINK_TTL_DAYS = 14;
59
+ export const SIGNATURE_MAX_LINK_OPENS = 20;
60
+ export const SIGNATURE_DEFAULT_VALIDITY_DAYS = 14;
61
+ export const SignatureInternalHandlers = {
62
+ linkOpen: `${SIGNATURE_FEATURE}:write:link-open`,
63
+ linkSign: `${SIGNATURE_FEATURE}:write:link-sign`,
64
+ linkDecline: `${SIGNATURE_FEATURE}:write:link-decline`,
65
+ finish: `${SIGNATURE_FEATURE}:write:finish`,
66
+ expire: `${SIGNATURE_FEATURE}:write:expire`,
67
+ reconcile: `${SIGNATURE_FEATURE}:write:reconcile`,
68
+ };
@@ -0,0 +1,3 @@
1
+ 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 "./constants.ts";
2
+ export type { SignaturePad as SignaturePadController, SignaturePadOptions } from "./pad.ts";
3
+ export { DEFAULT_SIGNATURE_PAD_LABELS, SignaturePad, type SignaturePadLabels, type SignaturePadProps, } from "./signature-pad.tsx";
@@ -0,0 +1,2 @@
1
+ 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 "./constants.js";
2
+ export { DEFAULT_SIGNATURE_PAD_LABELS, SignaturePad, } from "./signature-pad.js";
@@ -0,0 +1,20 @@
1
+ export type SignaturePadCanvas = Pick<HTMLCanvasElement, "width" | "height" | "addEventListener" | "removeEventListener" | "getBoundingClientRect" | "getContext" | "toBlob" | "setPointerCapture" | "releasePointerCapture"> & {
2
+ readonly style: Pick<CSSStyleDeclaration, "touchAction">;
3
+ };
4
+ export type SignaturePadOptions = {
5
+ /** Stroke width in canvas pixels. Default 3. */
6
+ readonly lineWidth?: number;
7
+ /** Stroke colour. Default near-black. */
8
+ readonly strokeStyle?: string;
9
+ /** Called whenever the field switches between empty and drawn. */
10
+ readonly onChange?: (isEmpty: boolean) => void;
11
+ };
12
+ export type SignaturePad = {
13
+ readonly clear: () => void;
14
+ readonly isEmpty: () => boolean;
15
+ /** PNG with transparent background as base64 without the data-URL prefix. */
16
+ readonly toPngBase64: () => Promise<string>;
17
+ readonly destroy: () => void;
18
+ };
19
+ export declare function bytesToBase64(bytes: Uint8Array): string;
20
+ export declare function createSignaturePad(canvas: SignaturePadCanvas, options?: SignaturePadOptions): SignaturePad;
@@ -0,0 +1,104 @@
1
+ // Framework-free signature field: Pointer Events (finger, pen, mouse) on a canvas. Imports nothing,
2
+ // so the static-sign entry stays free of React and of any runtime dependency.
3
+ const DEFAULT_LINE_WIDTH = 3;
4
+ const DEFAULT_STROKE_STYLE = "#111111";
5
+ const BASE64_CHUNK_SIZE = 0x8000;
6
+ export function bytesToBase64(bytes) {
7
+ let binary = "";
8
+ for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK_SIZE) {
9
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK_SIZE));
10
+ }
11
+ return btoa(binary);
12
+ }
13
+ // Closures of the pad need the non-null context; narrowing a const does not carry into them.
14
+ function requireContext(canvas) {
15
+ const context = canvas.getContext("2d");
16
+ if (context === null)
17
+ throw new Error("createSignaturePad: the canvas has no 2d context");
18
+ return context;
19
+ }
20
+ export function createSignaturePad(canvas, options = {}) {
21
+ const context = requireContext(canvas);
22
+ const lineWidth = options.lineWidth ?? DEFAULT_LINE_WIDTH;
23
+ context.lineWidth = lineWidth;
24
+ context.lineCap = "round";
25
+ context.lineJoin = "round";
26
+ context.strokeStyle = options.strokeStyle ?? DEFAULT_STROKE_STYLE;
27
+ context.fillStyle = options.strokeStyle ?? DEFAULT_STROKE_STYLE;
28
+ canvas.style.touchAction = "none";
29
+ let drawnAny = false;
30
+ let activePointerId = null;
31
+ let lastPoint = null;
32
+ function setDrawn(next) {
33
+ if (drawnAny === next)
34
+ return;
35
+ drawnAny = next;
36
+ options.onChange?.(!next);
37
+ }
38
+ // The canvas may be displayed at another size than its pixel size (CSS scaling).
39
+ function pointOf(event) {
40
+ const rect = canvas.getBoundingClientRect();
41
+ const scaleX = rect.width > 0 ? canvas.width / rect.width : 1;
42
+ const scaleY = rect.height > 0 ? canvas.height / rect.height : 1;
43
+ return { x: (event.clientX - rect.left) * scaleX, y: (event.clientY - rect.top) * scaleY };
44
+ }
45
+ function onPointerDown(event) {
46
+ if (activePointerId !== null)
47
+ return;
48
+ activePointerId = event.pointerId;
49
+ canvas.setPointerCapture(event.pointerId);
50
+ const point = pointOf(event);
51
+ lastPoint = point;
52
+ context.beginPath();
53
+ context.arc(point.x, point.y, lineWidth / 2, 0, Math.PI * 2);
54
+ context.fill();
55
+ setDrawn(true);
56
+ event.preventDefault();
57
+ }
58
+ function onPointerMove(event) {
59
+ if (event.pointerId !== activePointerId || lastPoint === null)
60
+ return;
61
+ const point = pointOf(event);
62
+ context.beginPath();
63
+ context.moveTo(lastPoint.x, lastPoint.y);
64
+ context.lineTo(point.x, point.y);
65
+ context.stroke();
66
+ lastPoint = point;
67
+ event.preventDefault();
68
+ }
69
+ function onPointerEnd(event) {
70
+ if (event.pointerId !== activePointerId)
71
+ return;
72
+ canvas.releasePointerCapture(event.pointerId);
73
+ activePointerId = null;
74
+ lastPoint = null;
75
+ }
76
+ canvas.addEventListener("pointerdown", onPointerDown);
77
+ canvas.addEventListener("pointermove", onPointerMove);
78
+ canvas.addEventListener("pointerup", onPointerEnd);
79
+ canvas.addEventListener("pointercancel", onPointerEnd);
80
+ return {
81
+ clear: () => {
82
+ context.clearRect(0, 0, canvas.width, canvas.height);
83
+ setDrawn(false);
84
+ },
85
+ isEmpty: () => !drawnAny,
86
+ toPngBase64: () => new Promise((resolve, reject) => {
87
+ canvas.toBlob((blob) => {
88
+ if (blob === null) {
89
+ reject(new Error("createSignaturePad: the canvas could not be exported as PNG"));
90
+ return;
91
+ }
92
+ blob
93
+ .arrayBuffer()
94
+ .then((buffer) => resolve(bytesToBase64(new Uint8Array(buffer))), reject);
95
+ }, "image/png");
96
+ }),
97
+ destroy: () => {
98
+ canvas.removeEventListener("pointerdown", onPointerDown);
99
+ canvas.removeEventListener("pointermove", onPointerMove);
100
+ canvas.removeEventListener("pointerup", onPointerEnd);
101
+ canvas.removeEventListener("pointercancel", onPointerEnd);
102
+ },
103
+ };
104
+ }
@@ -0,0 +1,19 @@
1
+ import { type SignaturePad as SignaturePadController } from "./pad.ts";
2
+ export type SignaturePadLabels = {
3
+ readonly fieldLabel: string;
4
+ readonly clear: string;
5
+ readonly signOnPaper: string;
6
+ };
7
+ export declare const DEFAULT_SIGNATURE_PAD_LABELS: SignaturePadLabels;
8
+ export type SignaturePadProps = {
9
+ /** Gets the controller once the canvas is mounted and null on unmount; read `toPngBase64()` from it on submit. Keep it referentially stable, a new function recreates the field. */
10
+ readonly onPadReady: (pad: SignaturePadController | null) => void;
11
+ /** Same stability requirement as `onPadReady`. */
12
+ readonly onChange?: (isEmpty: boolean) => void;
13
+ /** Shows the "sign on paper" exit; the signer who cannot draw must always have a way out. */
14
+ readonly onSignOnPaper?: () => void;
15
+ readonly labels?: Partial<SignaturePadLabels>;
16
+ readonly width?: number;
17
+ readonly height?: number;
18
+ };
19
+ export declare function SignaturePad(props: SignaturePadProps): import("react").JSX.Element;
@@ -0,0 +1,36 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { usePrimitives } from "@cosmicdrift/kumiko-renderer";
3
+ import { useCallback, useRef, useState } from "react";
4
+ import { createSignaturePad } from "./pad.js";
5
+ export const DEFAULT_SIGNATURE_PAD_LABELS = {
6
+ fieldLabel: "Signature field: draw your signature with finger, pen or mouse",
7
+ clear: "Clear",
8
+ signOnPaper: "Sign on paper instead",
9
+ };
10
+ const DEFAULT_WIDTH = 600;
11
+ const DEFAULT_HEIGHT = 240;
12
+ // Drawing needs a pointer; everything else (clear, the paper exit) is a plain focusable button.
13
+ // The pad lives in a callback ref instead of an effect: it follows the canvas element's mount and unmount.
14
+ export function SignaturePad(props) {
15
+ const { Button } = usePrimitives();
16
+ const labels = { ...DEFAULT_SIGNATURE_PAD_LABELS, ...props.labels };
17
+ const padRef = useRef(null);
18
+ const [isEmpty, setIsEmpty] = useState(true);
19
+ const { onPadReady, onChange } = props;
20
+ const mountPad = useCallback((canvas) => {
21
+ const pad = createSignaturePad(canvas, {
22
+ onChange: (empty) => {
23
+ setIsEmpty(empty);
24
+ onChange?.(empty);
25
+ },
26
+ });
27
+ padRef.current = pad;
28
+ onPadReady(pad);
29
+ return () => {
30
+ pad.destroy();
31
+ padRef.current = null;
32
+ onPadReady(null);
33
+ };
34
+ }, [onPadReady, onChange]);
35
+ return (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx("canvas", { ref: mountPad, width: props.width ?? DEFAULT_WIDTH, height: props.height ?? DEFAULT_HEIGHT, role: "img", "aria-label": labels.fieldLabel, className: "w-full rounded border border-input bg-white" }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { variant: "secondary", disabled: isEmpty, onClick: () => padRef.current?.clear(), children: labels.clear }), props.onSignOnPaper === undefined ? null : (_jsx(Button, { variant: "ghost", onClick: props.onSignOnPaper, children: labels.signOnPaper }))] })] }));
36
+ }
@@ -46,6 +46,12 @@ export type SubscriptionStripeOptions = {
46
46
  * mode:"subscription" — Stripe rejects invoice_creation there; the
47
47
  * subscription's own invoicing covers it. */
48
48
  readonly paymentInvoiceCreation?: boolean;
49
+ /** Shows Stripe's promotion-code field in every checkout of this app.
50
+ * Default false, because the field shows even when no code exists. Codes
51
+ * and coupons are created in the Stripe dashboard, not in the app. The
52
+ * consumer-protection confirmation mail shows the catalog price captured
53
+ * at consent, not the discounted amount. */
54
+ readonly allowPromotionCodes?: boolean;
49
55
  /** Allowlist of Stripe price-ids a mode:"payment" (one-off) checkout may
50
56
  * target — checkout-core's `openCheckout` rejects any other priceId as
51
57
  * `unknown_price`. App-specific and empty by default: without an
@@ -164,6 +164,9 @@ export function createSubscriptionStripeFeature(options = {}) {
164
164
  ...(options.paymentInvoiceCreation !== undefined && {
165
165
  paymentInvoiceCreation: options.paymentInvoiceCreation,
166
166
  }),
167
+ ...(options.allowPromotionCodes !== undefined && {
168
+ allowPromotionCodes: options.allowPromotionCodes,
169
+ }),
167
170
  }),
168
171
  createPortalSession: createStripePortalSession(runtimes.ctx),
169
172
  cancelSubscription: createStripeCancelSubscription(runtimes.ctx),
@@ -7,9 +7,11 @@ export type StripeCheckoutSessionRuntimeOptions = {
7
7
  /** Whether a mode:"payment" checkout gets a Stripe invoice. Default true.
8
8
  * Never applied in mode:"subscription" — Stripe rejects invoice_creation there. */
9
9
  readonly paymentInvoiceCreation?: boolean;
10
+ /** Shows Stripe's promotion-code field in checkout. Default false. */
11
+ readonly allowPromotionCodes?: boolean;
10
12
  };
11
13
  export declare function mapAppLocaleToStripeLocale(locale: string): Stripe.Checkout.SessionCreateParams.Locale;
12
- export declare function createStripeCheckoutSession(runtime: StripeCtxRuntime, { paymentInvoiceCreation }?: StripeCheckoutSessionRuntimeOptions): (ctx: HandlerContext, options: StripeCheckoutOptions) => Promise<{
14
+ export declare function createStripeCheckoutSession(runtime: StripeCtxRuntime, { paymentInvoiceCreation, allowPromotionCodes, }?: StripeCheckoutSessionRuntimeOptions): (ctx: HandlerContext, options: StripeCheckoutOptions) => Promise<{
13
15
  url: string;
14
16
  providerCheckoutId: string;
15
17
  }>;
@@ -77,7 +77,7 @@ export function mapAppLocaleToStripeLocale(locale) {
77
77
  function isUnknownCustomerStripeError(error) {
78
78
  return isResourceMissingStripeError(error) && error.param === "customer";
79
79
  }
80
- export function createStripeCheckoutSession(runtime, { paymentInvoiceCreation = true } = {}) {
80
+ export function createStripeCheckoutSession(runtime, { paymentInvoiceCreation = true, allowPromotionCodes = false, } = {}) {
81
81
  return async (ctx, options) => {
82
82
  // Invariant: without billing-live, no Stripe session may be created
83
83
  // (sk_test_-keys in production would otherwise create a test-mode checkout).
@@ -94,6 +94,7 @@ export function createStripeCheckoutSession(runtime, { paymentInvoiceCreation =
94
94
  success_url: options.successUrl,
95
95
  cancel_url: options.cancelUrl,
96
96
  submit_type: "pay",
97
+ ...(allowPromotionCodes && { allow_promotion_codes: true }),
97
98
  ...(options.locale && { locale: mapAppLocaleToStripeLocale(options.locale) }),
98
99
  ...(options.submitMessage && {
99
100
  custom_text: {