@cosmicdrift/kumiko-samples 0.415.0 → 0.417.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/channel-whatsapp/changes.json +6 -0
- package/packages/bundled-features/src/channel-whatsapp/constants.ts +1 -0
- package/packages/bundled-features/src/channel-whatsapp/graph-client.ts +37 -1
- 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/screens.ts +5 -1
- package/packages/bundled-features/src/signature/README.md +66 -0
- package/packages/bundled-features/src/signature/changes.json +22 -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 +48 -0
- package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +77 -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 +120 -0
- package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +37 -0
- package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +73 -0
- package/packages/bundled-features/src/signature/i18n.ts +52 -0
- package/packages/bundled-features/src/signature/index.ts +35 -0
- package/packages/bundled-features/src/signature/lib.ts +125 -0
- package/packages/bundled-features/src/signature/options.ts +64 -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 +117 -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 +99 -0
- package/packages/bundled-features/src/signature/subject-queries.ts +144 -0
- package/packages/bundled-features/src/signature/subject-scope.ts +43 -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/subscription-stripe/changes.json +6 -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/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/dashboard-stats/README.md +4 -0
- package/samples/recipes/dashboard-stats/src/feature.ts +47 -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/event-sourcing/src/feature.ts +31 -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/list-table-options/README.md +9 -0
- package/samples/recipes/list-table-options/src/feature.ts +47 -2
- package/samples/recipes/managed-config/src/feature.ts +9 -1
- package/samples/recipes/record-detail-layout/README.md +7 -0
- package/samples/recipes/record-detail-layout/src/feature.ts +40 -2
- package/samples/recipes/record-detail-layout/src/order-board.ts +1 -0
- package/samples/recipes/secrets-demo/README.md +1 -1
- package/samples/recipes/secrets-demo/src/feature.ts +2 -0
- 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
- package/samples/recipes/writeform-section/README.md +4 -0
- package/samples/recipes/writeform-section/src/feature.ts +97 -0
|
@@ -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,35 @@
|
|
|
1
|
+
export type { SignatureRetention } from "./entity.ts";
|
|
2
|
+
export { createSignatureFeature } from "./feature.ts";
|
|
3
|
+
export type {
|
|
4
|
+
AuthorizeSignatureSubject,
|
|
5
|
+
DeliverSignatureLink,
|
|
6
|
+
RenderSignatureHtmlToPdf,
|
|
7
|
+
SignatureLinkDelivery,
|
|
8
|
+
SignatureOptions,
|
|
9
|
+
SignatureSubject,
|
|
10
|
+
} from "./options.ts";
|
|
11
|
+
export type { SignaturePageLabels } from "./signature-page.ts";
|
|
12
|
+
export {
|
|
13
|
+
SIGNATURE_DEFAULT_VALIDITY_DAYS,
|
|
14
|
+
SIGNATURE_EVENT_SHORT,
|
|
15
|
+
SIGNATURE_FEATURE,
|
|
16
|
+
SIGNATURE_INVALID_IMAGE_REASON,
|
|
17
|
+
SIGNATURE_INVALID_LINK_REASON,
|
|
18
|
+
SIGNATURE_LEVEL,
|
|
19
|
+
SIGNATURE_LINK_TTL_DAYS,
|
|
20
|
+
SIGNATURE_MAX_LINK_OPENS,
|
|
21
|
+
SIGNATURE_METHOD,
|
|
22
|
+
SIGNATURE_REQUEST_ENTITY,
|
|
23
|
+
SIGNATURE_REQUEST_STATUS,
|
|
24
|
+
SIGNATURE_SIGNER_ENTITY,
|
|
25
|
+
SIGNATURE_SIGNER_STATUS,
|
|
26
|
+
SignatureEvents,
|
|
27
|
+
SignatureHandlers,
|
|
28
|
+
SignatureInternalHandlers,
|
|
29
|
+
SignatureJobs,
|
|
30
|
+
type SignatureLevel,
|
|
31
|
+
type SignatureMethod,
|
|
32
|
+
SignatureQueries,
|
|
33
|
+
type SignatureRequestStatus,
|
|
34
|
+
type SignatureSignerStatus,
|
|
35
|
+
} 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,64 @@
|
|
|
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 SignatureSubject = {
|
|
31
|
+
readonly subjectType: string;
|
|
32
|
+
readonly subjectId: string;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export type AuthorizeSignatureSubject = (
|
|
36
|
+
ctx: HandlerContext,
|
|
37
|
+
user: SessionUser,
|
|
38
|
+
subject: SignatureSubject,
|
|
39
|
+
) => Promise<boolean>;
|
|
40
|
+
|
|
41
|
+
export type SignatureOptions = {
|
|
42
|
+
/** How long requests and signers are kept, data-retention keepFor syntax, counted from creation. */
|
|
43
|
+
readonly retention: SignatureRetention;
|
|
44
|
+
/** Renders the signature page (HTML) to a PDF. An outage leaves the request at `all-signed` and the sweep job retries. */
|
|
45
|
+
readonly renderHtmlToPdf: RenderSignatureHtmlToPdf;
|
|
46
|
+
/** HMAC secret of the signing links. Without it every link is rejected. */
|
|
47
|
+
readonly linkSecret: string;
|
|
48
|
+
/** Sends a freshly issued link to the signer, e.g. by mail. A throw fails issue-link and leaves no link sent. */
|
|
49
|
+
readonly deliverLink: DeliverSignatureLink;
|
|
50
|
+
/** URL of the app's signature page; the token is appended as `#<token>`. */
|
|
51
|
+
readonly signaturePageUrl: string;
|
|
52
|
+
/** 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. */
|
|
53
|
+
readonly access?: AccessRule;
|
|
54
|
+
/** 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. */
|
|
55
|
+
readonly authorizeSubject?: AuthorizeSignatureSubject;
|
|
56
|
+
/** Roles that skip `authorizeSubject`, e.g. admins. */
|
|
57
|
+
readonly unscopedRoles?: readonly string[];
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export const LINK_RATE_LIMIT: RateLimitDeclaration = {
|
|
61
|
+
per: "ip+handler",
|
|
62
|
+
limit: 30,
|
|
63
|
+
windowSeconds: 60,
|
|
64
|
+
};
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type EntityListScreenDefinition,
|
|
3
|
+
i18nKey,
|
|
4
|
+
type ProjectionDetailScreenDefinition,
|
|
5
|
+
} from "@cosmicdrift/kumiko-framework/engine";
|
|
6
|
+
import {
|
|
7
|
+
SIGNATURE_REQUEST_ENTITY,
|
|
8
|
+
SIGNATURE_REQUEST_STATUS,
|
|
9
|
+
SIGNATURE_SIGNER_ENTITY,
|
|
10
|
+
SIGNATURE_SIGNER_STATUS,
|
|
11
|
+
SignatureHandlers,
|
|
12
|
+
SignatureQueries,
|
|
13
|
+
} from "./web/constants.ts";
|
|
14
|
+
|
|
15
|
+
const REQUEST = `signature:entity:${SIGNATURE_REQUEST_ENTITY}:field`;
|
|
16
|
+
|
|
17
|
+
const UNSIGNED_SIGNER = {
|
|
18
|
+
field: "status",
|
|
19
|
+
in: [SIGNATURE_SIGNER_STATUS.Pending, SIGNATURE_SIGNER_STATUS.Viewed],
|
|
20
|
+
} as const;
|
|
21
|
+
|
|
22
|
+
const CANCEL_ACTION = {
|
|
23
|
+
id: "cancel",
|
|
24
|
+
label: i18nKey("signature.action.cancel"),
|
|
25
|
+
handler: SignatureHandlers.cancel,
|
|
26
|
+
payload: { map: { requestId: "id" } },
|
|
27
|
+
confirm: i18nKey("signature.action.cancel.confirm"),
|
|
28
|
+
style: "danger",
|
|
29
|
+
visible: { field: "status", eq: SIGNATURE_REQUEST_STATUS.Open },
|
|
30
|
+
} as const;
|
|
31
|
+
|
|
32
|
+
export function createSignatureListScreen(
|
|
33
|
+
access: EntityListScreenDefinition["access"],
|
|
34
|
+
): EntityListScreenDefinition {
|
|
35
|
+
return {
|
|
36
|
+
id: "signature-list",
|
|
37
|
+
type: "entityList",
|
|
38
|
+
entity: SIGNATURE_REQUEST_ENTITY,
|
|
39
|
+
columns: [
|
|
40
|
+
"title",
|
|
41
|
+
"status",
|
|
42
|
+
"subjectType",
|
|
43
|
+
{ field: "expiresAt", hideOnNarrow: true },
|
|
44
|
+
{ field: "completedAt", hideOnNarrow: true },
|
|
45
|
+
],
|
|
46
|
+
defaultSort: { field: "expiresAt", dir: "desc" },
|
|
47
|
+
// A user bound by authorizeSubject gets no total, so the list pages by cursor.
|
|
48
|
+
pagination: "infinite",
|
|
49
|
+
access,
|
|
50
|
+
searchable: true,
|
|
51
|
+
rowActions: [
|
|
52
|
+
{
|
|
53
|
+
kind: "navigate",
|
|
54
|
+
id: "open",
|
|
55
|
+
label: i18nKey("signature.action.open"),
|
|
56
|
+
screen: "signature-detail",
|
|
57
|
+
entityId: "id",
|
|
58
|
+
rowClick: true,
|
|
59
|
+
},
|
|
60
|
+
CANCEL_ACTION,
|
|
61
|
+
],
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Signing in person needs the drawing pad, which a declarative screen cannot host: the app mounts
|
|
66
|
+
// SignaturePad on its own screen and calls sign-in-person.
|
|
67
|
+
export function createSignatureDetailScreen(
|
|
68
|
+
access: ProjectionDetailScreenDefinition["access"],
|
|
69
|
+
): ProjectionDetailScreenDefinition {
|
|
70
|
+
return {
|
|
71
|
+
id: "signature-detail",
|
|
72
|
+
type: "projectionDetail",
|
|
73
|
+
dormant: true,
|
|
74
|
+
listScreenId: "signature-list",
|
|
75
|
+
query: SignatureQueries.detail,
|
|
76
|
+
access,
|
|
77
|
+
header: { title: "title", status: "status" },
|
|
78
|
+
fieldLabels: {
|
|
79
|
+
status: i18nKey(`${REQUEST}:status`),
|
|
80
|
+
subjectType: i18nKey(`${REQUEST}:subjectType`),
|
|
81
|
+
expiresAt: i18nKey(`${REQUEST}:expiresAt`),
|
|
82
|
+
completedAt: i18nKey(`${REQUEST}:completedAt`),
|
|
83
|
+
},
|
|
84
|
+
actions: [CANCEL_ACTION],
|
|
85
|
+
layout: {
|
|
86
|
+
sections: [
|
|
87
|
+
{ fields: ["status", "subjectType", "expiresAt", "completedAt"] },
|
|
88
|
+
{
|
|
89
|
+
kind: "relatedList",
|
|
90
|
+
title: i18nKey("signature.signers.title"),
|
|
91
|
+
query: SignatureQueries.signerList,
|
|
92
|
+
parentFilter: { field: "requestId" },
|
|
93
|
+
entity: SIGNATURE_SIGNER_ENTITY,
|
|
94
|
+
columns: ["name", "role", "status", "method", { field: "signedAt", hideOnNarrow: true }],
|
|
95
|
+
rowActions: [
|
|
96
|
+
{
|
|
97
|
+
id: "issue-link",
|
|
98
|
+
label: i18nKey("signature.action.issueLink"),
|
|
99
|
+
handler: SignatureHandlers.issueLink,
|
|
100
|
+
payload: { map: { signerId: "id" } },
|
|
101
|
+
visible: UNSIGNED_SIGNER,
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
id: "revoke-link",
|
|
105
|
+
label: i18nKey("signature.action.revokeLink"),
|
|
106
|
+
handler: SignatureHandlers.revokeLink,
|
|
107
|
+
payload: { map: { signerId: "id" } },
|
|
108
|
+
confirm: i18nKey("signature.action.revokeLink.confirm"),
|
|
109
|
+
style: "danger",
|
|
110
|
+
visible: UNSIGNED_SIGNER,
|
|
111
|
+
},
|
|
112
|
+
],
|
|
113
|
+
},
|
|
114
|
+
],
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|