@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,93 @@
|
|
|
1
|
+
import { PDFDocument } from "pdf-lib";
|
|
2
|
+
import { SIGNATURE_METHOD, type SignatureMethod } from "./web/constants.ts";
|
|
3
|
+
|
|
4
|
+
export type SignaturePageLabels = {
|
|
5
|
+
readonly heading: string;
|
|
6
|
+
readonly documentHash: string;
|
|
7
|
+
readonly signedAt: string;
|
|
8
|
+
readonly inPerson: string;
|
|
9
|
+
readonly link: string;
|
|
10
|
+
readonly noRole: string;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export const DEFAULT_SIGNATURE_PAGE_LABELS: SignaturePageLabels = {
|
|
14
|
+
heading: "Signature page",
|
|
15
|
+
documentHash: "SHA-256 of the original document",
|
|
16
|
+
signedAt: "Signed",
|
|
17
|
+
inPerson: "In person",
|
|
18
|
+
link: "By link",
|
|
19
|
+
noRole: "",
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type SignaturePageEntry = {
|
|
23
|
+
readonly name: string;
|
|
24
|
+
readonly role: string | null;
|
|
25
|
+
readonly signedAtIso: string;
|
|
26
|
+
readonly method: SignatureMethod;
|
|
27
|
+
readonly imagePng: Uint8Array;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const HTML_ESCAPES: Readonly<Record<string, string>> = {
|
|
31
|
+
"&": "&",
|
|
32
|
+
"<": "<",
|
|
33
|
+
">": ">",
|
|
34
|
+
'"': """,
|
|
35
|
+
"'": "'",
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
// Names and titles are free text typed by users; they reach Chromium as HTML, so every value is escaped.
|
|
39
|
+
export function escapeHtml(value: string): string {
|
|
40
|
+
return value.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function imageDataUri(png: Uint8Array): string {
|
|
44
|
+
return `data:image/png;base64,${Buffer.from(png).toString("base64")}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function entryHtml(entry: SignaturePageEntry, labels: SignaturePageLabels): string {
|
|
48
|
+
const way = entry.method === SIGNATURE_METHOD.InPerson ? labels.inPerson : labels.link;
|
|
49
|
+
const role = entry.role === null ? labels.noRole : entry.role;
|
|
50
|
+
return `<section class="entry">
|
|
51
|
+
<img src="${escapeHtml(imageDataUri(entry.imagePng))}" alt="">
|
|
52
|
+
<div class="meta">
|
|
53
|
+
<strong>${escapeHtml(entry.name)}</strong>
|
|
54
|
+
${role === "" ? "" : `<span>${escapeHtml(role)}</span>`}
|
|
55
|
+
<span>${escapeHtml(labels.signedAt)}: ${escapeHtml(entry.signedAtIso)} (${escapeHtml(way)})</span>
|
|
56
|
+
</div>
|
|
57
|
+
</section>`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function buildSignaturePageHtml(args: {
|
|
61
|
+
readonly title: string;
|
|
62
|
+
readonly documentSha256: string;
|
|
63
|
+
readonly entries: readonly SignaturePageEntry[];
|
|
64
|
+
readonly labels: SignaturePageLabels;
|
|
65
|
+
}): string {
|
|
66
|
+
return `<!doctype html>
|
|
67
|
+
<html><head><meta charset="utf-8"><style>
|
|
68
|
+
body { font-family: sans-serif; font-size: 12px; color: #111; margin: 0; }
|
|
69
|
+
h1 { font-size: 20px; margin: 0 0 4px; }
|
|
70
|
+
h2 { font-size: 14px; font-weight: normal; margin: 0 0 24px; }
|
|
71
|
+
.entry { display: flex; align-items: center; gap: 24px; border-top: 1px solid #ccc; padding: 12px 0; page-break-inside: avoid; }
|
|
72
|
+
.entry img { width: 220px; height: 90px; object-fit: contain; }
|
|
73
|
+
.meta { display: flex; flex-direction: column; gap: 2px; }
|
|
74
|
+
.hash { margin-top: 24px; font-family: monospace; font-size: 10px; word-break: break-all; }
|
|
75
|
+
</style></head><body>
|
|
76
|
+
<h1>${escapeHtml(args.labels.heading)}</h1>
|
|
77
|
+
<h2>${escapeHtml(args.title)}</h2>
|
|
78
|
+
${args.entries.map((entry) => entryHtml(entry, args.labels)).join("\n")}
|
|
79
|
+
<p class="hash">${escapeHtml(args.labels.documentHash)}: ${escapeHtml(args.documentSha256)}</p>
|
|
80
|
+
</body></html>`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// The original pages are copied as they are; the signature pages only get appended.
|
|
84
|
+
export async function appendPdfPages(
|
|
85
|
+
original: Uint8Array,
|
|
86
|
+
appendix: Uint8Array,
|
|
87
|
+
): Promise<Uint8Array> {
|
|
88
|
+
const merged = await PDFDocument.load(original);
|
|
89
|
+
const extra = await PDFDocument.load(appendix);
|
|
90
|
+
const pages = await merged.copyPages(extra, extra.getPageIndices());
|
|
91
|
+
for (const page of pages) merged.addPage(page);
|
|
92
|
+
return merged.save();
|
|
93
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { requestContext } from "@cosmicdrift/kumiko-framework/api";
|
|
2
|
+
import type { TenantDb } from "@cosmicdrift/kumiko-framework/db";
|
|
3
|
+
import type { SessionUser } from "@cosmicdrift/kumiko-framework/engine";
|
|
4
|
+
import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
|
|
5
|
+
import type { Temporal } from "@cosmicdrift/kumiko-types/temporal";
|
|
6
|
+
import { signerExecutor } from "./entity.ts";
|
|
7
|
+
import { type GeneratedFileContext, storeGeneratedFile } from "./files.ts";
|
|
8
|
+
import { type SignerRow, versionOf } from "./lib.ts";
|
|
9
|
+
import { checkSignaturePng, decodeSignaturePngBase64 } from "./png.ts";
|
|
10
|
+
import {
|
|
11
|
+
SIGNATURE_INVALID_IMAGE_REASON,
|
|
12
|
+
SIGNATURE_SIGNER_STATUS,
|
|
13
|
+
type SignatureMethod,
|
|
14
|
+
} from "./web/constants.ts";
|
|
15
|
+
|
|
16
|
+
export function invalidImage() {
|
|
17
|
+
return writeFailure(new UnprocessableError(SIGNATURE_INVALID_IMAGE_REASON));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function decodeSignatureImage(imagePngBase64: string): Uint8Array | null {
|
|
21
|
+
const bytes = decodeSignaturePngBase64(imagePngBase64);
|
|
22
|
+
if (bytes === null) return null;
|
|
23
|
+
return checkSignaturePng(bytes).ok ? bytes : null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// IP and user agent come from the HTTP request, not from the payload, so a client cannot choose them.
|
|
27
|
+
export function auditValuesOfRequest(): Record<string, string> {
|
|
28
|
+
const scope = requestContext.get();
|
|
29
|
+
return {
|
|
30
|
+
...(scope?.ip !== undefined && { signedFromIp: scope.ip }),
|
|
31
|
+
...(scope?.userAgent !== undefined && { signedUserAgent: scope.userAgent }),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type SignatureWrite = {
|
|
36
|
+
readonly method: SignatureMethod;
|
|
37
|
+
readonly imageFileId: string;
|
|
38
|
+
readonly signedAt: Temporal.Instant;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export function signatureChanges(write: SignatureWrite): Record<string, unknown> {
|
|
42
|
+
return {
|
|
43
|
+
status: SIGNATURE_SIGNER_STATUS.Signed,
|
|
44
|
+
method: write.method,
|
|
45
|
+
signedAt: write.signedAt,
|
|
46
|
+
imageFileId: write.imageFileId,
|
|
47
|
+
linkAnchor: null,
|
|
48
|
+
...auditValuesOfRequest(),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function storeSignatureImage(
|
|
53
|
+
ctx: GeneratedFileContext,
|
|
54
|
+
user: SessionUser,
|
|
55
|
+
png: Uint8Array,
|
|
56
|
+
) {
|
|
57
|
+
return storeGeneratedFile(ctx, user, {
|
|
58
|
+
fileName: "signature.png",
|
|
59
|
+
mimeType: "image/png",
|
|
60
|
+
data: png,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Records the signature of an in-person signer. A concurrent change of the row makes the executor
|
|
65
|
+
// refuse the stale version, so a double submit signs once.
|
|
66
|
+
export function recordInPersonSignature(
|
|
67
|
+
ctx: { readonly db: TenantDb },
|
|
68
|
+
user: SessionUser,
|
|
69
|
+
signer: SignerRow,
|
|
70
|
+
write: SignatureWrite,
|
|
71
|
+
) {
|
|
72
|
+
return signerExecutor.update(
|
|
73
|
+
{ id: signer.id, version: versionOf(signer), changes: signatureChanges(write) },
|
|
74
|
+
user,
|
|
75
|
+
ctx.db,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// DOM-free signing page for static sites: fetch, canvas and Pointer Events only, no React. The link
|
|
2
|
+
// a signer receives carries the token in the URL fragment (`#token=`), which browsers never send to a
|
|
3
|
+
// server or in a Referer.
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
dispatchWrite,
|
|
7
|
+
type StaticRequestOptions,
|
|
8
|
+
type StaticResult,
|
|
9
|
+
staticFailure,
|
|
10
|
+
staticSuccess,
|
|
11
|
+
takeUrlToken,
|
|
12
|
+
} from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
|
|
13
|
+
import { SIGNATURE_INVALID_LINK_REASON, SignatureHandlers } from "./web/constants.ts";
|
|
14
|
+
|
|
15
|
+
export {
|
|
16
|
+
hrefWithoutUrlToken,
|
|
17
|
+
readUrlToken,
|
|
18
|
+
STATIC_NETWORK_REASON,
|
|
19
|
+
STATIC_RATE_LIMITED_REASON,
|
|
20
|
+
type StaticFailure,
|
|
21
|
+
type StaticRequestOptions,
|
|
22
|
+
type StaticResult,
|
|
23
|
+
type StaticSuccess,
|
|
24
|
+
} from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
|
|
25
|
+
export {
|
|
26
|
+
bytesToBase64,
|
|
27
|
+
createSignaturePad,
|
|
28
|
+
type SignaturePad,
|
|
29
|
+
type SignaturePadCanvas,
|
|
30
|
+
type SignaturePadOptions,
|
|
31
|
+
} from "./web/pad.ts";
|
|
32
|
+
export { SIGNATURE_INVALID_LINK_REASON };
|
|
33
|
+
|
|
34
|
+
export type SignatureLinkView = {
|
|
35
|
+
readonly title: string;
|
|
36
|
+
readonly signerName: string;
|
|
37
|
+
readonly role: string | null;
|
|
38
|
+
/** Short-lived URL of the PDF; null when the storage provider cannot sign URLs. */
|
|
39
|
+
readonly documentUrl: string | null;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** Reads `#token=` from the current page and removes it from the address bar. Browser only. */
|
|
43
|
+
export function takeSignatureToken(): string {
|
|
44
|
+
return takeUrlToken("fragment");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
48
|
+
return typeof value === "object" && value !== null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function parseLinkView(data: unknown): SignatureLinkView | null {
|
|
52
|
+
if (!isRecord(data)) return null;
|
|
53
|
+
const { title, signerName, role, documentUrl } = data;
|
|
54
|
+
if (typeof title !== "string" || typeof signerName !== "string") return null;
|
|
55
|
+
return {
|
|
56
|
+
title,
|
|
57
|
+
signerName,
|
|
58
|
+
role: typeof role === "string" ? role : null,
|
|
59
|
+
documentUrl: typeof documentUrl === "string" ? documentUrl : null,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Counts a view but does not use up the link. A bad, used or expired link fails with `invalid_or_expired_link`. */
|
|
64
|
+
export async function openSignatureLink(
|
|
65
|
+
token: string,
|
|
66
|
+
options?: StaticRequestOptions,
|
|
67
|
+
): Promise<StaticResult<SignatureLinkView>> {
|
|
68
|
+
const result = await dispatchWrite(SignatureHandlers.openByLink, { token }, options);
|
|
69
|
+
if (result.kind !== "success") return result;
|
|
70
|
+
const view = parseLinkView(result.data);
|
|
71
|
+
return view === null ? staticFailure("unknown") : staticSuccess(view);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** `imagePngBase64` comes from `SignaturePad.toPngBase64()`. Uses up the link on success. */
|
|
75
|
+
export async function signByLink(
|
|
76
|
+
token: string,
|
|
77
|
+
imagePngBase64: string,
|
|
78
|
+
options?: StaticRequestOptions,
|
|
79
|
+
): Promise<StaticResult<undefined>> {
|
|
80
|
+
const result = await dispatchWrite(
|
|
81
|
+
SignatureHandlers.signByLink,
|
|
82
|
+
{ token, imagePngBase64 },
|
|
83
|
+
options,
|
|
84
|
+
);
|
|
85
|
+
return result.kind === "success" ? staticSuccess(undefined) : result;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function declineByLink(
|
|
89
|
+
token: string,
|
|
90
|
+
reason?: string,
|
|
91
|
+
options?: StaticRequestOptions,
|
|
92
|
+
): Promise<StaticResult<undefined>> {
|
|
93
|
+
const result = await dispatchWrite(
|
|
94
|
+
SignatureHandlers.declineByLink,
|
|
95
|
+
{ token, ...(reason !== undefined && reason !== "" && { reason }) },
|
|
96
|
+
options,
|
|
97
|
+
);
|
|
98
|
+
return result.kind === "success" ? staticSuccess(undefined) : result;
|
|
99
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_LIST_LIMIT,
|
|
3
|
+
entityListSchema,
|
|
4
|
+
type HandlerContext,
|
|
5
|
+
MAX_LIST_LIMIT,
|
|
6
|
+
type QueryHandlerDef,
|
|
7
|
+
type SessionUser,
|
|
8
|
+
} from "@cosmicdrift/kumiko-framework/engine";
|
|
9
|
+
import { AccessDeniedError } from "@cosmicdrift/kumiko-framework/errors";
|
|
10
|
+
import { requestExecutor } from "./entity.ts";
|
|
11
|
+
import type { SubjectScope } from "./subject-scope.ts";
|
|
12
|
+
|
|
13
|
+
type ListPayload = ReturnType<typeof entityListSchema.parse>;
|
|
14
|
+
type ListFilter = NonNullable<ListPayload["filter"]>;
|
|
15
|
+
|
|
16
|
+
function allFilters(payload: ListPayload): readonly ListFilter[] {
|
|
17
|
+
return [...(payload.filter === undefined ? [] : [payload.filter]), ...(payload.filters ?? [])];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function emptyPage(payload: ListPayload) {
|
|
21
|
+
return { rows: [], nextCursor: null, ...(payload.totalCount === true && { total: 0 }) };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function onlyFilterOn(payload: ListPayload, field: string): ListFilter | null {
|
|
25
|
+
const matching = allFilters(payload).filter((filter) => filter.field === field);
|
|
26
|
+
const [first] = matching;
|
|
27
|
+
return matching.length === 1 && first !== undefined ? first : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
type RowsPage = { rows: unknown[] } & Record<string, unknown>;
|
|
31
|
+
|
|
32
|
+
function isRowsPage(value: unknown): value is RowsPage {
|
|
33
|
+
return (
|
|
34
|
+
typeof value === "object" && value !== null && "rows" in value && Array.isArray(value.rows)
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function subjectKey(subject: { subjectType?: unknown; subjectId?: unknown }): string {
|
|
39
|
+
return `${String(subject.subjectType)}\u0000${String(subject.subjectId)}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ponytail: at most this many base pages per answer; a user who may see almost none of the
|
|
43
|
+
// tenant's requests gets short pages and scrolls on. Upgrade to a subject-joined query if that hurts.
|
|
44
|
+
const MAX_BASE_PAGES_PER_ANSWER = 10;
|
|
45
|
+
// authorizeSubject usually queries the database; a page of 200 subjects must not take the whole pool.
|
|
46
|
+
const SUBJECT_CHECKS_IN_PARALLEL = 10;
|
|
47
|
+
|
|
48
|
+
export function scopeRequestList(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef {
|
|
49
|
+
return {
|
|
50
|
+
...base,
|
|
51
|
+
handler: async (query, ctx) => {
|
|
52
|
+
const user = query.user;
|
|
53
|
+
if (!scope.isScoped(user)) return base.handler(query, ctx);
|
|
54
|
+
const payload = entityListSchema.parse(query.payload);
|
|
55
|
+
// Group counts would include requests of foreign subjects, and an offset counts base rows,
|
|
56
|
+
// not the rows this user sees; the screen pages by cursor.
|
|
57
|
+
if (payload.aggregate !== undefined || (payload.offset ?? 0) > 0) {
|
|
58
|
+
throw new AccessDeniedError();
|
|
59
|
+
}
|
|
60
|
+
const limit = payload.limit ?? DEFAULT_LIST_LIMIT;
|
|
61
|
+
const verdicts = new Map<string, boolean>();
|
|
62
|
+
const visibleRows: unknown[] = [];
|
|
63
|
+
let page: unknown = await base.handler(query, ctx);
|
|
64
|
+
for (let fetched = 1; ; fetched++) {
|
|
65
|
+
if (!isRowsPage(page)) throw new Error("signature request list did not return a rows page");
|
|
66
|
+
const unknownSubjects = new Map(
|
|
67
|
+
page.rows
|
|
68
|
+
.map((row) => [subjectKey(subjectOf(row)), subjectOf(row)] as const)
|
|
69
|
+
.filter(([key]) => !verdicts.has(key)),
|
|
70
|
+
);
|
|
71
|
+
const pending = [...unknownSubjects];
|
|
72
|
+
for (let start = 0; start < pending.length; start += SUBJECT_CHECKS_IN_PARALLEL) {
|
|
73
|
+
await Promise.all(
|
|
74
|
+
pending.slice(start, start + SUBJECT_CHECKS_IN_PARALLEL).map(async ([key, subject]) => {
|
|
75
|
+
verdicts.set(key, await scope.allowsRequest(ctx, user, subject));
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
visibleRows.push(...page.rows.filter((row) => verdicts.get(subjectKey(subjectOf(row)))));
|
|
80
|
+
const nextCursor = page["nextCursor"];
|
|
81
|
+
if (
|
|
82
|
+
visibleRows.length >= limit ||
|
|
83
|
+
typeof nextCursor !== "string" ||
|
|
84
|
+
fetched >= MAX_BASE_PAGES_PER_ANSWER ||
|
|
85
|
+
verdicts.size >= MAX_LIST_LIMIT
|
|
86
|
+
) {
|
|
87
|
+
// `total` would count requests of foreign subjects; the cursor continues after the last base page.
|
|
88
|
+
const { total: _total, rows: _rows, ...rest } = page;
|
|
89
|
+
return { ...rest, rows: visibleRows };
|
|
90
|
+
}
|
|
91
|
+
page = await base.handler(
|
|
92
|
+
{
|
|
93
|
+
...query,
|
|
94
|
+
payload: { ...payload, cursor: nextCursor, limit: limit - visibleRows.length },
|
|
95
|
+
},
|
|
96
|
+
ctx,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function scopeRequestDetail(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef {
|
|
104
|
+
return {
|
|
105
|
+
...base,
|
|
106
|
+
handler: async (query, ctx) => {
|
|
107
|
+
const row = await base.handler(query, ctx);
|
|
108
|
+
if (row === null || !scope.isScoped(query.user)) return row;
|
|
109
|
+
return (await scope.allowsRequest(ctx, query.user, subjectOf(row))) ? row : null;
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function subjectOf(row: unknown): { subjectType?: unknown; subjectId?: unknown } {
|
|
115
|
+
if (typeof row !== "object" || row === null) return {};
|
|
116
|
+
return {
|
|
117
|
+
subjectType: "subjectType" in row ? row.subjectType : undefined,
|
|
118
|
+
subjectId: "subjectId" in row ? row.subjectId : undefined,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function scopeSignerList(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef {
|
|
123
|
+
return {
|
|
124
|
+
...base,
|
|
125
|
+
handler: async (query, ctx: HandlerContext) => {
|
|
126
|
+
const user: SessionUser = query.user;
|
|
127
|
+
if (!scope.isScoped(user)) return base.handler(query, ctx);
|
|
128
|
+
const payload = entityListSchema.parse(query.payload);
|
|
129
|
+
const requestFilter = onlyFilterOn(payload, "requestId");
|
|
130
|
+
if (
|
|
131
|
+
requestFilter === null ||
|
|
132
|
+
requestFilter.op !== "eq" ||
|
|
133
|
+
typeof requestFilter.value !== "string"
|
|
134
|
+
) {
|
|
135
|
+
throw new AccessDeniedError();
|
|
136
|
+
}
|
|
137
|
+
const request = await requestExecutor.detail({ id: requestFilter.value }, user, ctx.db);
|
|
138
|
+
if (request === null || !(await scope.allowsRequest(ctx, user, request))) {
|
|
139
|
+
return emptyPage(payload);
|
|
140
|
+
}
|
|
141
|
+
return base.handler(query, ctx);
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { HandlerContext, SessionUser } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import type { SignatureOptions } from "./options.ts";
|
|
3
|
+
|
|
4
|
+
export type SubjectScope = {
|
|
5
|
+
isScoped(user: SessionUser): boolean;
|
|
6
|
+
allows(
|
|
7
|
+
ctx: HandlerContext,
|
|
8
|
+
user: SessionUser,
|
|
9
|
+
subjectType: unknown,
|
|
10
|
+
subjectId: unknown,
|
|
11
|
+
): Promise<boolean>;
|
|
12
|
+
allowsRequest(
|
|
13
|
+
ctx: HandlerContext,
|
|
14
|
+
user: SessionUser,
|
|
15
|
+
request: { readonly subjectType?: unknown; readonly subjectId?: unknown },
|
|
16
|
+
): Promise<boolean>;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
function isNonEmptyString(value: unknown): value is string {
|
|
20
|
+
return typeof value === "string" && value !== "";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function createSubjectScope(
|
|
24
|
+
opts: Pick<SignatureOptions, "authorizeSubject" | "unscopedRoles">,
|
|
25
|
+
): SubjectScope {
|
|
26
|
+
const { authorizeSubject } = opts;
|
|
27
|
+
const unscopedRoles = opts.unscopedRoles ?? [];
|
|
28
|
+
const isScoped = (user: SessionUser): boolean =>
|
|
29
|
+
authorizeSubject !== undefined && !user.roles.some((role) => unscopedRoles.includes(role));
|
|
30
|
+
|
|
31
|
+
const allows: SubjectScope["allows"] = async (ctx, user, subjectType, subjectId) => {
|
|
32
|
+
if (authorizeSubject === undefined || !isScoped(user)) return true;
|
|
33
|
+
if (!isNonEmptyString(subjectType) || !isNonEmptyString(subjectId)) return false;
|
|
34
|
+
return authorizeSubject(ctx, user, { subjectType, subjectId });
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
isScoped,
|
|
39
|
+
allows,
|
|
40
|
+
allowsRequest: (ctx, user, request) =>
|
|
41
|
+
allows(ctx, user, request.subjectType, request.subjectId),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import type { JobContext } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
|
|
3
|
+
import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
|
|
4
|
+
import { requestExecutor } from "./entity.ts";
|
|
5
|
+
import {
|
|
6
|
+
discardGeneratedFile,
|
|
7
|
+
PDF_MIME_TYPE,
|
|
8
|
+
readTenantFile,
|
|
9
|
+
sha256Hex,
|
|
10
|
+
storeGeneratedFile,
|
|
11
|
+
} from "./files.ts";
|
|
12
|
+
import {
|
|
13
|
+
instantOrNull,
|
|
14
|
+
isPastInstant,
|
|
15
|
+
listSigners,
|
|
16
|
+
type RequestRow,
|
|
17
|
+
type SignerRow,
|
|
18
|
+
} from "./lib.ts";
|
|
19
|
+
import type { SignatureOptions } from "./options.ts";
|
|
20
|
+
import {
|
|
21
|
+
appendPdfPages,
|
|
22
|
+
buildSignaturePageHtml,
|
|
23
|
+
DEFAULT_SIGNATURE_PAGE_LABELS,
|
|
24
|
+
type SignaturePageEntry,
|
|
25
|
+
} from "./signature-page.ts";
|
|
26
|
+
import {
|
|
27
|
+
SIGNATURE_METHOD,
|
|
28
|
+
SIGNATURE_REQUEST_STATUS,
|
|
29
|
+
SignatureInternalHandlers,
|
|
30
|
+
} from "./web/constants.ts";
|
|
31
|
+
|
|
32
|
+
// Equals the executor's MAX_LIST_LIMIT.
|
|
33
|
+
const SWEEP_PAGE_SIZE = 200;
|
|
34
|
+
|
|
35
|
+
type RequestPage = Awaited<ReturnType<typeof requestExecutor.list>>;
|
|
36
|
+
|
|
37
|
+
// Keyset-paged, so rows that leave the status while the sweep works on them cannot shift the next page.
|
|
38
|
+
async function forEachRequestWithStatus(
|
|
39
|
+
ctx: JobContext,
|
|
40
|
+
status: string,
|
|
41
|
+
visit: (request: RequestRow) => Promise<void>,
|
|
42
|
+
): Promise<void> {
|
|
43
|
+
let cursor: string | null = null;
|
|
44
|
+
do {
|
|
45
|
+
const page: RequestPage = await requestExecutor.list(
|
|
46
|
+
{
|
|
47
|
+
filter: { field: "status", op: "eq", value: status },
|
|
48
|
+
limit: SWEEP_PAGE_SIZE,
|
|
49
|
+
...(cursor !== null && { cursor }),
|
|
50
|
+
},
|
|
51
|
+
ctx.systemUser,
|
|
52
|
+
ctx.db,
|
|
53
|
+
);
|
|
54
|
+
for (const request of page.rows) await visit(request);
|
|
55
|
+
cursor = page.nextCursor;
|
|
56
|
+
} while (cursor !== null);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function bySignedAt(left: SignerRow, right: SignerRow): number {
|
|
60
|
+
const a = instantOrNull(left.signedAt);
|
|
61
|
+
const b = instantOrNull(right.signedAt);
|
|
62
|
+
if (a === null || b === null) return 0;
|
|
63
|
+
return Temporal.Instant.compare(a, b);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function signaturePageEntries(
|
|
67
|
+
ctx: JobContext,
|
|
68
|
+
signers: readonly SignerRow[],
|
|
69
|
+
): Promise<readonly SignaturePageEntry[] | null> {
|
|
70
|
+
const entries: SignaturePageEntry[] = [];
|
|
71
|
+
for (const signer of [...signers].sort(bySignedAt)) {
|
|
72
|
+
const signedAt = instantOrNull(signer.signedAt);
|
|
73
|
+
if (signedAt === null || typeof signer.imageFileId !== "string") return null;
|
|
74
|
+
const image = await readTenantFile(ctx, ctx.systemUser.tenantId, signer.imageFileId);
|
|
75
|
+
if (image === null) return null;
|
|
76
|
+
entries.push({
|
|
77
|
+
name: signer.name,
|
|
78
|
+
role: signer.role ?? null,
|
|
79
|
+
signedAtIso: signedAt.toString(),
|
|
80
|
+
method:
|
|
81
|
+
signer.method === SIGNATURE_METHOD.Link ? SIGNATURE_METHOD.Link : SIGNATURE_METHOD.InPerson,
|
|
82
|
+
imagePng: image.content,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
return entries;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Appends the signature page to the unchanged original. A renderer outage throws, the request
|
|
89
|
+
// stays all-signed and the next run tries again.
|
|
90
|
+
async function finalizeRequest(
|
|
91
|
+
ctx: JobContext,
|
|
92
|
+
opts: SignatureOptions,
|
|
93
|
+
request: RequestRow,
|
|
94
|
+
): Promise<void> {
|
|
95
|
+
const original = await readTenantFile(ctx, ctx.systemUser.tenantId, request.documentFileId);
|
|
96
|
+
if (original === null || sha256Hex(original.content) !== request.documentSha256) {
|
|
97
|
+
ctx.obs.log.warn("[signature:sweep] original document missing or changed, not completing", {
|
|
98
|
+
requestId: request.id,
|
|
99
|
+
});
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const entries = await signaturePageEntries(
|
|
103
|
+
ctx,
|
|
104
|
+
await listSigners(ctx, ctx.systemUser, request.id),
|
|
105
|
+
);
|
|
106
|
+
if (entries === null) {
|
|
107
|
+
ctx.obs.log.warn("[signature:sweep] signature image missing, not completing", {
|
|
108
|
+
requestId: request.id,
|
|
109
|
+
});
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const html = buildSignaturePageHtml({
|
|
113
|
+
title: request.title,
|
|
114
|
+
documentSha256: request.documentSha256,
|
|
115
|
+
entries,
|
|
116
|
+
labels: DEFAULT_SIGNATURE_PAGE_LABELS,
|
|
117
|
+
});
|
|
118
|
+
const signaturePages = await opts.renderHtmlToPdf(html);
|
|
119
|
+
const completed = await appendPdfPages(original.content, signaturePages);
|
|
120
|
+
const stored = await storeGeneratedFile(ctx, ctx.systemUser, {
|
|
121
|
+
fileName: "signed-document.pdf",
|
|
122
|
+
mimeType: PDF_MIME_TYPE,
|
|
123
|
+
data: completed,
|
|
124
|
+
});
|
|
125
|
+
if (!stored.isSuccess) {
|
|
126
|
+
ctx.obs.log.warn("[signature:sweep] storing the completed pdf failed", {
|
|
127
|
+
requestId: request.id,
|
|
128
|
+
});
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const finished = await ctx.dispatch.write(SignatureInternalHandlers.finish, {
|
|
132
|
+
requestId: request.id,
|
|
133
|
+
completedFileId: stored.data.id,
|
|
134
|
+
});
|
|
135
|
+
if (!finished.isSuccess || propertyOf(finished.data, "finished") !== true) {
|
|
136
|
+
await discardGeneratedFile(ctx, ctx.systemUser, stored.data);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function sweepSignatureRequests(
|
|
141
|
+
ctx: JobContext,
|
|
142
|
+
opts: SignatureOptions,
|
|
143
|
+
): Promise<void> {
|
|
144
|
+
const now = ctx.tz.now();
|
|
145
|
+
await forEachRequestWithStatus(ctx, SIGNATURE_REQUEST_STATUS.Open, async (request) => {
|
|
146
|
+
const qn = isPastInstant(request.expiresAt, now)
|
|
147
|
+
? SignatureInternalHandlers.expire
|
|
148
|
+
: SignatureInternalHandlers.reconcile;
|
|
149
|
+
await ctx.dispatch.write(qn, { requestId: request.id });
|
|
150
|
+
});
|
|
151
|
+
await forEachRequestWithStatus(ctx, SIGNATURE_REQUEST_STATUS.AllSigned, async (request) => {
|
|
152
|
+
try {
|
|
153
|
+
await finalizeRequest(ctx, opts, request);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
ctx.obs.log.warn("[signature:sweep] completing failed, retrying on the next run", {
|
|
156
|
+
requestId: request.id,
|
|
157
|
+
error: error instanceof Error ? error.message : String(error),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
}
|