@cosmicdrift/kumiko-samples 0.414.0 → 0.416.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/packages/bundled-features/package.json +21 -1
- package/packages/bundled-features/src/agent-tools/changes.json +6 -0
- package/packages/bundled-features/src/agent-tools/tool-catalog.ts +20 -1
- package/packages/bundled-features/src/agent-tools/tool-dispatch.ts +19 -5
- package/packages/bundled-features/src/auth-email-password/signup-token-store.ts +2 -3
- package/packages/bundled-features/src/auth-email-password/web/session.tsx +2 -1
- package/packages/bundled-features/src/auth-mfa/changes.json +6 -0
- package/packages/bundled-features/src/billing-foundation/changes.json +24 -0
- package/packages/bundled-features/src/billing-foundation/checkout-core.ts +11 -0
- package/packages/bundled-features/src/billing-foundation/checkout-ledger.ts +8 -0
- package/packages/bundled-features/src/billing-foundation/events.ts +7 -5
- package/packages/bundled-features/src/billing-foundation/handlers/create-checkout-session.write.ts +2 -0
- package/packages/bundled-features/src/billing-foundation/handlers/process-event.write.ts +76 -24
- package/packages/bundled-features/src/billing-foundation/handlers/process-payment-event.write.ts +5 -4
- package/packages/bundled-features/src/billing-foundation/handlers/start-plan-checkout.write.ts +2 -0
- package/packages/bundled-features/src/billing-foundation/webhook-handler.ts +2 -2
- package/packages/bundled-features/src/channel-whatsapp/changes.json +30 -0
- package/packages/bundled-features/src/channel-whatsapp/constants.ts +1 -0
- package/packages/bundled-features/src/channel-whatsapp/events.ts +4 -3
- package/packages/bundled-features/src/channel-whatsapp/graph-client.ts +37 -1
- package/packages/bundled-features/src/channel-whatsapp/inbound-handlers.ts +23 -2
- package/packages/bundled-features/src/channel-whatsapp/webhook-normalize.ts +27 -6
- package/packages/bundled-features/src/compliance-profiles/changes.json +5 -0
- package/packages/bundled-features/src/compliance-profiles/handlers/set-profile.write.ts +2 -0
- package/packages/bundled-features/src/data-retention/feature.ts +1 -0
- package/packages/bundled-features/src/delivery/changes.json +6 -0
- package/packages/bundled-features/src/delivery/handlers/opted-in-user-ids.query.ts +12 -3
- package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
- package/packages/bundled-features/src/document-ingest-foundation/feature.ts +1 -0
- package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +3 -1
- package/packages/bundled-features/src/documents/changes.json +6 -0
- package/packages/bundled-features/src/documents/feature.ts +10 -5
- package/packages/bundled-features/src/form-draft/feature.ts +1 -0
- package/packages/bundled-features/src/handbook-knowledge/README.md +64 -0
- package/packages/bundled-features/src/handbook-knowledge/changes.json +8 -0
- package/packages/bundled-features/src/handbook-knowledge/constants.ts +8 -0
- package/packages/bundled-features/src/handbook-knowledge/feature.ts +34 -0
- package/packages/bundled-features/src/handbook-knowledge/handbook-index.ts +66 -0
- package/packages/bundled-features/src/handbook-knowledge/handlers.ts +77 -0
- package/packages/bundled-features/src/handbook-knowledge/index.ts +10 -0
- package/packages/bundled-features/src/helpdesk/changes.json +6 -0
- package/packages/bundled-features/src/helpdesk/feature.ts +1 -0
- package/packages/bundled-features/src/helpdesk/handlers/reply.write.ts +3 -3
- package/packages/bundled-features/src/helpdesk/handlers/report.write.ts +3 -2
- package/packages/bundled-features/src/helpdesk/handlers/submit.write.ts +3 -2
- package/packages/bundled-features/src/helpdesk/legacy-contact-streams.ts +3 -1
- package/packages/bundled-features/src/helpdesk/lib.ts +9 -4
- package/packages/bundled-features/src/inbound-mail-foundation/account-poll.ts +4 -1
- package/packages/bundled-features/src/inbound-mail-foundation/changes.json +6 -0
- package/packages/bundled-features/src/inbound-mail-foundation/content-refetch.ts +11 -4
- package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +18 -9
- package/packages/bundled-features/src/inbound-mail-foundation/events.ts +18 -9
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/connect-account.write.ts +2 -1
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/forget-message.write.ts +6 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/ingest-message-schema.ts +18 -5
- package/packages/bundled-features/src/inbound-mail-foundation/normalize-inbound-message.ts +22 -8
- package/packages/bundled-features/src/inbound-mail-foundation/sanitize-inbound-html.ts +2 -5
- package/packages/bundled-features/src/managed-pages/web/page-edit-screen.tsx +11 -5
- package/packages/bundled-features/src/shared/changes.json +6 -0
- package/packages/bundled-features/src/shared/hmac-signature.ts +4 -2
- package/packages/bundled-features/src/shared/index.ts +2 -1
- package/packages/bundled-features/src/shared/normalize-email.ts +3 -0
- package/packages/bundled-features/src/shared/send-best-effort.ts +16 -6
- package/packages/bundled-features/src/signature/README.md +59 -0
- package/packages/bundled-features/src/signature/changes.json +15 -0
- package/packages/bundled-features/src/signature/entity.ts +192 -0
- package/packages/bundled-features/src/signature/feature.ts +125 -0
- package/packages/bundled-features/src/signature/files.ts +107 -0
- package/packages/bundled-features/src/signature/grant.ts +79 -0
- package/packages/bundled-features/src/signature/handlers/anonymous.write.ts +88 -0
- package/packages/bundled-features/src/signature/handlers/cancel.write.ts +40 -0
- package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +72 -0
- package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +99 -0
- package/packages/bundled-features/src/signature/handlers/link-internal.write.ts +261 -0
- package/packages/bundled-features/src/signature/handlers/request.write.ts +86 -0
- package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +23 -0
- package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +69 -0
- package/packages/bundled-features/src/signature/i18n.ts +52 -0
- package/packages/bundled-features/src/signature/index.ts +33 -0
- package/packages/bundled-features/src/signature/lib.ts +125 -0
- package/packages/bundled-features/src/signature/options.ts +49 -0
- package/packages/bundled-features/src/signature/payloads.ts +71 -0
- package/packages/bundled-features/src/signature/png.ts +169 -0
- package/packages/bundled-features/src/signature/screens.ts +115 -0
- package/packages/bundled-features/src/signature/signature-page.ts +93 -0
- package/packages/bundled-features/src/signature/signing.ts +77 -0
- package/packages/bundled-features/src/signature/static-sign.ts +98 -0
- package/packages/bundled-features/src/signature/sweep.ts +161 -0
- package/packages/bundled-features/src/signature/user-data.ts +159 -0
- package/packages/bundled-features/src/signature/web/constants.ts +92 -0
- package/packages/bundled-features/src/signature/web/index.ts +31 -0
- package/packages/bundled-features/src/signature/web/pad.ts +147 -0
- package/packages/bundled-features/src/signature/web/signature-pad.tsx +82 -0
- package/packages/bundled-features/src/step-dispatcher/changes.json +6 -0
- package/packages/bundled-features/src/step-dispatcher/deliver-dispatch-request.ts +5 -2
- package/packages/bundled-features/src/step-dispatcher/feature.ts +14 -0
- package/packages/bundled-features/src/step-dispatcher/sweep-abandoned.ts +4 -0
- package/packages/bundled-features/src/subscription-paddle/backfill-checkout-ledger.ts +2 -0
- package/packages/bundled-features/src/subscription-paddle/changes.json +6 -0
- package/packages/bundled-features/src/subscription-paddle/redeliver-legacy-checkout.ts +23 -2
- package/packages/bundled-features/src/subscription-stripe/changes.json +12 -0
- package/packages/bundled-features/src/subscription-stripe/feature.ts +9 -0
- package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +7 -1
- package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +19 -5
- package/packages/bundled-features/src/template-resolver/changes.json +12 -0
- package/packages/bundled-features/src/template-resolver/seeding.ts +37 -7
- package/packages/bundled-features/src/template-resolver/web/web-preview-renderer.tsx +7 -1
- package/packages/bundled-features/src/tenant-inactivity/changes.json +6 -0
- package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +34 -16
- package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +6 -0
- package/packages/bundled-features/src/tenant-inactivity/state-store.ts +12 -1
- package/packages/bundled-features/src/tenant-lifecycle/changes.json +6 -0
- package/packages/bundled-features/src/tenant-lifecycle/feature.ts +1 -0
- package/packages/bundled-features/src/user/resolve-verified-user-email.ts +3 -3
- package/packages/bundled-features/src/user-data-rights/feature.ts +1 -0
- package/packages/bundled-features/src/waitlist/handlers/reject.write.ts +1 -1
- package/packages/bundled-features/src/waitlist/handlers/submit.write.ts +2 -2
- package/packages/bundled-features/src/waitlist/import.ts +2 -1
- package/packages/bundled-features/src/waitlist/lib.ts +1 -5
- package/packages/bundled-features/src/waitlist/link-on-signup.ts +2 -2
- package/packages/bundled-features/src/workflow-runner/changes.json +6 -0
- package/packages/bundled-features/src/workflow-runner/handlers/resume-run.write.ts +4 -2
- package/samples/apps/admin-console/src/app/shell.tsx +1 -0
- package/samples/apps/use-all-bundled/feature-manifest.json +63 -1
- package/samples/apps/use-all-bundled/kumiko/migrations/0068_signature.rebuild.json +4 -0
- package/samples/apps/use-all-bundled/src/run-config.ts +35 -1
- package/samples/recipes/crypto-shredding-hr/README.md +11 -0
- package/samples/recipes/crypto-shredding-hr/src/feature.ts +27 -0
- package/samples/recipes/embedded/README.md +4 -0
- package/samples/recipes/embedded/src/entities/invoice.ts +6 -0
- package/samples/recipes/embedded/src/feature.ts +7 -1
- package/samples/recipes/embedded/src/handlers/invoice-receive.write.ts +1 -0
- package/samples/recipes/embedded/src/screens/invoice-receive.screen.ts +2 -0
- package/samples/recipes/handbook-knowledge/README.md +22 -0
- package/samples/recipes/handbook-knowledge/package.json +12 -0
- package/samples/recipes/handbook-knowledge/src/feature.ts +42 -0
- package/samples/recipes/record-detail-layout/src/feature.ts +36 -5
- package/samples/recipes/record-detail-layout/src/order-board.ts +10 -2
- package/samples/recipes/signature/README.md +21 -0
- package/samples/recipes/signature/package.json +13 -0
- package/samples/recipes/signature/src/feature.ts +26 -0
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
|
|
3
|
+
import { PDFDocument } from "pdf-lib";
|
|
4
|
+
import { requestExecutor, signerExecutor } from "../entity.ts";
|
|
5
|
+
import { readTenantFile, sha256Hex } from "../files.ts";
|
|
6
|
+
import { RequestSignatureSchema } from "../payloads.ts";
|
|
7
|
+
import {
|
|
8
|
+
SIGNATURE_DEFAULT_VALIDITY_DAYS,
|
|
9
|
+
SIGNATURE_REQUEST_STATUS,
|
|
10
|
+
SIGNATURE_SIGNER_STATUS,
|
|
11
|
+
} from "../web/constants.ts";
|
|
12
|
+
|
|
13
|
+
export type RequestSignatureData = {
|
|
14
|
+
readonly requestId: string;
|
|
15
|
+
readonly signerIds: readonly string[];
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
|
19
|
+
|
|
20
|
+
// Encrypted or unparseable PDFs would fail later when the signature page is appended and leave the
|
|
21
|
+
// request stuck in all-signed.
|
|
22
|
+
async function isLoadablePdf(bytes: Uint8Array): Promise<boolean> {
|
|
23
|
+
try {
|
|
24
|
+
await PDFDocument.load(bytes);
|
|
25
|
+
return true;
|
|
26
|
+
} catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createRequestHandler(access: AccessRule) {
|
|
32
|
+
return defineWriteHandler<"request", typeof RequestSignatureSchema, RequestSignatureData>({
|
|
33
|
+
name: "request",
|
|
34
|
+
schema: RequestSignatureSchema,
|
|
35
|
+
access,
|
|
36
|
+
agent: { risk: "mid" },
|
|
37
|
+
description:
|
|
38
|
+
"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.",
|
|
39
|
+
handler: async (event, ctx) => {
|
|
40
|
+
const payload = event.payload;
|
|
41
|
+
const user = event.user;
|
|
42
|
+
const document = await readTenantFile(ctx, user.tenantId, payload.documentFileId);
|
|
43
|
+
if (document === null || !(await isLoadablePdf(document.content))) {
|
|
44
|
+
return writeFailure(new UnprocessableError("document_not_a_pdf"));
|
|
45
|
+
}
|
|
46
|
+
const validityDays = payload.expiresInDays ?? SIGNATURE_DEFAULT_VALIDITY_DAYS;
|
|
47
|
+
const now = ctx.tz.now();
|
|
48
|
+
const created = await requestExecutor.create(
|
|
49
|
+
{
|
|
50
|
+
documentFileId: payload.documentFileId,
|
|
51
|
+
documentSha256: sha256Hex(document.content),
|
|
52
|
+
title: payload.title,
|
|
53
|
+
level: payload.level,
|
|
54
|
+
subjectType: payload.subjectType,
|
|
55
|
+
subjectId: payload.subjectId,
|
|
56
|
+
status: SIGNATURE_REQUEST_STATUS.Open,
|
|
57
|
+
expiresAt: now.add({ milliseconds: validityDays * MS_PER_DAY }),
|
|
58
|
+
},
|
|
59
|
+
user,
|
|
60
|
+
ctx.db,
|
|
61
|
+
);
|
|
62
|
+
if (!created.isSuccess) return created;
|
|
63
|
+
const requestId = String(created.data.id);
|
|
64
|
+
|
|
65
|
+
const signerIds: string[] = [];
|
|
66
|
+
for (const signer of payload.signers) {
|
|
67
|
+
const createdSigner = await signerExecutor.create(
|
|
68
|
+
{
|
|
69
|
+
requestId,
|
|
70
|
+
name: signer.name,
|
|
71
|
+
status: SIGNATURE_SIGNER_STATUS.Pending,
|
|
72
|
+
viewCount: 0,
|
|
73
|
+
...(signer.role !== undefined && { role: signer.role }),
|
|
74
|
+
...(signer.contactId !== undefined && { contactId: signer.contactId }),
|
|
75
|
+
...(signer.email !== undefined && { email: signer.email.toLowerCase() }),
|
|
76
|
+
},
|
|
77
|
+
user,
|
|
78
|
+
ctx.db,
|
|
79
|
+
);
|
|
80
|
+
if (!createdSigner.isSuccess) return createdSigner;
|
|
81
|
+
signerIds.push(String(createdSigner.data.id));
|
|
82
|
+
}
|
|
83
|
+
return { isSuccess: true, data: { requestId, signerIds } };
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import { signerExecutor } from "../entity.ts";
|
|
3
|
+
import { SignerIdSchema } from "../payloads.ts";
|
|
4
|
+
|
|
5
|
+
export function createRevokeLinkHandler(access: AccessRule) {
|
|
6
|
+
return defineWriteHandler<"revoke-link", typeof SignerIdSchema, { readonly revoked: true }>({
|
|
7
|
+
name: "revoke-link",
|
|
8
|
+
schema: SignerIdSchema,
|
|
9
|
+
access,
|
|
10
|
+
agent: { expose: false },
|
|
11
|
+
description: "Revokes the signing link of one signer; the token stops working at once.",
|
|
12
|
+
handler: async (event, ctx) => {
|
|
13
|
+
const updated = await signerExecutor.update(
|
|
14
|
+
{ id: event.payload.signerId, changes: { linkAnchor: null } },
|
|
15
|
+
event.user,
|
|
16
|
+
ctx.db,
|
|
17
|
+
{ skipOptimisticLock: true },
|
|
18
|
+
);
|
|
19
|
+
if (!updated.isSuccess) return updated;
|
|
20
|
+
return { isSuccess: true, data: { revoked: true } };
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
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 { SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS } from "../web/constants.ts";
|
|
23
|
+
|
|
24
|
+
export type SignInPersonData = { readonly requestStatus: string };
|
|
25
|
+
|
|
26
|
+
export function createSignInPersonHandler(access: AccessRule) {
|
|
27
|
+
return defineWriteHandler<"sign-in-person", typeof SignInPersonSchema, SignInPersonData>({
|
|
28
|
+
name: "sign-in-person",
|
|
29
|
+
schema: SignInPersonSchema,
|
|
30
|
+
access,
|
|
31
|
+
agent: { expose: false },
|
|
32
|
+
description:
|
|
33
|
+
"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.",
|
|
34
|
+
handler: async (event, ctx) => {
|
|
35
|
+
const user = event.user;
|
|
36
|
+
const signer = await signerExecutor.detail({ id: event.payload.signerId }, user, ctx.db);
|
|
37
|
+
if (signer === null) return writeFailure(new NotFoundError("signer", event.payload.signerId));
|
|
38
|
+
const request = await loadRequestOfSigner(ctx, user, signer);
|
|
39
|
+
const now = ctx.tz.now();
|
|
40
|
+
if (request === null || !isOpenRequest(request, now) || !isUnsignedSigner(signer)) {
|
|
41
|
+
return writeFailure(new UnprocessableError("signature_not_possible"));
|
|
42
|
+
}
|
|
43
|
+
const png = decodeSignatureImage(event.payload.imagePngBase64);
|
|
44
|
+
if (png === null) return invalidImage();
|
|
45
|
+
|
|
46
|
+
const image = await storeSignatureImage(ctx, user, png);
|
|
47
|
+
if (!image.isSuccess) return image;
|
|
48
|
+
const recorded = await recordInPersonSignature(ctx, user, signer, {
|
|
49
|
+
method: SIGNATURE_METHOD.InPerson,
|
|
50
|
+
imageFileId: image.data.id,
|
|
51
|
+
signedAt: now,
|
|
52
|
+
});
|
|
53
|
+
if (!recorded.isSuccess) {
|
|
54
|
+
await discardGeneratedFile(ctx, user, image.data);
|
|
55
|
+
return recorded;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const allSigned = await advanceIfAllSigned(ctx, user, request.id);
|
|
59
|
+
return {
|
|
60
|
+
isSuccess: true,
|
|
61
|
+
data: {
|
|
62
|
+
requestStatus: allSigned
|
|
63
|
+
? SIGNATURE_REQUEST_STATUS.AllSigned
|
|
64
|
+
: SIGNATURE_REQUEST_STATUS.Open,
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
type LocalizedString = { readonly en: string; readonly de: string };
|
|
2
|
+
|
|
3
|
+
const REQUEST = "signature:entity:signatureRequest:field";
|
|
4
|
+
const SIGNER = "signature:entity:signatureSigner:field";
|
|
5
|
+
|
|
6
|
+
export const SIGNATURE_I18N: Readonly<Record<string, LocalizedString>> = {
|
|
7
|
+
"signature:feature.label": { en: "Signatures", de: "Unterschriften" },
|
|
8
|
+
"screen:signature-list.title": { en: "Signatures", de: "Unterschriften" },
|
|
9
|
+
"signature.nav.signature": { en: "Signatures", de: "Unterschriften" },
|
|
10
|
+
"signature.action.open": { en: "Open", de: "Öffnen" },
|
|
11
|
+
"signature.signers.title": { en: "Signers", de: "Unterzeichner" },
|
|
12
|
+
"signature.action.issueLink": { en: "Send link", de: "Link senden" },
|
|
13
|
+
"signature.action.revokeLink": { en: "Revoke link", de: "Link widerrufen" },
|
|
14
|
+
"signature.action.revokeLink.confirm": {
|
|
15
|
+
en: "Revoke the link of this signer?",
|
|
16
|
+
de: "Den Link dieses Unterzeichners widerrufen?",
|
|
17
|
+
},
|
|
18
|
+
"screen:signature-detail.title": { en: "Signature request", de: "Unterschriftsanfrage" },
|
|
19
|
+
"signature.action.cancel": { en: "Cancel request", de: "Anfrage abbrechen" },
|
|
20
|
+
"signature.action.cancel.confirm": {
|
|
21
|
+
en: "Cancel this request? All signing links stop working.",
|
|
22
|
+
de: "Diese Anfrage abbrechen? Alle Unterschrifts-Links werden ungültig.",
|
|
23
|
+
},
|
|
24
|
+
[`${SIGNER}:name`]: { en: "Name", de: "Name" },
|
|
25
|
+
[`${SIGNER}:role`]: { en: "Role", de: "Rolle" },
|
|
26
|
+
[`${SIGNER}:status`]: { en: "Status", de: "Status" },
|
|
27
|
+
[`${SIGNER}:method`]: { en: "Way of signing", de: "Art der Unterschrift" },
|
|
28
|
+
[`${SIGNER}:signedAt`]: { en: "Signed", de: "Unterschrieben" },
|
|
29
|
+
[`${SIGNER}:status:option:pending`]: { en: "Pending", de: "Ausstehend" },
|
|
30
|
+
[`${SIGNER}:status:option:viewed`]: { en: "Viewed", de: "Geöffnet" },
|
|
31
|
+
[`${SIGNER}:status:option:signed`]: { en: "Signed", de: "Unterschrieben" },
|
|
32
|
+
[`${SIGNER}:status:option:declined`]: { en: "Declined", de: "Abgelehnt" },
|
|
33
|
+
[`${SIGNER}:method:option:in-person`]: { en: "In person", de: "Vor Ort" },
|
|
34
|
+
[`${SIGNER}:method:option:link`]: { en: "Link", de: "Link" },
|
|
35
|
+
[`${REQUEST}:title`]: { en: "Document", de: "Dokument" },
|
|
36
|
+
[`${REQUEST}:status`]: { en: "Status", de: "Status" },
|
|
37
|
+
[`${REQUEST}:subjectType`]: { en: "Related to", de: "Gehört zu" },
|
|
38
|
+
[`${REQUEST}:expiresAt`]: { en: "Valid until", de: "Gültig bis" },
|
|
39
|
+
[`${REQUEST}:completedAt`]: { en: "Completed", de: "Abgeschlossen" },
|
|
40
|
+
[`${REQUEST}:documentFileId`]: { en: "Document file", de: "Dokumentdatei" },
|
|
41
|
+
[`${REQUEST}:documentSha256`]: { en: "Document hash", de: "Dokument-Hash" },
|
|
42
|
+
[`${REQUEST}:level`]: { en: "Level", de: "Stufe" },
|
|
43
|
+
[`${REQUEST}:subjectId`]: { en: "Related id", de: "Zugehörige ID" },
|
|
44
|
+
[`${REQUEST}:completedFileId`]: { en: "Signed file", de: "Signierte Datei" },
|
|
45
|
+
[`${REQUEST}:level:option:simple`]: { en: "Simple", de: "Einfach" },
|
|
46
|
+
[`${REQUEST}:status:option:open`]: { en: "Open", de: "Offen" },
|
|
47
|
+
[`${REQUEST}:status:option:all-signed`]: { en: "All signed", de: "Alle unterschrieben" },
|
|
48
|
+
[`${REQUEST}:status:option:completed`]: { en: "Completed", de: "Abgeschlossen" },
|
|
49
|
+
[`${REQUEST}:status:option:declined`]: { en: "Declined", de: "Abgelehnt" },
|
|
50
|
+
[`${REQUEST}:status:option:expired`]: { en: "Expired", de: "Abgelaufen" },
|
|
51
|
+
[`${REQUEST}:status:option:cancelled`]: { en: "Cancelled", de: "Abgebrochen" },
|
|
52
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export type { SignatureRetention } from "./entity.ts";
|
|
2
|
+
export { createSignatureFeature } from "./feature.ts";
|
|
3
|
+
export type {
|
|
4
|
+
DeliverSignatureLink,
|
|
5
|
+
RenderSignatureHtmlToPdf,
|
|
6
|
+
SignatureLinkDelivery,
|
|
7
|
+
SignatureOptions,
|
|
8
|
+
} from "./options.ts";
|
|
9
|
+
export type { SignaturePageLabels } from "./signature-page.ts";
|
|
10
|
+
export {
|
|
11
|
+
SIGNATURE_DEFAULT_VALIDITY_DAYS,
|
|
12
|
+
SIGNATURE_EVENT_SHORT,
|
|
13
|
+
SIGNATURE_FEATURE,
|
|
14
|
+
SIGNATURE_INVALID_IMAGE_REASON,
|
|
15
|
+
SIGNATURE_INVALID_LINK_REASON,
|
|
16
|
+
SIGNATURE_LEVEL,
|
|
17
|
+
SIGNATURE_LINK_TTL_DAYS,
|
|
18
|
+
SIGNATURE_MAX_LINK_OPENS,
|
|
19
|
+
SIGNATURE_METHOD,
|
|
20
|
+
SIGNATURE_REQUEST_ENTITY,
|
|
21
|
+
SIGNATURE_REQUEST_STATUS,
|
|
22
|
+
SIGNATURE_SIGNER_ENTITY,
|
|
23
|
+
SIGNATURE_SIGNER_STATUS,
|
|
24
|
+
SignatureEvents,
|
|
25
|
+
SignatureHandlers,
|
|
26
|
+
SignatureInternalHandlers,
|
|
27
|
+
SignatureJobs,
|
|
28
|
+
type SignatureLevel,
|
|
29
|
+
type SignatureMethod,
|
|
30
|
+
SignatureQueries,
|
|
31
|
+
type SignatureRequestStatus,
|
|
32
|
+
type SignatureSignerStatus,
|
|
33
|
+
} from "./web/constants.ts";
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type { TenantDb } from "@cosmicdrift/kumiko-framework/db";
|
|
2
|
+
import {
|
|
3
|
+
type AccessRule,
|
|
4
|
+
access,
|
|
5
|
+
type HandlerContext,
|
|
6
|
+
type SessionUser,
|
|
7
|
+
} from "@cosmicdrift/kumiko-framework/engine";
|
|
8
|
+
import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
|
|
9
|
+
import { generateId } from "@cosmicdrift/kumiko-framework/utils";
|
|
10
|
+
import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
|
|
11
|
+
import { requestExecutor, signerExecutor } from "./entity.ts";
|
|
12
|
+
import {
|
|
13
|
+
SIGNATURE_INVALID_LINK_REASON,
|
|
14
|
+
SIGNATURE_REQUEST_STATUS,
|
|
15
|
+
SIGNATURE_SIGNER_STATUS,
|
|
16
|
+
type SignatureRequestStatus,
|
|
17
|
+
} from "./web/constants.ts";
|
|
18
|
+
|
|
19
|
+
export const DEFAULT_SIGNATURE_ACCESS: AccessRule = { roles: ["TenantAdmin", "TenantMember"] };
|
|
20
|
+
|
|
21
|
+
export const internalAccess = { roles: access.system } as const;
|
|
22
|
+
|
|
23
|
+
export const SIGNATURE_OUTCOME_AGGREGATE_TYPE = "signature-outcome" as const;
|
|
24
|
+
|
|
25
|
+
export type RequestRow = NonNullable<Awaited<ReturnType<typeof requestExecutor.detail>>>;
|
|
26
|
+
export type SignerRow = NonNullable<Awaited<ReturnType<typeof signerExecutor.detail>>>;
|
|
27
|
+
|
|
28
|
+
// Same body and status for every link rejection: forged, expired, revoked, used up, signed already.
|
|
29
|
+
export function invalidLink() {
|
|
30
|
+
return writeFailure(new UnprocessableError(SIGNATURE_INVALID_LINK_REASON));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function instantOrNull(value: unknown): Temporal.Instant | null {
|
|
34
|
+
return value instanceof Temporal.Instant ? value : null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function isPastInstant(value: unknown, now: Temporal.Instant): boolean {
|
|
38
|
+
const instant = instantOrNull(value);
|
|
39
|
+
return instant !== null && Temporal.Instant.compare(instant, now) <= 0;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function isOpenRequest(request: RequestRow, now: Temporal.Instant): boolean {
|
|
43
|
+
return request.status === SIGNATURE_REQUEST_STATUS.Open && !isPastInstant(request.expiresAt, now);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function isUnsignedSigner(signer: SignerRow): boolean {
|
|
47
|
+
return (
|
|
48
|
+
signer.status === SIGNATURE_SIGNER_STATUS.Pending ||
|
|
49
|
+
signer.status === SIGNATURE_SIGNER_STATUS.Viewed
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Equals the executor's MAX_LIST_LIMIT.
|
|
54
|
+
const LIST_PAGE_SIZE = 200;
|
|
55
|
+
|
|
56
|
+
export async function listSigners(
|
|
57
|
+
ctx: { readonly db: TenantDb },
|
|
58
|
+
user: SessionUser,
|
|
59
|
+
requestId: string,
|
|
60
|
+
): Promise<readonly SignerRow[]> {
|
|
61
|
+
const found = await signerExecutor.list(
|
|
62
|
+
{ filter: { field: "requestId", op: "eq", value: requestId }, limit: LIST_PAGE_SIZE },
|
|
63
|
+
user,
|
|
64
|
+
ctx.db,
|
|
65
|
+
);
|
|
66
|
+
return found.rows;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function versionOf(row: { readonly version?: unknown }): number | undefined {
|
|
70
|
+
return typeof row.version === "number" ? row.version : undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function setRequestStatus(
|
|
74
|
+
ctx: { readonly db: TenantDb },
|
|
75
|
+
user: SessionUser,
|
|
76
|
+
requestId: string,
|
|
77
|
+
from: SignatureRequestStatus,
|
|
78
|
+
changes: Readonly<Record<string, unknown>>,
|
|
79
|
+
) {
|
|
80
|
+
return requestExecutor.update({ id: requestId, changes }, user, ctx.db, {
|
|
81
|
+
skipOptimisticLock: true,
|
|
82
|
+
expect: { status: from },
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Moves an open request to all-signed once every signer has signed. Two signers committing at the
|
|
87
|
+
// same moment can both still see the other as unsigned; the sweep job repeats this check.
|
|
88
|
+
export async function advanceIfAllSigned(
|
|
89
|
+
ctx: { readonly db: TenantDb },
|
|
90
|
+
user: SessionUser,
|
|
91
|
+
requestId: string,
|
|
92
|
+
): Promise<boolean> {
|
|
93
|
+
const signers = await listSigners(ctx, user, requestId);
|
|
94
|
+
const allSigned =
|
|
95
|
+
signers.length > 0 &&
|
|
96
|
+
signers.every((signer) => signer.status === SIGNATURE_SIGNER_STATUS.Signed);
|
|
97
|
+
if (!allSigned) return false;
|
|
98
|
+
const moved = await setRequestStatus(ctx, user, requestId, SIGNATURE_REQUEST_STATUS.Open, {
|
|
99
|
+
status: SIGNATURE_REQUEST_STATUS.AllSigned,
|
|
100
|
+
});
|
|
101
|
+
return moved.isSuccess;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function loadRequestOfSigner(
|
|
105
|
+
ctx: { readonly db: TenantDb },
|
|
106
|
+
user: SessionUser,
|
|
107
|
+
signer: SignerRow,
|
|
108
|
+
) {
|
|
109
|
+
return requestExecutor.detail({ id: signer.requestId }, user, ctx.db);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Each outcome is its own aggregate with a fresh id: it needs no predecessor version and cannot
|
|
113
|
+
// conflict with a concurrent write on the request it describes.
|
|
114
|
+
export function appendOutcomeEvent(
|
|
115
|
+
ctx: Pick<HandlerContext, "events">,
|
|
116
|
+
type: string,
|
|
117
|
+
payload: Readonly<Record<string, unknown>>,
|
|
118
|
+
) {
|
|
119
|
+
return ctx.events.unsafeAppend({
|
|
120
|
+
aggregateId: generateId(),
|
|
121
|
+
aggregateType: SIGNATURE_OUTCOME_AGGREGATE_TYPE,
|
|
122
|
+
type,
|
|
123
|
+
payload,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { AccessRule, HandlerContext, SessionUser } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import type { RateLimitDeclaration } from "@cosmicdrift/kumiko-types/handlers";
|
|
3
|
+
import type { PdfOptions } from "../renderer-foundation/index.ts";
|
|
4
|
+
import type { SignatureRetention } from "./entity.ts";
|
|
5
|
+
|
|
6
|
+
// Injected by the app (renderer-puppeteer-client's `renderHtmlToPdf`): bundled-features cannot
|
|
7
|
+
// import that package, which itself depends on bundled-features.
|
|
8
|
+
export type RenderSignatureHtmlToPdf = (html: string, options?: PdfOptions) => Promise<Uint8Array>;
|
|
9
|
+
|
|
10
|
+
export type SignatureLinkDelivery = {
|
|
11
|
+
readonly signerId: string;
|
|
12
|
+
readonly requestId: string;
|
|
13
|
+
readonly name: string;
|
|
14
|
+
readonly email: string;
|
|
15
|
+
/** Signing link with the token in the fragment. */
|
|
16
|
+
readonly url: string;
|
|
17
|
+
/** Who issued the link, e.g. to pick the mailbox it is sent from. */
|
|
18
|
+
readonly issuedBy: SessionUser;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// The token never leaves the server in a handler result: whoever calls issue-link would otherwise
|
|
22
|
+
// sign in the signer's place. The app sends the link to the signer's own address.
|
|
23
|
+
// Runs inside issue-link's transaction with its full context, so the app can dispatch its own mail write.
|
|
24
|
+
// The url must not land in an event, thread or record that other users or the assistant read.
|
|
25
|
+
export type DeliverSignatureLink = (
|
|
26
|
+
ctx: HandlerContext,
|
|
27
|
+
delivery: SignatureLinkDelivery,
|
|
28
|
+
) => Promise<void>;
|
|
29
|
+
|
|
30
|
+
export type SignatureOptions = {
|
|
31
|
+
/** How long requests and signers are kept, data-retention keepFor syntax, counted from creation. */
|
|
32
|
+
readonly retention: SignatureRetention;
|
|
33
|
+
/** Renders the signature page (HTML) to a PDF. An outage leaves the request at `all-signed` and the sweep job retries. */
|
|
34
|
+
readonly renderHtmlToPdf: RenderSignatureHtmlToPdf;
|
|
35
|
+
/** HMAC secret of the signing links. Without it every link is rejected. */
|
|
36
|
+
readonly linkSecret: string;
|
|
37
|
+
/** Sends a freshly issued link to the signer, e.g. by mail. A throw fails issue-link and leaves no link sent. */
|
|
38
|
+
readonly deliverLink: DeliverSignatureLink;
|
|
39
|
+
/** URL of the app's signature page; the token is appended as `#<token>`. */
|
|
40
|
+
readonly signaturePageUrl: string;
|
|
41
|
+
/** Access rule of the signed-in handlers, queries, screens and nav. Default `{ roles: ["TenantAdmin", "TenantMember"] }`; set it when the app hands out other roles. The link handlers stay anonymous. */
|
|
42
|
+
readonly access?: AccessRule;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export const LINK_RATE_LIMIT: RateLimitDeclaration = {
|
|
46
|
+
per: "ip+handler",
|
|
47
|
+
limit: 30,
|
|
48
|
+
windowSeconds: 60,
|
|
49
|
+
};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { MAX_SIGNATURE_PNG_BYTES } from "./png.ts";
|
|
3
|
+
import { SIGNATURE_LEVEL } from "./web/constants.ts";
|
|
4
|
+
|
|
5
|
+
export const MAX_SIGNERS_PER_REQUEST = 20;
|
|
6
|
+
const MAX_VALIDITY_DAYS = 365;
|
|
7
|
+
// Base64 inflates by 4/3; the png checks apply to the decoded bytes.
|
|
8
|
+
const MAX_IMAGE_BASE64_LENGTH = Math.ceil((MAX_SIGNATURE_PNG_BYTES * 4) / 3) + 4;
|
|
9
|
+
const MAX_TOKEN_LENGTH = 2000;
|
|
10
|
+
|
|
11
|
+
const SignerInputSchema = z.object({
|
|
12
|
+
name: z.string().trim().min(1).max(200),
|
|
13
|
+
role: z.string().trim().min(1).max(100).optional(),
|
|
14
|
+
contactId: z.string().min(1).max(64).optional(),
|
|
15
|
+
email: z.string().trim().min(3).max(320).optional(),
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
export const RequestSignatureSchema = z.object({
|
|
19
|
+
documentFileId: z.uuid(),
|
|
20
|
+
title: z.string().trim().min(1).max(200),
|
|
21
|
+
level: z.literal(SIGNATURE_LEVEL.Simple).default(SIGNATURE_LEVEL.Simple),
|
|
22
|
+
subjectType: z.string().trim().min(1).max(100),
|
|
23
|
+
subjectId: z.string().trim().min(1).max(100),
|
|
24
|
+
expiresInDays: z.number().int().min(1).max(MAX_VALIDITY_DAYS).optional(),
|
|
25
|
+
signers: z.array(SignerInputSchema).min(1).max(MAX_SIGNERS_PER_REQUEST),
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
export type RequestSignatureInput = z.infer<typeof RequestSignatureSchema>;
|
|
29
|
+
|
|
30
|
+
const ImagePayload = z.string().min(1).max(MAX_IMAGE_BASE64_LENGTH);
|
|
31
|
+
|
|
32
|
+
export const SignInPersonSchema = z.object({
|
|
33
|
+
signerId: z.uuid(),
|
|
34
|
+
imagePngBase64: ImagePayload,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
export const SignerIdSchema = z.object({ signerId: z.uuid() });
|
|
38
|
+
|
|
39
|
+
export const RequestIdSchema = z.object({ requestId: z.uuid() });
|
|
40
|
+
|
|
41
|
+
const TokenPayload = z.string().min(1).max(MAX_TOKEN_LENGTH);
|
|
42
|
+
|
|
43
|
+
export const OpenByLinkSchema = z.object({ token: TokenPayload });
|
|
44
|
+
|
|
45
|
+
export const SignByLinkSchema = z.object({ token: TokenPayload, imagePngBase64: ImagePayload });
|
|
46
|
+
|
|
47
|
+
export const DeclineByLinkSchema = z.object({
|
|
48
|
+
token: TokenPayload,
|
|
49
|
+
reason: z.string().trim().min(1).max(1000).optional(),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
export const FinishSchema = z.object({ requestId: z.uuid(), completedFileId: z.uuid() });
|
|
53
|
+
|
|
54
|
+
const OutcomeBase = {
|
|
55
|
+
requestId: z.string().min(1),
|
|
56
|
+
subjectType: z.string().min(1),
|
|
57
|
+
subjectId: z.string().min(1),
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export const SignatureCompletedEventSchema = z.object({
|
|
61
|
+
...OutcomeBase,
|
|
62
|
+
completedFileId: z.string().min(1),
|
|
63
|
+
signerCount: z.number().int().nonnegative(),
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
export const SignatureDeclinedEventSchema = z.object({
|
|
67
|
+
...OutcomeBase,
|
|
68
|
+
signerId: z.string().min(1),
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
export const SignatureExpiredEventSchema = z.object(OutcomeBase);
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { inflateSync } from "node:zlib";
|
|
2
|
+
|
|
3
|
+
export const MAX_SIGNATURE_PNG_BYTES = 300_000;
|
|
4
|
+
const MAX_DIMENSION = 3000;
|
|
5
|
+
const MIN_DIMENSION = 16;
|
|
6
|
+
const MAX_PIXELS = 4_000_000;
|
|
7
|
+
const MIN_INK_PIXELS = 20;
|
|
8
|
+
|
|
9
|
+
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] as const;
|
|
10
|
+
const COLOR_TYPE_GRAY_ALPHA = 4;
|
|
11
|
+
const COLOR_TYPE_RGBA = 6;
|
|
12
|
+
const BYTES_PER_PIXEL: Readonly<Record<number, number>> = {
|
|
13
|
+
[COLOR_TYPE_GRAY_ALPHA]: 2,
|
|
14
|
+
[COLOR_TYPE_RGBA]: 4,
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export type SignaturePngCheck =
|
|
18
|
+
| { readonly ok: true; readonly width: number; readonly height: number }
|
|
19
|
+
| { readonly ok: false; readonly reason: string };
|
|
20
|
+
|
|
21
|
+
const rejected = (reason: string): SignaturePngCheck => ({ ok: false, reason });
|
|
22
|
+
|
|
23
|
+
type Header = {
|
|
24
|
+
readonly width: number;
|
|
25
|
+
readonly height: number;
|
|
26
|
+
readonly bytesPerPixel: number;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
function hasPngSignature(bytes: Uint8Array): boolean {
|
|
30
|
+
return PNG_SIGNATURE.every((value, index) => bytes[index] === value);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function readHeader(view: DataView): Header | string {
|
|
34
|
+
const width = view.getUint32(16);
|
|
35
|
+
const height = view.getUint32(20);
|
|
36
|
+
const bitDepth = view.getUint8(24);
|
|
37
|
+
const colorType = view.getUint8(25);
|
|
38
|
+
const interlace = view.getUint8(28);
|
|
39
|
+
const bytesPerPixel = BYTES_PER_PIXEL[colorType];
|
|
40
|
+
if (bitDepth !== 8 || bytesPerPixel === undefined) return "unsupported_pixel_format";
|
|
41
|
+
if (interlace !== 0) return "interlaced";
|
|
42
|
+
if (width < MIN_DIMENSION || height < MIN_DIMENSION) return "too_small";
|
|
43
|
+
if (width > MAX_DIMENSION || height > MAX_DIMENSION || width * height > MAX_PIXELS) {
|
|
44
|
+
return "too_large";
|
|
45
|
+
}
|
|
46
|
+
return { width, height, bytesPerPixel };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function collectImageData(bytes: Uint8Array, view: DataView): Uint8Array | null {
|
|
50
|
+
const parts: Uint8Array[] = [];
|
|
51
|
+
let offset = 8;
|
|
52
|
+
while (offset + 12 <= bytes.length) {
|
|
53
|
+
const length = view.getUint32(offset);
|
|
54
|
+
const type = String.fromCharCode(...bytes.subarray(offset + 4, offset + 8));
|
|
55
|
+
const dataStart = offset + 8;
|
|
56
|
+
if (dataStart + length + 4 > bytes.length) return null;
|
|
57
|
+
if (type === "IDAT") parts.push(bytes.subarray(dataStart, dataStart + length));
|
|
58
|
+
if (type === "IEND") break;
|
|
59
|
+
offset = dataStart + length + 4;
|
|
60
|
+
}
|
|
61
|
+
if (parts.length === 0) return null;
|
|
62
|
+
const joined = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
|
63
|
+
let written = 0;
|
|
64
|
+
for (const part of parts) {
|
|
65
|
+
joined.set(part, written);
|
|
66
|
+
written += part.length;
|
|
67
|
+
}
|
|
68
|
+
return joined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function paeth(left: number, up: number, upLeft: number): number {
|
|
72
|
+
const estimate = left + up - upLeft;
|
|
73
|
+
const distanceLeft = Math.abs(estimate - left);
|
|
74
|
+
const distanceUp = Math.abs(estimate - up);
|
|
75
|
+
const distanceUpLeft = Math.abs(estimate - upLeft);
|
|
76
|
+
if (distanceLeft <= distanceUp && distanceLeft <= distanceUpLeft) return left;
|
|
77
|
+
return distanceUp <= distanceUpLeft ? up : upLeft;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Reverses one filtered byte; null for an unknown filter type.
|
|
81
|
+
function unfilterByte(
|
|
82
|
+
filter: number | undefined,
|
|
83
|
+
current: number,
|
|
84
|
+
left: number,
|
|
85
|
+
up: number,
|
|
86
|
+
upLeft: number,
|
|
87
|
+
): number | null {
|
|
88
|
+
switch (filter) {
|
|
89
|
+
case 0:
|
|
90
|
+
return current;
|
|
91
|
+
case 1:
|
|
92
|
+
return (current + left) & 0xff;
|
|
93
|
+
case 2:
|
|
94
|
+
return (current + up) & 0xff;
|
|
95
|
+
case 3:
|
|
96
|
+
return (current + ((left + up) >> 1)) & 0xff;
|
|
97
|
+
case 4:
|
|
98
|
+
return (current + paeth(left, up, upLeft)) & 0xff;
|
|
99
|
+
default:
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Reverses the per-row PNG filters in place; returns false for an unknown filter type.
|
|
105
|
+
function unfilterRows(raw: Uint8Array, header: Header): boolean {
|
|
106
|
+
const bpp = header.bytesPerPixel;
|
|
107
|
+
const rowBytes = header.width * bpp;
|
|
108
|
+
const stride = rowBytes + 1;
|
|
109
|
+
for (let row = 0; row < header.height; row++) {
|
|
110
|
+
const filter = raw[row * stride];
|
|
111
|
+
const start = row * stride + 1;
|
|
112
|
+
for (let i = 0; i < rowBytes; i++) {
|
|
113
|
+
const left = i >= bpp ? (raw[start + i - bpp] ?? 0) : 0;
|
|
114
|
+
const up = row > 0 ? (raw[start - stride + i] ?? 0) : 0;
|
|
115
|
+
const upLeft = row > 0 && i >= bpp ? (raw[start - stride + i - bpp] ?? 0) : 0;
|
|
116
|
+
const restored = unfilterByte(filter, raw[start + i] ?? 0, left, up, upLeft);
|
|
117
|
+
if (restored === null) return false;
|
|
118
|
+
raw[start + i] = restored;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function countInkPixels(raw: Uint8Array, header: Header): number {
|
|
125
|
+
const stride = header.width * header.bytesPerPixel + 1;
|
|
126
|
+
let ink = 0;
|
|
127
|
+
for (let row = 0; row < header.height; row++) {
|
|
128
|
+
for (let column = 0; column < header.width; column++) {
|
|
129
|
+
const alphaIndex =
|
|
130
|
+
row * stride + 1 + column * header.bytesPerPixel + header.bytesPerPixel - 1;
|
|
131
|
+
if ((raw[alphaIndex] ?? 0) > 0) ink++;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return ink;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// A real PNG with an alpha channel and at least a few drawn pixels. Dimensions and the inflated
|
|
138
|
+
// size are capped before anything is decoded, so a crafted file cannot exhaust memory.
|
|
139
|
+
export function checkSignaturePng(bytes: Uint8Array): SignaturePngCheck {
|
|
140
|
+
if (bytes.length > MAX_SIGNATURE_PNG_BYTES) return rejected("too_many_bytes");
|
|
141
|
+
if (bytes.length < 33 || !hasPngSignature(bytes)) return rejected("not_a_png");
|
|
142
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
143
|
+
if (String.fromCharCode(...bytes.subarray(12, 16)) !== "IHDR") return rejected("not_a_png");
|
|
144
|
+
const header = readHeader(view);
|
|
145
|
+
if (typeof header === "string") return rejected(header);
|
|
146
|
+
|
|
147
|
+
const compressed = collectImageData(bytes, view);
|
|
148
|
+
if (compressed === null) return rejected("no_image_data");
|
|
149
|
+
const expectedLength = header.height * (header.width * header.bytesPerPixel + 1);
|
|
150
|
+
let raw: Uint8Array;
|
|
151
|
+
try {
|
|
152
|
+
raw = new Uint8Array(inflateSync(compressed, { maxOutputLength: expectedLength }));
|
|
153
|
+
} catch {
|
|
154
|
+
return rejected("corrupt_image_data");
|
|
155
|
+
}
|
|
156
|
+
if (raw.length !== expectedLength) return rejected("corrupt_image_data");
|
|
157
|
+
if (!unfilterRows(raw, header)) return rejected("corrupt_image_data");
|
|
158
|
+
if (countInkPixels(raw, header) < MIN_INK_PIXELS) return rejected("empty");
|
|
159
|
+
return { ok: true, width: header.width, height: header.height };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
163
|
+
|
|
164
|
+
// The image arrives as base64 inside the JSON payload; the cap keeps the decode bounded.
|
|
165
|
+
export function decodeSignaturePngBase64(base64: string): Uint8Array | null {
|
|
166
|
+
if (base64.length > Math.ceil((MAX_SIGNATURE_PNG_BYTES * 4) / 3) + 4) return null;
|
|
167
|
+
if (!BASE64_PATTERN.test(base64)) return null;
|
|
168
|
+
return new Uint8Array(Buffer.from(base64, "base64"));
|
|
169
|
+
}
|