@cosmicdrift/kumiko-bundled-features 0.415.0 → 0.417.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-tools/tool-catalog.js +20 -1
- package/dist/agent-tools/tool-dispatch.js +14 -5
- package/dist/channel-whatsapp/constants.d.ts +1 -0
- package/dist/channel-whatsapp/constants.js +1 -0
- package/dist/channel-whatsapp/graph-client.d.ts +2 -0
- package/dist/channel-whatsapp/graph-client.js +29 -2
- package/dist/handbook-knowledge/constants.d.ts +6 -0
- package/dist/handbook-knowledge/constants.js +6 -0
- package/dist/handbook-knowledge/feature.d.ts +9 -0
- package/dist/handbook-knowledge/feature.js +17 -0
- package/dist/handbook-knowledge/handbook-index.d.ts +26 -0
- package/dist/handbook-knowledge/handbook-index.js +51 -0
- package/dist/handbook-knowledge/handlers.d.ts +28 -0
- package/dist/handbook-knowledge/handlers.js +67 -0
- package/dist/handbook-knowledge/index.d.ts +3 -0
- package/dist/handbook-knowledge/index.js +2 -0
- package/dist/helpdesk/screens.js +5 -1
- package/dist/signature/entity.d.ts +552 -0
- package/dist/signature/entity.js +156 -0
- package/dist/signature/feature.d.ts +3 -0
- package/dist/signature/feature.js +97 -0
- package/dist/signature/files.d.ts +23 -0
- package/dist/signature/files.js +64 -0
- package/dist/signature/grant.d.ts +32 -0
- package/dist/signature/grant.js +44 -0
- package/dist/signature/handlers/anonymous.write.d.ts +14 -0
- package/dist/signature/handlers/anonymous.write.js +52 -0
- package/dist/signature/handlers/cancel.write.d.ts +7 -0
- package/dist/signature/handlers/cancel.write.js +37 -0
- package/dist/signature/handlers/issue-link.write.d.ts +10 -0
- package/dist/signature/handlers/issue-link.write.js +60 -0
- package/dist/signature/handlers/lifecycle.write.d.ts +16 -0
- package/dist/signature/handlers/lifecycle.write.js +70 -0
- package/dist/signature/handlers/link-internal.write.d.ts +23 -0
- package/dist/signature/handlers/link-internal.write.js +186 -0
- package/dist/signature/handlers/request.write.d.ts +20 -0
- package/dist/signature/handlers/request.write.js +86 -0
- package/dist/signature/handlers/revoke-link.write.d.ts +7 -0
- package/dist/signature/handlers/revoke-link.write.js +27 -0
- package/dist/signature/handlers/sign-in-person.write.d.ts +9 -0
- package/dist/signature/handlers/sign-in-person.write.js +55 -0
- package/dist/signature/i18n.d.ts +6 -0
- package/dist/signature/i18n.js +49 -0
- package/dist/signature/index.d.ts +5 -0
- package/dist/signature/index.js +2 -0
- package/dist/signature/lib.d.ts +54 -0
- package/dist/signature/lib.js +68 -0
- package/dist/signature/options.d.ts +40 -0
- package/dist/signature/options.js +5 -0
- package/dist/signature/payloads.d.ts +60 -0
- package/dist/signature/payloads.js +53 -0
- package/dist/signature/png.d.ts +11 -0
- package/dist/signature/png.js +159 -0
- package/dist/signature/screens.d.ts +3 -0
- package/dist/signature/screens.js +97 -0
- package/dist/signature/signature-page.d.ts +25 -0
- package/dist/signature/signature-page.js +62 -0
- package/dist/signature/signing.d.ts +19 -0
- package/dist/signature/signing.js +46 -0
- package/dist/signature/static-sign.d.ts +19 -0
- package/dist/signature/static-sign.js +45 -0
- package/dist/signature/subject-queries.d.ts +5 -0
- package/dist/signature/subject-queries.js +113 -0
- package/dist/signature/subject-scope.d.ts +11 -0
- package/dist/signature/subject-scope.js +20 -0
- package/dist/signature/sweep.d.ts +3 -0
- package/dist/signature/sweep.js +113 -0
- package/dist/signature/user-data.d.ts +3 -0
- package/dist/signature/user-data.js +135 -0
- package/dist/signature/web/constants.d.ts +69 -0
- package/dist/signature/web/constants.js +68 -0
- package/dist/signature/web/index.d.ts +3 -0
- package/dist/signature/web/index.js +2 -0
- package/dist/signature/web/pad.d.ts +20 -0
- package/dist/signature/web/pad.js +104 -0
- package/dist/signature/web/signature-pad.d.ts +19 -0
- package/dist/signature/web/signature-pad.js +36 -0
- package/dist/subscription-stripe/feature.d.ts +6 -0
- package/dist/subscription-stripe/feature.js +3 -0
- package/dist/subscription-stripe/plugin-methods.d.ts +3 -1
- package/dist/subscription-stripe/plugin-methods.js +2 -1
- package/package.json +43 -11
- package/src/agent-tools/changes.json +6 -0
- package/src/channel-whatsapp/changes.json +6 -0
- package/src/handbook-knowledge/changes.json +8 -0
- package/src/signature/changes.json +22 -0
- package/src/subscription-stripe/changes.json +6 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { access, } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
|
|
3
|
+
import { generateId } from "@cosmicdrift/kumiko-framework/utils";
|
|
4
|
+
import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
|
|
5
|
+
import { requestExecutor, signerExecutor } from "./entity.js";
|
|
6
|
+
import { SIGNATURE_INVALID_LINK_REASON, SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_STATUS, } from "./web/constants.js";
|
|
7
|
+
export const DEFAULT_SIGNATURE_ACCESS = { roles: ["TenantAdmin", "TenantMember"] };
|
|
8
|
+
export const internalAccess = { roles: access.system };
|
|
9
|
+
export const SIGNATURE_OUTCOME_AGGREGATE_TYPE = "signature-outcome";
|
|
10
|
+
// Same body and status for every link rejection: forged, expired, revoked, used up, signed already.
|
|
11
|
+
export function invalidLink() {
|
|
12
|
+
return writeFailure(new UnprocessableError(SIGNATURE_INVALID_LINK_REASON));
|
|
13
|
+
}
|
|
14
|
+
export function instantOrNull(value) {
|
|
15
|
+
return value instanceof Temporal.Instant ? value : null;
|
|
16
|
+
}
|
|
17
|
+
export function isPastInstant(value, now) {
|
|
18
|
+
const instant = instantOrNull(value);
|
|
19
|
+
return instant !== null && Temporal.Instant.compare(instant, now) <= 0;
|
|
20
|
+
}
|
|
21
|
+
export function isOpenRequest(request, now) {
|
|
22
|
+
return request.status === SIGNATURE_REQUEST_STATUS.Open && !isPastInstant(request.expiresAt, now);
|
|
23
|
+
}
|
|
24
|
+
export function isUnsignedSigner(signer) {
|
|
25
|
+
return (signer.status === SIGNATURE_SIGNER_STATUS.Pending ||
|
|
26
|
+
signer.status === SIGNATURE_SIGNER_STATUS.Viewed);
|
|
27
|
+
}
|
|
28
|
+
// Equals the executor's MAX_LIST_LIMIT.
|
|
29
|
+
const LIST_PAGE_SIZE = 200;
|
|
30
|
+
export async function listSigners(ctx, user, requestId) {
|
|
31
|
+
const found = await signerExecutor.list({ filter: { field: "requestId", op: "eq", value: requestId }, limit: LIST_PAGE_SIZE }, user, ctx.db);
|
|
32
|
+
return found.rows;
|
|
33
|
+
}
|
|
34
|
+
export function versionOf(row) {
|
|
35
|
+
return typeof row.version === "number" ? row.version : undefined;
|
|
36
|
+
}
|
|
37
|
+
export async function setRequestStatus(ctx, user, requestId, from, changes) {
|
|
38
|
+
return requestExecutor.update({ id: requestId, changes }, user, ctx.db, {
|
|
39
|
+
skipOptimisticLock: true,
|
|
40
|
+
expect: { status: from },
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
// Moves an open request to all-signed once every signer has signed. Two signers committing at the
|
|
44
|
+
// same moment can both still see the other as unsigned; the sweep job repeats this check.
|
|
45
|
+
export async function advanceIfAllSigned(ctx, user, requestId) {
|
|
46
|
+
const signers = await listSigners(ctx, user, requestId);
|
|
47
|
+
const allSigned = signers.length > 0 &&
|
|
48
|
+
signers.every((signer) => signer.status === SIGNATURE_SIGNER_STATUS.Signed);
|
|
49
|
+
if (!allSigned)
|
|
50
|
+
return false;
|
|
51
|
+
const moved = await setRequestStatus(ctx, user, requestId, SIGNATURE_REQUEST_STATUS.Open, {
|
|
52
|
+
status: SIGNATURE_REQUEST_STATUS.AllSigned,
|
|
53
|
+
});
|
|
54
|
+
return moved.isSuccess;
|
|
55
|
+
}
|
|
56
|
+
export function loadRequestOfSigner(ctx, user, signer) {
|
|
57
|
+
return requestExecutor.detail({ id: signer.requestId }, user, ctx.db);
|
|
58
|
+
}
|
|
59
|
+
// Each outcome is its own aggregate with a fresh id: it needs no predecessor version and cannot
|
|
60
|
+
// conflict with a concurrent write on the request it describes.
|
|
61
|
+
export function appendOutcomeEvent(ctx, type, payload) {
|
|
62
|
+
return ctx.events.unsafeAppend({
|
|
63
|
+
aggregateId: generateId(),
|
|
64
|
+
aggregateType: SIGNATURE_OUTCOME_AGGREGATE_TYPE,
|
|
65
|
+
type,
|
|
66
|
+
payload,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
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
|
+
export type RenderSignatureHtmlToPdf = (html: string, options?: PdfOptions) => Promise<Uint8Array>;
|
|
6
|
+
export type SignatureLinkDelivery = {
|
|
7
|
+
readonly signerId: string;
|
|
8
|
+
readonly requestId: string;
|
|
9
|
+
readonly name: string;
|
|
10
|
+
readonly email: string;
|
|
11
|
+
/** Signing link with the token in the fragment. */
|
|
12
|
+
readonly url: string;
|
|
13
|
+
/** Who issued the link, e.g. to pick the mailbox it is sent from. */
|
|
14
|
+
readonly issuedBy: SessionUser;
|
|
15
|
+
};
|
|
16
|
+
export type DeliverSignatureLink = (ctx: HandlerContext, delivery: SignatureLinkDelivery) => Promise<void>;
|
|
17
|
+
export type SignatureSubject = {
|
|
18
|
+
readonly subjectType: string;
|
|
19
|
+
readonly subjectId: string;
|
|
20
|
+
};
|
|
21
|
+
export type AuthorizeSignatureSubject = (ctx: HandlerContext, user: SessionUser, subject: SignatureSubject) => Promise<boolean>;
|
|
22
|
+
export type SignatureOptions = {
|
|
23
|
+
/** How long requests and signers are kept, data-retention keepFor syntax, counted from creation. */
|
|
24
|
+
readonly retention: SignatureRetention;
|
|
25
|
+
/** Renders the signature page (HTML) to a PDF. An outage leaves the request at `all-signed` and the sweep job retries. */
|
|
26
|
+
readonly renderHtmlToPdf: RenderSignatureHtmlToPdf;
|
|
27
|
+
/** HMAC secret of the signing links. Without it every link is rejected. */
|
|
28
|
+
readonly linkSecret: string;
|
|
29
|
+
/** Sends a freshly issued link to the signer, e.g. by mail. A throw fails issue-link and leaves no link sent. */
|
|
30
|
+
readonly deliverLink: DeliverSignatureLink;
|
|
31
|
+
/** URL of the app's signature page; the token is appended as `#<token>`. */
|
|
32
|
+
readonly signaturePageUrl: string;
|
|
33
|
+
/** 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. */
|
|
34
|
+
readonly access?: AccessRule;
|
|
35
|
+
/** Runs for every signed-in handler and query on the subject of the request, except for `unscopedRoles`. `false` answers like "does not exist". Without it every user with `access` sees every request of the tenant. */
|
|
36
|
+
readonly authorizeSubject?: AuthorizeSignatureSubject;
|
|
37
|
+
/** Roles that skip `authorizeSubject`, e.g. admins. */
|
|
38
|
+
readonly unscopedRoles?: readonly string[];
|
|
39
|
+
};
|
|
40
|
+
export declare const LINK_RATE_LIMIT: RateLimitDeclaration;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
export declare const MAX_SIGNERS_PER_REQUEST = 20;
|
|
3
|
+
export declare const RequestSignatureSchema: z.ZodObject<{
|
|
4
|
+
documentFileId: z.ZodUUID;
|
|
5
|
+
title: z.ZodString;
|
|
6
|
+
level: z.ZodDefault<z.ZodLiteral<"simple">>;
|
|
7
|
+
subjectType: z.ZodString;
|
|
8
|
+
subjectId: z.ZodString;
|
|
9
|
+
expiresInDays: z.ZodOptional<z.ZodNumber>;
|
|
10
|
+
signers: z.ZodArray<z.ZodObject<{
|
|
11
|
+
name: z.ZodString;
|
|
12
|
+
role: z.ZodOptional<z.ZodString>;
|
|
13
|
+
contactId: z.ZodOptional<z.ZodString>;
|
|
14
|
+
email: z.ZodOptional<z.ZodString>;
|
|
15
|
+
}, z.core.$strip>>;
|
|
16
|
+
}, z.core.$strip>;
|
|
17
|
+
export type RequestSignatureInput = z.infer<typeof RequestSignatureSchema>;
|
|
18
|
+
export declare const SignInPersonSchema: z.ZodObject<{
|
|
19
|
+
signerId: z.ZodUUID;
|
|
20
|
+
imagePngBase64: z.ZodString;
|
|
21
|
+
}, z.core.$strip>;
|
|
22
|
+
export declare const SignerIdSchema: z.ZodObject<{
|
|
23
|
+
signerId: z.ZodUUID;
|
|
24
|
+
}, z.core.$strip>;
|
|
25
|
+
export declare const RequestIdSchema: z.ZodObject<{
|
|
26
|
+
requestId: z.ZodUUID;
|
|
27
|
+
}, z.core.$strip>;
|
|
28
|
+
export declare const OpenByLinkSchema: z.ZodObject<{
|
|
29
|
+
token: z.ZodString;
|
|
30
|
+
}, z.core.$strip>;
|
|
31
|
+
export declare const SignByLinkSchema: z.ZodObject<{
|
|
32
|
+
token: z.ZodString;
|
|
33
|
+
imagePngBase64: z.ZodString;
|
|
34
|
+
}, z.core.$strip>;
|
|
35
|
+
export declare const DeclineByLinkSchema: z.ZodObject<{
|
|
36
|
+
token: z.ZodString;
|
|
37
|
+
reason: z.ZodOptional<z.ZodString>;
|
|
38
|
+
}, z.core.$strip>;
|
|
39
|
+
export declare const FinishSchema: z.ZodObject<{
|
|
40
|
+
requestId: z.ZodUUID;
|
|
41
|
+
completedFileId: z.ZodUUID;
|
|
42
|
+
}, z.core.$strip>;
|
|
43
|
+
export declare const SignatureCompletedEventSchema: z.ZodObject<{
|
|
44
|
+
requestId: z.ZodString;
|
|
45
|
+
subjectType: z.ZodString;
|
|
46
|
+
subjectId: z.ZodString;
|
|
47
|
+
completedFileId: z.ZodString;
|
|
48
|
+
signerCount: z.ZodNumber;
|
|
49
|
+
}, z.core.$strip>;
|
|
50
|
+
export declare const SignatureDeclinedEventSchema: z.ZodObject<{
|
|
51
|
+
requestId: z.ZodString;
|
|
52
|
+
subjectType: z.ZodString;
|
|
53
|
+
subjectId: z.ZodString;
|
|
54
|
+
signerId: z.ZodString;
|
|
55
|
+
}, z.core.$strip>;
|
|
56
|
+
export declare const SignatureExpiredEventSchema: z.ZodObject<{
|
|
57
|
+
requestId: z.ZodString;
|
|
58
|
+
subjectType: z.ZodString;
|
|
59
|
+
subjectId: z.ZodString;
|
|
60
|
+
}, z.core.$strip>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { MAX_SIGNATURE_PNG_BYTES } from "./png.js";
|
|
3
|
+
import { SIGNATURE_LEVEL } from "./web/constants.js";
|
|
4
|
+
export const MAX_SIGNERS_PER_REQUEST = 20;
|
|
5
|
+
const MAX_VALIDITY_DAYS = 365;
|
|
6
|
+
// Base64 inflates by 4/3; the png checks apply to the decoded bytes.
|
|
7
|
+
const MAX_IMAGE_BASE64_LENGTH = Math.ceil((MAX_SIGNATURE_PNG_BYTES * 4) / 3) + 4;
|
|
8
|
+
const MAX_TOKEN_LENGTH = 2000;
|
|
9
|
+
const SignerInputSchema = z.object({
|
|
10
|
+
name: z.string().trim().min(1).max(200),
|
|
11
|
+
role: z.string().trim().min(1).max(100).optional(),
|
|
12
|
+
contactId: z.string().min(1).max(64).optional(),
|
|
13
|
+
email: z.string().trim().min(3).max(320).optional(),
|
|
14
|
+
});
|
|
15
|
+
export const RequestSignatureSchema = z.object({
|
|
16
|
+
documentFileId: z.uuid(),
|
|
17
|
+
title: z.string().trim().min(1).max(200),
|
|
18
|
+
level: z.literal(SIGNATURE_LEVEL.Simple).default(SIGNATURE_LEVEL.Simple),
|
|
19
|
+
subjectType: z.string().trim().min(1).max(100),
|
|
20
|
+
subjectId: z.string().trim().min(1).max(100),
|
|
21
|
+
expiresInDays: z.number().int().min(1).max(MAX_VALIDITY_DAYS).optional(),
|
|
22
|
+
signers: z.array(SignerInputSchema).min(1).max(MAX_SIGNERS_PER_REQUEST),
|
|
23
|
+
});
|
|
24
|
+
const ImagePayload = z.string().min(1).max(MAX_IMAGE_BASE64_LENGTH);
|
|
25
|
+
export const SignInPersonSchema = z.object({
|
|
26
|
+
signerId: z.uuid(),
|
|
27
|
+
imagePngBase64: ImagePayload,
|
|
28
|
+
});
|
|
29
|
+
export const SignerIdSchema = z.object({ signerId: z.uuid() });
|
|
30
|
+
export const RequestIdSchema = z.object({ requestId: z.uuid() });
|
|
31
|
+
const TokenPayload = z.string().min(1).max(MAX_TOKEN_LENGTH);
|
|
32
|
+
export const OpenByLinkSchema = z.object({ token: TokenPayload });
|
|
33
|
+
export const SignByLinkSchema = z.object({ token: TokenPayload, imagePngBase64: ImagePayload });
|
|
34
|
+
export const DeclineByLinkSchema = z.object({
|
|
35
|
+
token: TokenPayload,
|
|
36
|
+
reason: z.string().trim().min(1).max(1000).optional(),
|
|
37
|
+
});
|
|
38
|
+
export const FinishSchema = z.object({ requestId: z.uuid(), completedFileId: z.uuid() });
|
|
39
|
+
const OutcomeBase = {
|
|
40
|
+
requestId: z.string().min(1),
|
|
41
|
+
subjectType: z.string().min(1),
|
|
42
|
+
subjectId: z.string().min(1),
|
|
43
|
+
};
|
|
44
|
+
export const SignatureCompletedEventSchema = z.object({
|
|
45
|
+
...OutcomeBase,
|
|
46
|
+
completedFileId: z.string().min(1),
|
|
47
|
+
signerCount: z.number().int().nonnegative(),
|
|
48
|
+
});
|
|
49
|
+
export const SignatureDeclinedEventSchema = z.object({
|
|
50
|
+
...OutcomeBase,
|
|
51
|
+
signerId: z.string().min(1),
|
|
52
|
+
});
|
|
53
|
+
export const SignatureExpiredEventSchema = z.object(OutcomeBase);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const MAX_SIGNATURE_PNG_BYTES = 300000;
|
|
2
|
+
export type SignaturePngCheck = {
|
|
3
|
+
readonly ok: true;
|
|
4
|
+
readonly width: number;
|
|
5
|
+
readonly height: number;
|
|
6
|
+
} | {
|
|
7
|
+
readonly ok: false;
|
|
8
|
+
readonly reason: string;
|
|
9
|
+
};
|
|
10
|
+
export declare function checkSignaturePng(bytes: Uint8Array): SignaturePngCheck;
|
|
11
|
+
export declare function decodeSignaturePngBase64(base64: string): Uint8Array | null;
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { inflateSync } from "node:zlib";
|
|
2
|
+
export const MAX_SIGNATURE_PNG_BYTES = 300_000;
|
|
3
|
+
const MAX_DIMENSION = 3000;
|
|
4
|
+
const MIN_DIMENSION = 16;
|
|
5
|
+
const MAX_PIXELS = 4_000_000;
|
|
6
|
+
const MIN_INK_PIXELS = 20;
|
|
7
|
+
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
|
8
|
+
const COLOR_TYPE_GRAY_ALPHA = 4;
|
|
9
|
+
const COLOR_TYPE_RGBA = 6;
|
|
10
|
+
const BYTES_PER_PIXEL = {
|
|
11
|
+
[COLOR_TYPE_GRAY_ALPHA]: 2,
|
|
12
|
+
[COLOR_TYPE_RGBA]: 4,
|
|
13
|
+
};
|
|
14
|
+
const rejected = (reason) => ({ ok: false, reason });
|
|
15
|
+
function hasPngSignature(bytes) {
|
|
16
|
+
return PNG_SIGNATURE.every((value, index) => bytes[index] === value);
|
|
17
|
+
}
|
|
18
|
+
function readHeader(view) {
|
|
19
|
+
const width = view.getUint32(16);
|
|
20
|
+
const height = view.getUint32(20);
|
|
21
|
+
const bitDepth = view.getUint8(24);
|
|
22
|
+
const colorType = view.getUint8(25);
|
|
23
|
+
const interlace = view.getUint8(28);
|
|
24
|
+
const bytesPerPixel = BYTES_PER_PIXEL[colorType];
|
|
25
|
+
if (bitDepth !== 8 || bytesPerPixel === undefined)
|
|
26
|
+
return "unsupported_pixel_format";
|
|
27
|
+
if (interlace !== 0)
|
|
28
|
+
return "interlaced";
|
|
29
|
+
if (width < MIN_DIMENSION || height < MIN_DIMENSION)
|
|
30
|
+
return "too_small";
|
|
31
|
+
if (width > MAX_DIMENSION || height > MAX_DIMENSION || width * height > MAX_PIXELS) {
|
|
32
|
+
return "too_large";
|
|
33
|
+
}
|
|
34
|
+
return { width, height, bytesPerPixel };
|
|
35
|
+
}
|
|
36
|
+
function collectImageData(bytes, view) {
|
|
37
|
+
const parts = [];
|
|
38
|
+
let offset = 8;
|
|
39
|
+
while (offset + 12 <= bytes.length) {
|
|
40
|
+
const length = view.getUint32(offset);
|
|
41
|
+
const type = String.fromCharCode(...bytes.subarray(offset + 4, offset + 8));
|
|
42
|
+
const dataStart = offset + 8;
|
|
43
|
+
if (dataStart + length + 4 > bytes.length)
|
|
44
|
+
return null;
|
|
45
|
+
if (type === "IDAT")
|
|
46
|
+
parts.push(bytes.subarray(dataStart, dataStart + length));
|
|
47
|
+
if (type === "IEND")
|
|
48
|
+
break;
|
|
49
|
+
offset = dataStart + length + 4;
|
|
50
|
+
}
|
|
51
|
+
if (parts.length === 0)
|
|
52
|
+
return null;
|
|
53
|
+
const joined = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
|
54
|
+
let written = 0;
|
|
55
|
+
for (const part of parts) {
|
|
56
|
+
joined.set(part, written);
|
|
57
|
+
written += part.length;
|
|
58
|
+
}
|
|
59
|
+
return joined;
|
|
60
|
+
}
|
|
61
|
+
function paeth(left, up, upLeft) {
|
|
62
|
+
const estimate = left + up - upLeft;
|
|
63
|
+
const distanceLeft = Math.abs(estimate - left);
|
|
64
|
+
const distanceUp = Math.abs(estimate - up);
|
|
65
|
+
const distanceUpLeft = Math.abs(estimate - upLeft);
|
|
66
|
+
if (distanceLeft <= distanceUp && distanceLeft <= distanceUpLeft)
|
|
67
|
+
return left;
|
|
68
|
+
return distanceUp <= distanceUpLeft ? up : upLeft;
|
|
69
|
+
}
|
|
70
|
+
// Reverses one filtered byte; null for an unknown filter type.
|
|
71
|
+
function unfilterByte(filter, current, left, up, upLeft) {
|
|
72
|
+
switch (filter) {
|
|
73
|
+
case 0:
|
|
74
|
+
return current;
|
|
75
|
+
case 1:
|
|
76
|
+
return (current + left) & 0xff;
|
|
77
|
+
case 2:
|
|
78
|
+
return (current + up) & 0xff;
|
|
79
|
+
case 3:
|
|
80
|
+
return (current + ((left + up) >> 1)) & 0xff;
|
|
81
|
+
case 4:
|
|
82
|
+
return (current + paeth(left, up, upLeft)) & 0xff;
|
|
83
|
+
default:
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// Reverses the per-row PNG filters in place; returns false for an unknown filter type.
|
|
88
|
+
function unfilterRows(raw, header) {
|
|
89
|
+
const bpp = header.bytesPerPixel;
|
|
90
|
+
const rowBytes = header.width * bpp;
|
|
91
|
+
const stride = rowBytes + 1;
|
|
92
|
+
for (let row = 0; row < header.height; row++) {
|
|
93
|
+
const filter = raw[row * stride];
|
|
94
|
+
const start = row * stride + 1;
|
|
95
|
+
for (let i = 0; i < rowBytes; i++) {
|
|
96
|
+
const left = i >= bpp ? (raw[start + i - bpp] ?? 0) : 0;
|
|
97
|
+
const up = row > 0 ? (raw[start - stride + i] ?? 0) : 0;
|
|
98
|
+
const upLeft = row > 0 && i >= bpp ? (raw[start - stride + i - bpp] ?? 0) : 0;
|
|
99
|
+
const restored = unfilterByte(filter, raw[start + i] ?? 0, left, up, upLeft);
|
|
100
|
+
if (restored === null)
|
|
101
|
+
return false;
|
|
102
|
+
raw[start + i] = restored;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
function countInkPixels(raw, header) {
|
|
108
|
+
const stride = header.width * header.bytesPerPixel + 1;
|
|
109
|
+
let ink = 0;
|
|
110
|
+
for (let row = 0; row < header.height; row++) {
|
|
111
|
+
for (let column = 0; column < header.width; column++) {
|
|
112
|
+
const alphaIndex = row * stride + 1 + column * header.bytesPerPixel + header.bytesPerPixel - 1;
|
|
113
|
+
if ((raw[alphaIndex] ?? 0) > 0)
|
|
114
|
+
ink++;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return ink;
|
|
118
|
+
}
|
|
119
|
+
// A real PNG with an alpha channel and at least a few drawn pixels. Dimensions and the inflated
|
|
120
|
+
// size are capped before anything is decoded, so a crafted file cannot exhaust memory.
|
|
121
|
+
export function checkSignaturePng(bytes) {
|
|
122
|
+
if (bytes.length > MAX_SIGNATURE_PNG_BYTES)
|
|
123
|
+
return rejected("too_many_bytes");
|
|
124
|
+
if (bytes.length < 33 || !hasPngSignature(bytes))
|
|
125
|
+
return rejected("not_a_png");
|
|
126
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
127
|
+
if (String.fromCharCode(...bytes.subarray(12, 16)) !== "IHDR")
|
|
128
|
+
return rejected("not_a_png");
|
|
129
|
+
const header = readHeader(view);
|
|
130
|
+
if (typeof header === "string")
|
|
131
|
+
return rejected(header);
|
|
132
|
+
const compressed = collectImageData(bytes, view);
|
|
133
|
+
if (compressed === null)
|
|
134
|
+
return rejected("no_image_data");
|
|
135
|
+
const expectedLength = header.height * (header.width * header.bytesPerPixel + 1);
|
|
136
|
+
let raw;
|
|
137
|
+
try {
|
|
138
|
+
raw = new Uint8Array(inflateSync(compressed, { maxOutputLength: expectedLength }));
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return rejected("corrupt_image_data");
|
|
142
|
+
}
|
|
143
|
+
if (raw.length !== expectedLength)
|
|
144
|
+
return rejected("corrupt_image_data");
|
|
145
|
+
if (!unfilterRows(raw, header))
|
|
146
|
+
return rejected("corrupt_image_data");
|
|
147
|
+
if (countInkPixels(raw, header) < MIN_INK_PIXELS)
|
|
148
|
+
return rejected("empty");
|
|
149
|
+
return { ok: true, width: header.width, height: header.height };
|
|
150
|
+
}
|
|
151
|
+
const BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
152
|
+
// The image arrives as base64 inside the JSON payload; the cap keeps the decode bounded.
|
|
153
|
+
export function decodeSignaturePngBase64(base64) {
|
|
154
|
+
if (base64.length > Math.ceil((MAX_SIGNATURE_PNG_BYTES * 4) / 3) + 4)
|
|
155
|
+
return null;
|
|
156
|
+
if (!BASE64_PATTERN.test(base64))
|
|
157
|
+
return null;
|
|
158
|
+
return new Uint8Array(Buffer.from(base64, "base64"));
|
|
159
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type EntityListScreenDefinition, type ProjectionDetailScreenDefinition } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
export declare function createSignatureListScreen(access: EntityListScreenDefinition["access"]): EntityListScreenDefinition;
|
|
3
|
+
export declare function createSignatureDetailScreen(access: ProjectionDetailScreenDefinition["access"]): ProjectionDetailScreenDefinition;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { i18nKey, } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import { SIGNATURE_REQUEST_ENTITY, SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_ENTITY, SIGNATURE_SIGNER_STATUS, SignatureHandlers, SignatureQueries, } from "./web/constants.js";
|
|
3
|
+
const REQUEST = `signature:entity:${SIGNATURE_REQUEST_ENTITY}:field`;
|
|
4
|
+
const UNSIGNED_SIGNER = {
|
|
5
|
+
field: "status",
|
|
6
|
+
in: [SIGNATURE_SIGNER_STATUS.Pending, SIGNATURE_SIGNER_STATUS.Viewed],
|
|
7
|
+
};
|
|
8
|
+
const CANCEL_ACTION = {
|
|
9
|
+
id: "cancel",
|
|
10
|
+
label: i18nKey("signature.action.cancel"),
|
|
11
|
+
handler: SignatureHandlers.cancel,
|
|
12
|
+
payload: { map: { requestId: "id" } },
|
|
13
|
+
confirm: i18nKey("signature.action.cancel.confirm"),
|
|
14
|
+
style: "danger",
|
|
15
|
+
visible: { field: "status", eq: SIGNATURE_REQUEST_STATUS.Open },
|
|
16
|
+
};
|
|
17
|
+
export function createSignatureListScreen(access) {
|
|
18
|
+
return {
|
|
19
|
+
id: "signature-list",
|
|
20
|
+
type: "entityList",
|
|
21
|
+
entity: SIGNATURE_REQUEST_ENTITY,
|
|
22
|
+
columns: [
|
|
23
|
+
"title",
|
|
24
|
+
"status",
|
|
25
|
+
"subjectType",
|
|
26
|
+
{ field: "expiresAt", hideOnNarrow: true },
|
|
27
|
+
{ field: "completedAt", hideOnNarrow: true },
|
|
28
|
+
],
|
|
29
|
+
defaultSort: { field: "expiresAt", dir: "desc" },
|
|
30
|
+
// A user bound by authorizeSubject gets no total, so the list pages by cursor.
|
|
31
|
+
pagination: "infinite",
|
|
32
|
+
access,
|
|
33
|
+
searchable: true,
|
|
34
|
+
rowActions: [
|
|
35
|
+
{
|
|
36
|
+
kind: "navigate",
|
|
37
|
+
id: "open",
|
|
38
|
+
label: i18nKey("signature.action.open"),
|
|
39
|
+
screen: "signature-detail",
|
|
40
|
+
entityId: "id",
|
|
41
|
+
rowClick: true,
|
|
42
|
+
},
|
|
43
|
+
CANCEL_ACTION,
|
|
44
|
+
],
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
// Signing in person needs the drawing pad, which a declarative screen cannot host: the app mounts
|
|
48
|
+
// SignaturePad on its own screen and calls sign-in-person.
|
|
49
|
+
export function createSignatureDetailScreen(access) {
|
|
50
|
+
return {
|
|
51
|
+
id: "signature-detail",
|
|
52
|
+
type: "projectionDetail",
|
|
53
|
+
dormant: true,
|
|
54
|
+
listScreenId: "signature-list",
|
|
55
|
+
query: SignatureQueries.detail,
|
|
56
|
+
access,
|
|
57
|
+
header: { title: "title", status: "status" },
|
|
58
|
+
fieldLabels: {
|
|
59
|
+
status: i18nKey(`${REQUEST}:status`),
|
|
60
|
+
subjectType: i18nKey(`${REQUEST}:subjectType`),
|
|
61
|
+
expiresAt: i18nKey(`${REQUEST}:expiresAt`),
|
|
62
|
+
completedAt: i18nKey(`${REQUEST}:completedAt`),
|
|
63
|
+
},
|
|
64
|
+
actions: [CANCEL_ACTION],
|
|
65
|
+
layout: {
|
|
66
|
+
sections: [
|
|
67
|
+
{ fields: ["status", "subjectType", "expiresAt", "completedAt"] },
|
|
68
|
+
{
|
|
69
|
+
kind: "relatedList",
|
|
70
|
+
title: i18nKey("signature.signers.title"),
|
|
71
|
+
query: SignatureQueries.signerList,
|
|
72
|
+
parentFilter: { field: "requestId" },
|
|
73
|
+
entity: SIGNATURE_SIGNER_ENTITY,
|
|
74
|
+
columns: ["name", "role", "status", "method", { field: "signedAt", hideOnNarrow: true }],
|
|
75
|
+
rowActions: [
|
|
76
|
+
{
|
|
77
|
+
id: "issue-link",
|
|
78
|
+
label: i18nKey("signature.action.issueLink"),
|
|
79
|
+
handler: SignatureHandlers.issueLink,
|
|
80
|
+
payload: { map: { signerId: "id" } },
|
|
81
|
+
visible: UNSIGNED_SIGNER,
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
id: "revoke-link",
|
|
85
|
+
label: i18nKey("signature.action.revokeLink"),
|
|
86
|
+
handler: SignatureHandlers.revokeLink,
|
|
87
|
+
payload: { map: { signerId: "id" } },
|
|
88
|
+
confirm: i18nKey("signature.action.revokeLink.confirm"),
|
|
89
|
+
style: "danger",
|
|
90
|
+
visible: UNSIGNED_SIGNER,
|
|
91
|
+
},
|
|
92
|
+
],
|
|
93
|
+
},
|
|
94
|
+
],
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type SignatureMethod } from "./web/constants.ts";
|
|
2
|
+
export type SignaturePageLabels = {
|
|
3
|
+
readonly heading: string;
|
|
4
|
+
readonly documentHash: string;
|
|
5
|
+
readonly signedAt: string;
|
|
6
|
+
readonly inPerson: string;
|
|
7
|
+
readonly link: string;
|
|
8
|
+
readonly noRole: string;
|
|
9
|
+
};
|
|
10
|
+
export declare const DEFAULT_SIGNATURE_PAGE_LABELS: SignaturePageLabels;
|
|
11
|
+
export type SignaturePageEntry = {
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly role: string | null;
|
|
14
|
+
readonly signedAtIso: string;
|
|
15
|
+
readonly method: SignatureMethod;
|
|
16
|
+
readonly imagePng: Uint8Array;
|
|
17
|
+
};
|
|
18
|
+
export declare function escapeHtml(value: string): string;
|
|
19
|
+
export declare function buildSignaturePageHtml(args: {
|
|
20
|
+
readonly title: string;
|
|
21
|
+
readonly documentSha256: string;
|
|
22
|
+
readonly entries: readonly SignaturePageEntry[];
|
|
23
|
+
readonly labels: SignaturePageLabels;
|
|
24
|
+
}): string;
|
|
25
|
+
export declare function appendPdfPages(original: Uint8Array, appendix: Uint8Array): Promise<Uint8Array>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { PDFDocument } from "pdf-lib";
|
|
2
|
+
import { SIGNATURE_METHOD } from "./web/constants.js";
|
|
3
|
+
export const DEFAULT_SIGNATURE_PAGE_LABELS = {
|
|
4
|
+
heading: "Signature page",
|
|
5
|
+
documentHash: "SHA-256 of the original document",
|
|
6
|
+
signedAt: "Signed",
|
|
7
|
+
inPerson: "In person",
|
|
8
|
+
link: "By link",
|
|
9
|
+
noRole: "",
|
|
10
|
+
};
|
|
11
|
+
const HTML_ESCAPES = {
|
|
12
|
+
"&": "&",
|
|
13
|
+
"<": "<",
|
|
14
|
+
">": ">",
|
|
15
|
+
'"': """,
|
|
16
|
+
"'": "'",
|
|
17
|
+
};
|
|
18
|
+
// Names and titles are free text typed by users; they reach Chromium as HTML, so every value is escaped.
|
|
19
|
+
export function escapeHtml(value) {
|
|
20
|
+
return value.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char);
|
|
21
|
+
}
|
|
22
|
+
function imageDataUri(png) {
|
|
23
|
+
return `data:image/png;base64,${Buffer.from(png).toString("base64")}`;
|
|
24
|
+
}
|
|
25
|
+
function entryHtml(entry, labels) {
|
|
26
|
+
const way = entry.method === SIGNATURE_METHOD.InPerson ? labels.inPerson : labels.link;
|
|
27
|
+
const role = entry.role === null ? labels.noRole : entry.role;
|
|
28
|
+
return `<section class="entry">
|
|
29
|
+
<img src="${escapeHtml(imageDataUri(entry.imagePng))}" alt="">
|
|
30
|
+
<div class="meta">
|
|
31
|
+
<strong>${escapeHtml(entry.name)}</strong>
|
|
32
|
+
${role === "" ? "" : `<span>${escapeHtml(role)}</span>`}
|
|
33
|
+
<span>${escapeHtml(labels.signedAt)}: ${escapeHtml(entry.signedAtIso)} (${escapeHtml(way)})</span>
|
|
34
|
+
</div>
|
|
35
|
+
</section>`;
|
|
36
|
+
}
|
|
37
|
+
export function buildSignaturePageHtml(args) {
|
|
38
|
+
return `<!doctype html>
|
|
39
|
+
<html><head><meta charset="utf-8"><style>
|
|
40
|
+
body { font-family: sans-serif; font-size: 12px; color: #111; margin: 0; }
|
|
41
|
+
h1 { font-size: 20px; margin: 0 0 4px; }
|
|
42
|
+
h2 { font-size: 14px; font-weight: normal; margin: 0 0 24px; }
|
|
43
|
+
.entry { display: flex; align-items: center; gap: 24px; border-top: 1px solid #ccc; padding: 12px 0; page-break-inside: avoid; }
|
|
44
|
+
.entry img { width: 220px; height: 90px; object-fit: contain; }
|
|
45
|
+
.meta { display: flex; flex-direction: column; gap: 2px; }
|
|
46
|
+
.hash { margin-top: 24px; font-family: monospace; font-size: 10px; word-break: break-all; }
|
|
47
|
+
</style></head><body>
|
|
48
|
+
<h1>${escapeHtml(args.labels.heading)}</h1>
|
|
49
|
+
<h2>${escapeHtml(args.title)}</h2>
|
|
50
|
+
${args.entries.map((entry) => entryHtml(entry, args.labels)).join("\n")}
|
|
51
|
+
<p class="hash">${escapeHtml(args.labels.documentHash)}: ${escapeHtml(args.documentSha256)}</p>
|
|
52
|
+
</body></html>`;
|
|
53
|
+
}
|
|
54
|
+
// The original pages are copied as they are; the signature pages only get appended.
|
|
55
|
+
export async function appendPdfPages(original, appendix) {
|
|
56
|
+
const merged = await PDFDocument.load(original);
|
|
57
|
+
const extra = await PDFDocument.load(appendix);
|
|
58
|
+
const pages = await merged.copyPages(extra, extra.getPageIndices());
|
|
59
|
+
for (const page of pages)
|
|
60
|
+
merged.addPage(page);
|
|
61
|
+
return merged.save();
|
|
62
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { TenantDb } from "@cosmicdrift/kumiko-framework/db";
|
|
2
|
+
import type { SessionUser } from "@cosmicdrift/kumiko-framework/engine";
|
|
3
|
+
import type { Temporal } from "@cosmicdrift/kumiko-types/temporal";
|
|
4
|
+
import { type GeneratedFileContext } from "./files.ts";
|
|
5
|
+
import { type SignerRow } from "./lib.ts";
|
|
6
|
+
import { type SignatureMethod } from "./web/constants.ts";
|
|
7
|
+
export declare function invalidImage(): import("@cosmicdrift/kumiko-types/write-error-info-types").WriteFailure;
|
|
8
|
+
export declare function decodeSignatureImage(imagePngBase64: string): Uint8Array | null;
|
|
9
|
+
export declare function auditValuesOfRequest(): Record<string, string>;
|
|
10
|
+
export type SignatureWrite = {
|
|
11
|
+
readonly method: SignatureMethod;
|
|
12
|
+
readonly imageFileId: string;
|
|
13
|
+
readonly signedAt: Temporal.Instant;
|
|
14
|
+
};
|
|
15
|
+
export declare function signatureChanges(write: SignatureWrite): Record<string, unknown>;
|
|
16
|
+
export declare function storeSignatureImage(ctx: GeneratedFileContext, user: SessionUser, png: Uint8Array): Promise<import("@cosmicdrift/kumiko-types/handlers").WriteResult<import("@cosmicdrift/kumiko-framework/files").CreatedFileRef>>;
|
|
17
|
+
export declare function recordInPersonSignature(ctx: {
|
|
18
|
+
readonly db: TenantDb;
|
|
19
|
+
}, user: SessionUser, signer: SignerRow, write: SignatureWrite): Promise<import("@cosmicdrift/kumiko-types/handlers").WriteResult<import("@cosmicdrift/kumiko-types/hooks").SaveContext>>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { requestContext } from "@cosmicdrift/kumiko-framework/api";
|
|
2
|
+
import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
|
|
3
|
+
import { signerExecutor } from "./entity.js";
|
|
4
|
+
import { storeGeneratedFile } from "./files.js";
|
|
5
|
+
import { versionOf } from "./lib.js";
|
|
6
|
+
import { checkSignaturePng, decodeSignaturePngBase64 } from "./png.js";
|
|
7
|
+
import { SIGNATURE_INVALID_IMAGE_REASON, SIGNATURE_SIGNER_STATUS, } from "./web/constants.js";
|
|
8
|
+
export function invalidImage() {
|
|
9
|
+
return writeFailure(new UnprocessableError(SIGNATURE_INVALID_IMAGE_REASON));
|
|
10
|
+
}
|
|
11
|
+
export function decodeSignatureImage(imagePngBase64) {
|
|
12
|
+
const bytes = decodeSignaturePngBase64(imagePngBase64);
|
|
13
|
+
if (bytes === null)
|
|
14
|
+
return null;
|
|
15
|
+
return checkSignaturePng(bytes).ok ? bytes : null;
|
|
16
|
+
}
|
|
17
|
+
// IP and user agent come from the HTTP request, not from the payload, so a client cannot choose them.
|
|
18
|
+
export function auditValuesOfRequest() {
|
|
19
|
+
const scope = requestContext.get();
|
|
20
|
+
return {
|
|
21
|
+
...(scope?.ip !== undefined && { signedFromIp: scope.ip }),
|
|
22
|
+
...(scope?.userAgent !== undefined && { signedUserAgent: scope.userAgent }),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export function signatureChanges(write) {
|
|
26
|
+
return {
|
|
27
|
+
status: SIGNATURE_SIGNER_STATUS.Signed,
|
|
28
|
+
method: write.method,
|
|
29
|
+
signedAt: write.signedAt,
|
|
30
|
+
imageFileId: write.imageFileId,
|
|
31
|
+
linkAnchor: null,
|
|
32
|
+
...auditValuesOfRequest(),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export async function storeSignatureImage(ctx, user, png) {
|
|
36
|
+
return storeGeneratedFile(ctx, user, {
|
|
37
|
+
fileName: "signature.png",
|
|
38
|
+
mimeType: "image/png",
|
|
39
|
+
data: png,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
// Records the signature of an in-person signer. A concurrent change of the row makes the executor
|
|
43
|
+
// refuse the stale version, so a double submit signs once.
|
|
44
|
+
export function recordInPersonSignature(ctx, user, signer, write) {
|
|
45
|
+
return signerExecutor.update({ id: signer.id, version: versionOf(signer), changes: signatureChanges(write) }, user, ctx.db);
|
|
46
|
+
}
|