@cosmicdrift/kumiko-samples 0.416.0 → 0.418.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +1 -1
  3. package/packages/bundled-features/src/agent-tools/api-docs/schema-fields.ts +14 -0
  4. package/packages/bundled-features/src/agent-tools/changes.json +6 -0
  5. package/packages/bundled-features/src/auth-email-password/index.ts +1 -1
  6. package/packages/bundled-features/src/auth-email-password/signup-activation.ts +2 -5
  7. package/packages/bundled-features/src/auth-email-password/signup-token-store.ts +0 -6
  8. package/packages/bundled-features/src/cap-counter/changes.json +6 -0
  9. package/packages/bundled-features/src/cap-counter/stock-cap-guard.ts +46 -13
  10. package/packages/bundled-features/src/channel-whatsapp/changes.json +1 -1
  11. package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
  12. package/packages/bundled-features/src/document-ingest-foundation/feature.ts +13 -1
  13. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +23 -6
  14. package/packages/bundled-features/src/helpdesk/screens.ts +5 -1
  15. package/packages/bundled-features/src/signature/README.md +10 -3
  16. package/packages/bundled-features/src/signature/changes.json +25 -0
  17. package/packages/bundled-features/src/signature/entity.ts +3 -1
  18. package/packages/bundled-features/src/signature/feature.ts +41 -28
  19. package/packages/bundled-features/src/signature/handlers/cancel.write.ts +11 -3
  20. package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +5 -0
  21. package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +33 -1
  22. package/packages/bundled-features/src/signature/handlers/request.write.ts +37 -3
  23. package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +15 -1
  24. package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +5 -1
  25. package/packages/bundled-features/src/signature/i18n.ts +1 -0
  26. package/packages/bundled-features/src/signature/index.ts +2 -0
  27. package/packages/bundled-features/src/signature/list-cursor-seal.ts +59 -0
  28. package/packages/bundled-features/src/signature/options.ts +16 -1
  29. package/packages/bundled-features/src/signature/payloads.ts +14 -2
  30. package/packages/bundled-features/src/signature/png.ts +25 -4
  31. package/packages/bundled-features/src/signature/screens.ts +2 -0
  32. package/packages/bundled-features/src/signature/static-sign.ts +2 -1
  33. package/packages/bundled-features/src/signature/subject-queries.ts +184 -0
  34. package/packages/bundled-features/src/signature/subject-scope.ts +43 -0
  35. package/packages/bundled-features/src/signature/sweep.ts +32 -8
  36. package/packages/bundled-features/src/signature/web/constants.ts +12 -0
  37. package/packages/bundled-features/src/subscription-paddle/changes.json +1 -1
  38. package/packages/bundled-features/src/subscription-stripe/changes.json +6 -0
  39. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +2 -0
  40. package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +21 -16
  41. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +7 -3
  42. package/packages/bundled-features/src/tenant-lifecycle/changes.json +6 -0
  43. package/packages/bundled-features/src/tenant-lifecycle/run-tenant-destroy.ts +90 -42
  44. package/samples/apps/use-all-bundled/feature-manifest.json +2 -1
  45. package/samples/recipes/crypto-shredding-hr/README.md +1 -1
  46. package/samples/recipes/crypto-shredding-hr/src/feature.ts +1 -1
  47. package/samples/recipes/dashboard-stats/README.md +4 -0
  48. package/samples/recipes/dashboard-stats/src/feature.ts +47 -0
  49. package/samples/recipes/event-sourcing/src/feature.ts +31 -0
  50. package/samples/recipes/list-table-options/README.md +18 -3
  51. package/samples/recipes/list-table-options/src/feature.ts +170 -5
  52. package/samples/recipes/managed-config/src/feature.ts +9 -1
  53. package/samples/recipes/record-detail-layout/README.md +7 -0
  54. package/samples/recipes/record-detail-layout/src/feature.ts +40 -2
  55. package/samples/recipes/record-detail-layout/src/order-board.ts +1 -0
  56. package/samples/recipes/secrets-demo/README.md +1 -1
  57. package/samples/recipes/secrets-demo/src/feature.ts +2 -0
  58. package/samples/recipes/writeform-section/README.md +4 -0
  59. package/samples/recipes/writeform-section/src/feature.ts +97 -0
@@ -1,11 +1,28 @@
1
- import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
- import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
1
+ import { selectMany } from "@cosmicdrift/kumiko-framework/db";
2
+ import {
3
+ type AccessRule,
4
+ defineWriteHandler,
5
+ type HandlerContext,
6
+ isUuid,
7
+ } from "@cosmicdrift/kumiko-framework/engine";
8
+ import {
9
+ NotFoundError,
10
+ UnprocessableError,
11
+ writeFailure,
12
+ } from "@cosmicdrift/kumiko-framework/errors";
13
+ import {
14
+ canCallerReadFileRef,
15
+ type FileRef,
16
+ fileRefsTable,
17
+ } from "@cosmicdrift/kumiko-framework/files";
3
18
  import { PDFDocument } from "pdf-lib";
4
19
  import { requestExecutor, signerExecutor } from "../entity.ts";
5
20
  import { readTenantFile, sha256Hex } from "../files.ts";
6
21
  import { RequestSignatureSchema } from "../payloads.ts";
22
+ import type { SubjectScope } from "../subject-scope.ts";
7
23
  import {
8
24
  SIGNATURE_DEFAULT_VALIDITY_DAYS,
25
+ SIGNATURE_REQUEST_ENTITY,
9
26
  SIGNATURE_REQUEST_STATUS,
10
27
  SIGNATURE_SIGNER_STATUS,
11
28
  } from "../web/constants.ts";
@@ -28,7 +45,18 @@ async function isLoadablePdf(bytes: Uint8Array): Promise<boolean> {
28
45
  }
29
46
  }
30
47
 
31
- export function createRequestHandler(access: AccessRule) {
48
+ // A file the caller may not open through GET /files/:id answers like an unknown id, so ids cannot be probed.
49
+ async function isReadableTenantFile(ctx: HandlerContext, fileRefId: string): Promise<boolean> {
50
+ if (!isUuid(fileRefId)) return false;
51
+ const [fileRef] = await selectMany<FileRef>(ctx.db, fileRefsTable, {
52
+ id: fileRefId,
53
+ tenantId: ctx.user.tenantId,
54
+ isDeleted: false,
55
+ });
56
+ return fileRef !== undefined && (await canCallerReadFileRef(ctx, fileRef));
57
+ }
58
+
59
+ export function createRequestHandler(access: AccessRule, scope: SubjectScope) {
32
60
  return defineWriteHandler<"request", typeof RequestSignatureSchema, RequestSignatureData>({
33
61
  name: "request",
34
62
  schema: RequestSignatureSchema,
@@ -39,6 +67,12 @@ export function createRequestHandler(access: AccessRule) {
39
67
  handler: async (event, ctx) => {
40
68
  const payload = event.payload;
41
69
  const user = event.user;
70
+ if (!(await scope.allows(ctx, user, payload.subjectType, payload.subjectId))) {
71
+ return writeFailure(new NotFoundError(SIGNATURE_REQUEST_ENTITY));
72
+ }
73
+ if (!(await isReadableTenantFile(ctx, payload.documentFileId))) {
74
+ return writeFailure(new UnprocessableError("document_not_a_pdf"));
75
+ }
42
76
  const document = await readTenantFile(ctx, user.tenantId, payload.documentFileId);
43
77
  if (document === null || !(await isLoadablePdf(document.content))) {
44
78
  return writeFailure(new UnprocessableError("document_not_a_pdf"));
@@ -1,8 +1,11 @@
1
1
  import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { NotFoundError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
2
3
  import { signerExecutor } from "../entity.ts";
4
+ import { loadRequestOfSigner } from "../lib.ts";
3
5
  import { SignerIdSchema } from "../payloads.ts";
6
+ import type { SubjectScope } from "../subject-scope.ts";
4
7
 
5
- export function createRevokeLinkHandler(access: AccessRule) {
8
+ export function createRevokeLinkHandler(access: AccessRule, scope: SubjectScope) {
6
9
  return defineWriteHandler<"revoke-link", typeof SignerIdSchema, { readonly revoked: true }>({
7
10
  name: "revoke-link",
8
11
  schema: SignerIdSchema,
@@ -10,6 +13,17 @@ export function createRevokeLinkHandler(access: AccessRule) {
10
13
  agent: { expose: false },
11
14
  description: "Revokes the signing link of one signer; the token stops working at once.",
12
15
  handler: async (event, ctx) => {
16
+ if (scope.isScoped(event.user)) {
17
+ const signer = await signerExecutor.detail(
18
+ { id: event.payload.signerId },
19
+ event.user,
20
+ ctx.db,
21
+ );
22
+ const request = signer === null ? null : await loadRequestOfSigner(ctx, event.user, signer);
23
+ if (request === null || !(await scope.allowsRequest(ctx, event.user, request))) {
24
+ return writeFailure(new NotFoundError("signer", event.payload.signerId));
25
+ }
26
+ }
13
27
  const updated = await signerExecutor.update(
14
28
  { id: event.payload.signerId, changes: { linkAnchor: null } },
15
29
  event.user,
@@ -19,11 +19,12 @@ import {
19
19
  recordInPersonSignature,
20
20
  storeSignatureImage,
21
21
  } from "../signing.ts";
22
+ import type { SubjectScope } from "../subject-scope.ts";
22
23
  import { SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS } from "../web/constants.ts";
23
24
 
24
25
  export type SignInPersonData = { readonly requestStatus: string };
25
26
 
26
- export function createSignInPersonHandler(access: AccessRule) {
27
+ export function createSignInPersonHandler(access: AccessRule, scope: SubjectScope) {
27
28
  return defineWriteHandler<"sign-in-person", typeof SignInPersonSchema, SignInPersonData>({
28
29
  name: "sign-in-person",
29
30
  schema: SignInPersonSchema,
@@ -36,6 +37,9 @@ export function createSignInPersonHandler(access: AccessRule) {
36
37
  const signer = await signerExecutor.detail({ id: event.payload.signerId }, user, ctx.db);
37
38
  if (signer === null) return writeFailure(new NotFoundError("signer", event.payload.signerId));
38
39
  const request = await loadRequestOfSigner(ctx, user, signer);
40
+ if (request !== null && !(await scope.allowsRequest(ctx, user, request))) {
41
+ return writeFailure(new NotFoundError("signer", event.payload.signerId));
42
+ }
39
43
  const now = ctx.tz.now();
40
44
  if (request === null || !isOpenRequest(request, now) || !isUnsignedSigner(signer)) {
41
45
  return writeFailure(new UnprocessableError("signature_not_possible"));
@@ -48,5 +48,6 @@ export const SIGNATURE_I18N: Readonly<Record<string, LocalizedString>> = {
48
48
  [`${REQUEST}:status:option:completed`]: { en: "Completed", de: "Abgeschlossen" },
49
49
  [`${REQUEST}:status:option:declined`]: { en: "Declined", de: "Abgelehnt" },
50
50
  [`${REQUEST}:status:option:expired`]: { en: "Expired", de: "Abgelaufen" },
51
+ [`${REQUEST}:status:option:failed`]: { en: "Failed", de: "Fehlgeschlagen" },
51
52
  [`${REQUEST}:status:option:cancelled`]: { en: "Cancelled", de: "Abgebrochen" },
52
53
  };
@@ -1,10 +1,12 @@
1
1
  export type { SignatureRetention } from "./entity.ts";
2
2
  export { createSignatureFeature } from "./feature.ts";
3
3
  export type {
4
+ AuthorizeSignatureSubject,
4
5
  DeliverSignatureLink,
5
6
  RenderSignatureHtmlToPdf,
6
7
  SignatureLinkDelivery,
7
8
  SignatureOptions,
9
+ SignatureSubject,
8
10
  } from "./options.ts";
9
11
  export type { SignaturePageLabels } from "./signature-page.ts";
10
12
  export {
@@ -0,0 +1,59 @@
1
+ import { createHmac } from "node:crypto";
2
+ import type { SessionUser } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
4
+ import { CompactEncrypt, compactDecrypt } from "jose";
5
+
6
+ // Domain separation: the same secret also keys the link HMAC.
7
+ const CURSOR_KEY_LABEL = "signature-list-cursor";
8
+ const encoder = new TextEncoder();
9
+ const decoder = new TextDecoder();
10
+
11
+ type SealedCursorPayload = { readonly c: string; readonly u: string; readonly t: string };
12
+
13
+ function isSealedCursorPayload(value: unknown): value is SealedCursorPayload {
14
+ return (
15
+ isPlainObject(value) &&
16
+ typeof value["c"] === "string" &&
17
+ typeof value["u"] === "string" &&
18
+ typeof value["t"] === "string"
19
+ );
20
+ }
21
+
22
+ function cursorKey(secret: string): Uint8Array {
23
+ return new Uint8Array(createHmac("sha256", secret).update(CURSOR_KEY_LABEL).digest());
24
+ }
25
+
26
+ export async function sealListCursor(
27
+ baseCursor: string,
28
+ user: SessionUser,
29
+ secret: string,
30
+ ): Promise<string> {
31
+ const payload: SealedCursorPayload = {
32
+ c: baseCursor,
33
+ u: String(user.id),
34
+ t: String(user.tenantId),
35
+ };
36
+ return new CompactEncrypt(encoder.encode(JSON.stringify(payload)))
37
+ .setProtectedHeader({ alg: "dir", enc: "A256GCM" })
38
+ .encrypt(cursorKey(secret));
39
+ }
40
+
41
+ export async function openListCursor(
42
+ sealed: string,
43
+ user: SessionUser,
44
+ secret: string,
45
+ ): Promise<string | null> {
46
+ try {
47
+ // Allowlist: a foreign header such as PBES2 would cost PBKDF2 rounds per request.
48
+ const { plaintext } = await compactDecrypt(sealed, cursorKey(secret), {
49
+ keyManagementAlgorithms: ["dir"],
50
+ contentEncryptionAlgorithms: ["A256GCM"],
51
+ });
52
+ const payload: unknown = JSON.parse(decoder.decode(plaintext));
53
+ if (!isSealedCursorPayload(payload)) return null;
54
+ if (payload.u !== String(user.id) || payload.t !== String(user.tenantId)) return null;
55
+ return payload.c;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
@@ -27,6 +27,17 @@ export type DeliverSignatureLink = (
27
27
  delivery: SignatureLinkDelivery,
28
28
  ) => Promise<void>;
29
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
+
30
41
  export type SignatureOptions = {
31
42
  /** How long requests and signers are kept, data-retention keepFor syntax, counted from creation. */
32
43
  readonly retention: SignatureRetention;
@@ -34,12 +45,16 @@ export type SignatureOptions = {
34
45
  readonly renderHtmlToPdf: RenderSignatureHtmlToPdf;
35
46
  /** HMAC secret of the signing links. Without it every link is rejected. */
36
47
  readonly linkSecret: string;
37
- /** Sends a freshly issued link to the signer, e.g. by mail. A throw fails issue-link and leaves no link sent. */
48
+ /** Sends a freshly issued link to the signer, e.g. by mail. Runs inside the issue-link transaction, before it commits: enqueue through `ctx.dispatch` so the send commits or rolls back with the new link; a throw fails issue-link and leaves no link sent. */
38
49
  readonly deliverLink: DeliverSignatureLink;
39
50
  /** URL of the app's signature page; the token is appended as `#<token>`. */
40
51
  readonly signaturePageUrl: string;
41
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. */
42
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. Needs a non-empty `linkSecret`, which also seals the list cursor. */
55
+ readonly authorizeSubject?: AuthorizeSignatureSubject;
56
+ /** Roles that skip `authorizeSubject`, e.g. admins. */
57
+ readonly unscopedRoles?: readonly string[];
43
58
  };
44
59
 
45
60
  export const LINK_RATE_LIMIT: RateLimitDeclaration = {
@@ -1,6 +1,6 @@
1
1
  import * as z from "zod";
2
2
  import { MAX_SIGNATURE_PNG_BYTES } from "./png.ts";
3
- import { SIGNATURE_LEVEL } from "./web/constants.ts";
3
+ import { SIGNATURE_FAILURE_REASON, SIGNATURE_LEVEL } from "./web/constants.ts";
4
4
 
5
5
  export const MAX_SIGNERS_PER_REQUEST = 20;
6
6
  const MAX_VALIDITY_DAYS = 365;
@@ -12,7 +12,7 @@ const SignerInputSchema = z.object({
12
12
  name: z.string().trim().min(1).max(200),
13
13
  role: z.string().trim().min(1).max(100).optional(),
14
14
  contactId: z.string().min(1).max(64).optional(),
15
- email: z.string().trim().min(3).max(320).optional(),
15
+ email: z.string().trim().max(320).pipe(z.email()).optional(),
16
16
  });
17
17
 
18
18
  export const RequestSignatureSchema = z.object({
@@ -49,6 +49,13 @@ export const DeclineByLinkSchema = z.object({
49
49
  reason: z.string().trim().min(1).max(1000).optional(),
50
50
  });
51
51
 
52
+ const FailureReasonSchema = z.enum([
53
+ SIGNATURE_FAILURE_REASON.DocumentChanged,
54
+ SIGNATURE_FAILURE_REASON.SignatureImageMissing,
55
+ ]);
56
+
57
+ export const FailSchema = z.object({ requestId: z.uuid(), reason: FailureReasonSchema });
58
+
52
59
  export const FinishSchema = z.object({ requestId: z.uuid(), completedFileId: z.uuid() });
53
60
 
54
61
  const OutcomeBase = {
@@ -69,3 +76,8 @@ export const SignatureDeclinedEventSchema = z.object({
69
76
  });
70
77
 
71
78
  export const SignatureExpiredEventSchema = z.object(OutcomeBase);
79
+
80
+ export const SignatureFailedEventSchema = z.object({
81
+ ...OutcomeBase,
82
+ reason: FailureReasonSchema,
83
+ });
@@ -122,13 +122,34 @@ function unfilterRows(raw: Uint8Array, header: Header): boolean {
122
122
  }
123
123
 
124
124
  function countInkPixels(raw: Uint8Array, header: Header): number {
125
- const stride = header.width * header.bytesPerPixel + 1;
125
+ const bytesPerPixel = header.bytesPerPixel;
126
+ const stride = header.width * bytesPerPixel + 1;
127
+ const pixelStart = (row: number, column: number): number =>
128
+ row * stride + 1 + column * bytesPerPixel;
129
+ const background = pixelStart(0, 0);
130
+ const alphaOf = (start: number): number => raw[start + bytesPerPixel - 1] ?? 0;
131
+ const colorMatchesBackground = (start: number): boolean => {
132
+ for (let i = 0; i < bytesPerPixel; i++) {
133
+ if (raw[start + i] !== raw[background + i]) return false;
134
+ }
135
+ return true;
136
+ };
137
+ // Only four identical, opaque corners mean a solid background; a single opaque pixel could be a stroke.
138
+ const corners = [
139
+ background,
140
+ pixelStart(0, header.width - 1),
141
+ pixelStart(header.height - 1, 0),
142
+ pixelStart(header.height - 1, header.width - 1),
143
+ ];
144
+ const hasSolidBackground = corners.every(
145
+ (corner) => alphaOf(corner) > 0 && colorMatchesBackground(corner),
146
+ );
126
147
  let ink = 0;
127
148
  for (let row = 0; row < header.height; row++) {
128
149
  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++;
150
+ const start = pixelStart(row, column);
151
+ const isInk = alphaOf(start) > 0 && (!hasSolidBackground || !colorMatchesBackground(start));
152
+ if (isInk) ink++;
132
153
  }
133
154
  }
134
155
  return ink;
@@ -44,6 +44,8 @@ export function createSignatureListScreen(
44
44
  { field: "completedAt", hideOnNarrow: true },
45
45
  ],
46
46
  defaultSort: { field: "expiresAt", dir: "desc" },
47
+ // A user bound by authorizeSubject gets no total, so the list pages by cursor.
48
+ pagination: "infinite",
47
49
  access,
48
50
  searchable: true,
49
51
  rowActions: [
@@ -10,7 +10,7 @@ import {
10
10
  staticSuccess,
11
11
  takeUrlToken,
12
12
  } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
13
- import { SignatureHandlers } from "./web/constants.ts";
13
+ import { SIGNATURE_INVALID_LINK_REASON, SignatureHandlers } from "./web/constants.ts";
14
14
 
15
15
  export {
16
16
  hrefWithoutUrlToken,
@@ -29,6 +29,7 @@ export {
29
29
  type SignaturePadCanvas,
30
30
  type SignaturePadOptions,
31
31
  } from "./web/pad.ts";
32
+ export { SIGNATURE_INVALID_LINK_REASON };
32
33
 
33
34
  export type SignatureLinkView = {
34
35
  readonly title: string;
@@ -0,0 +1,184 @@
1
+ import {
2
+ DEFAULT_LIST_LIMIT,
3
+ entityListSchema,
4
+ type HandlerContext,
5
+ isUuid,
6
+ MAX_LIST_LIMIT,
7
+ type QueryHandlerDef,
8
+ type SessionUser,
9
+ } from "@cosmicdrift/kumiko-framework/engine";
10
+ import { AccessDeniedError } from "@cosmicdrift/kumiko-framework/errors";
11
+ import { requestExecutor } from "./entity.ts";
12
+ import { openListCursor, sealListCursor } from "./list-cursor-seal.ts";
13
+ import type { SubjectScope } from "./subject-scope.ts";
14
+
15
+ type ListPayload = ReturnType<typeof entityListSchema.parse>;
16
+ type ListFilter = NonNullable<ListPayload["filter"]>;
17
+
18
+ function allFilters(payload: ListPayload): readonly ListFilter[] {
19
+ return [...(payload.filter === undefined ? [] : [payload.filter]), ...(payload.filters ?? [])];
20
+ }
21
+
22
+ function emptyPage(payload: ListPayload) {
23
+ return { rows: [], nextCursor: null, ...(payload.totalCount === true && { total: 0 }) };
24
+ }
25
+
26
+ function onlyFilterOn(payload: ListPayload, field: string): ListFilter | null {
27
+ const matching = allFilters(payload).filter((filter) => filter.field === field);
28
+ const [first] = matching;
29
+ return matching.length === 1 && first !== undefined ? first : null;
30
+ }
31
+
32
+ type RowsPage = { rows: unknown[] } & Record<string, unknown>;
33
+
34
+ function isRowsPage(value: unknown): value is RowsPage {
35
+ return (
36
+ typeof value === "object" && value !== null && "rows" in value && Array.isArray(value.rows)
37
+ );
38
+ }
39
+
40
+ function subjectKey(subject: { subjectType?: unknown; subjectId?: unknown }): string {
41
+ return `${String(subject.subjectType)}\u0000${String(subject.subjectId)}`;
42
+ }
43
+
44
+ // ponytail: at most this many base pages per answer; a user who may see almost none of the
45
+ // tenant's requests gets short pages and scrolls on. Upgrade to a subject-joined query if that hurts.
46
+ const MAX_BASE_PAGES_PER_ANSWER = 10;
47
+ // authorizeSubject usually queries the database; a page of 200 subjects must not take the whole pool.
48
+ const SUBJECT_CHECKS_IN_PARALLEL = 10;
49
+
50
+ type ListQuery = Parameters<QueryHandlerDef["handler"]>[0];
51
+
52
+ async function openFirstQuery(
53
+ query: ListQuery,
54
+ payload: ListPayload,
55
+ user: SessionUser,
56
+ cursorSecret: string,
57
+ ): Promise<ListQuery> {
58
+ const { cursor: sealedCursor, ...payloadWithoutCursor } = payload;
59
+ if (sealedCursor === undefined) return query;
60
+ const openedCursor = await openListCursor(sealedCursor, user, cursorSecret);
61
+ if (openedCursor === null) throw new AccessDeniedError();
62
+ return { ...query, payload: { ...payloadWithoutCursor, cursor: openedCursor } };
63
+ }
64
+
65
+ async function sealedPage(
66
+ page: RowsPage,
67
+ visibleRows: unknown[],
68
+ nextCursor: unknown,
69
+ user: SessionUser,
70
+ cursorSecret: string,
71
+ ) {
72
+ // `total` would count requests of foreign subjects. The base cursor names the last base row,
73
+ // which may belong to a foreign subject, so the user only gets it sealed.
74
+ const { total: _total, rows: _rows, nextCursor: _baseCursor, ...rest } = page;
75
+ return {
76
+ ...rest,
77
+ rows: visibleRows,
78
+ nextCursor:
79
+ typeof nextCursor === "string" ? await sealListCursor(nextCursor, user, cursorSecret) : null,
80
+ };
81
+ }
82
+
83
+ export function scopeRequestList(
84
+ base: QueryHandlerDef,
85
+ scope: SubjectScope,
86
+ cursorSecret: string,
87
+ ): QueryHandlerDef {
88
+ return {
89
+ ...base,
90
+ handler: async (query, ctx) => {
91
+ const user = query.user;
92
+ if (!scope.isScoped(user)) return base.handler(query, ctx);
93
+ const payload = entityListSchema.parse(query.payload);
94
+ // Group counts would include requests of foreign subjects, and an offset counts base rows,
95
+ // not the rows this user sees; the screen pages by cursor. limit 0 would hand out a cursor
96
+ // without checking a row.
97
+ if (payload.aggregate !== undefined || (payload.offset ?? 0) > 0 || payload.limit === 0) {
98
+ throw new AccessDeniedError();
99
+ }
100
+ const limit = payload.limit ?? DEFAULT_LIST_LIMIT;
101
+ const verdicts = new Map<string, boolean>();
102
+ const visibleRows: unknown[] = [];
103
+ const firstQuery = await openFirstQuery(query, payload, user, cursorSecret);
104
+ let page: unknown = await base.handler(firstQuery, ctx);
105
+ for (let fetched = 1; ; fetched++) {
106
+ if (!isRowsPage(page)) throw new Error("signature request list did not return a rows page");
107
+ const unknownSubjects = new Map(
108
+ page.rows
109
+ .map((row) => [subjectKey(subjectOf(row)), subjectOf(row)] as const)
110
+ .filter(([key]) => !verdicts.has(key)),
111
+ );
112
+ const pending = [...unknownSubjects];
113
+ for (let start = 0; start < pending.length; start += SUBJECT_CHECKS_IN_PARALLEL) {
114
+ await Promise.all(
115
+ pending.slice(start, start + SUBJECT_CHECKS_IN_PARALLEL).map(async ([key, subject]) => {
116
+ verdicts.set(key, await scope.allowsRequest(ctx, user, subject));
117
+ }),
118
+ );
119
+ }
120
+ visibleRows.push(...page.rows.filter((row) => verdicts.get(subjectKey(subjectOf(row)))));
121
+ const nextCursor = page["nextCursor"];
122
+ if (
123
+ visibleRows.length >= limit ||
124
+ typeof nextCursor !== "string" ||
125
+ fetched >= MAX_BASE_PAGES_PER_ANSWER ||
126
+ verdicts.size >= MAX_LIST_LIMIT
127
+ ) {
128
+ return sealedPage(page, visibleRows, nextCursor, user, cursorSecret);
129
+ }
130
+ page = await base.handler(
131
+ {
132
+ ...query,
133
+ payload: { ...payload, cursor: nextCursor, limit: limit - visibleRows.length },
134
+ },
135
+ ctx,
136
+ );
137
+ }
138
+ },
139
+ };
140
+ }
141
+
142
+ export function scopeRequestDetail(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef {
143
+ return {
144
+ ...base,
145
+ handler: async (query, ctx) => {
146
+ const row = await base.handler(query, ctx);
147
+ if (row === null || !scope.isScoped(query.user)) return row;
148
+ return (await scope.allowsRequest(ctx, query.user, subjectOf(row))) ? row : null;
149
+ },
150
+ };
151
+ }
152
+
153
+ function subjectOf(row: unknown): { subjectType?: unknown; subjectId?: unknown } {
154
+ if (typeof row !== "object" || row === null) return {};
155
+ return {
156
+ subjectType: "subjectType" in row ? row.subjectType : undefined,
157
+ subjectId: "subjectId" in row ? row.subjectId : undefined,
158
+ };
159
+ }
160
+
161
+ export function scopeSignerList(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef {
162
+ return {
163
+ ...base,
164
+ handler: async (query, ctx: HandlerContext) => {
165
+ const user: SessionUser = query.user;
166
+ if (!scope.isScoped(user)) return base.handler(query, ctx);
167
+ const payload = entityListSchema.parse(query.payload);
168
+ const requestFilter = onlyFilterOn(payload, "requestId");
169
+ if (
170
+ requestFilter === null ||
171
+ requestFilter.op !== "eq" ||
172
+ typeof requestFilter.value !== "string"
173
+ ) {
174
+ throw new AccessDeniedError();
175
+ }
176
+ if (!isUuid(requestFilter.value)) return emptyPage(payload);
177
+ const request = await requestExecutor.detail({ id: requestFilter.value }, user, ctx.db);
178
+ if (request === null || !(await scope.allowsRequest(ctx, user, request))) {
179
+ return emptyPage(payload);
180
+ }
181
+ return base.handler(query, ctx);
182
+ },
183
+ };
184
+ }
@@ -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
+ }
@@ -24,8 +24,10 @@ import {
24
24
  type SignaturePageEntry,
25
25
  } from "./signature-page.ts";
26
26
  import {
27
+ SIGNATURE_FAILURE_REASON,
27
28
  SIGNATURE_METHOD,
28
29
  SIGNATURE_REQUEST_STATUS,
30
+ type SignatureFailureReason,
29
31
  SignatureInternalHandlers,
30
32
  } from "./web/constants.ts";
31
33
 
@@ -85,8 +87,34 @@ async function signaturePageEntries(
85
87
  return entries;
86
88
  }
87
89
 
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 failRequest(
91
+ ctx: JobContext,
92
+ request: RequestRow,
93
+ reason: SignatureFailureReason,
94
+ ): Promise<void> {
95
+ const failed = await ctx.dispatch.write(SignatureInternalHandlers.fail, {
96
+ requestId: request.id,
97
+ reason,
98
+ });
99
+ if (!failed.isSuccess) {
100
+ ctx.obs.log.error("[signature:sweep] marking the request failed was rejected", {
101
+ requestId: request.id,
102
+ reason,
103
+ error: failed.error,
104
+ });
105
+ return;
106
+ }
107
+ if (propertyOf(failed.data, "failed") === true) {
108
+ ctx.obs.log.warn("[signature:sweep] request cannot be completed, marked failed", {
109
+ requestId: request.id,
110
+ reason,
111
+ });
112
+ }
113
+ }
114
+
115
+ // Appends the signature page to the unchanged original. A missing or changed original or a
116
+ // missing signature image can never heal and ends the request as failed. A renderer outage
117
+ // throws, the request stays all-signed and the next run tries again.
90
118
  async function finalizeRequest(
91
119
  ctx: JobContext,
92
120
  opts: SignatureOptions,
@@ -94,9 +122,7 @@ async function finalizeRequest(
94
122
  ): Promise<void> {
95
123
  const original = await readTenantFile(ctx, ctx.systemUser.tenantId, request.documentFileId);
96
124
  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
- });
125
+ await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.DocumentChanged);
100
126
  return;
101
127
  }
102
128
  const entries = await signaturePageEntries(
@@ -104,9 +130,7 @@ async function finalizeRequest(
104
130
  await listSigners(ctx, ctx.systemUser, request.id),
105
131
  );
106
132
  if (entries === null) {
107
- ctx.obs.log.warn("[signature:sweep] signature image missing, not completing", {
108
- requestId: request.id,
109
- });
133
+ await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.SignatureImageMissing);
110
134
  return;
111
135
  }
112
136
  const html = buildSignaturePageHtml({