@cosmicdrift/kumiko-bundled-features 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.
- package/dist/agent-tools/api-docs/schema-fields.js +9 -0
- package/dist/auth-email-password/index.d.ts +2 -1
- package/dist/auth-email-password/index.js +2 -1
- package/dist/auth-email-password/signup-activation.js +2 -1
- package/dist/auth-email-password/signup-token-store.d.ts +1 -6
- package/dist/auth-email-password/signup-token-store.js +0 -5
- package/dist/cap-counter/stock-cap-guard.d.ts +9 -2
- package/dist/cap-counter/stock-cap-guard.js +9 -11
- package/dist/document-ingest-foundation/feature.js +5 -1
- package/dist/document-ingest-foundation/report-ingest-progress.js +19 -6
- package/dist/helpdesk/screens.js +5 -1
- package/dist/signature/entity.d.ts +8 -6
- package/dist/signature/entity.js +3 -1
- package/dist/signature/feature.js +27 -14
- package/dist/signature/handlers/cancel.write.d.ts +2 -1
- package/dist/signature/handlers/cancel.write.js +10 -3
- package/dist/signature/handlers/issue-link.write.d.ts +2 -1
- package/dist/signature/handlers/issue-link.write.js +4 -1
- package/dist/signature/handlers/lifecycle.write.d.ts +9 -0
- package/dist/signature/handlers/lifecycle.write.js +23 -1
- package/dist/signature/handlers/request.write.d.ts +3 -2
- package/dist/signature/handlers/request.write.js +23 -4
- package/dist/signature/handlers/revoke-link.write.d.ts +2 -1
- package/dist/signature/handlers/revoke-link.write.js +10 -1
- package/dist/signature/handlers/sign-in-person.write.d.ts +2 -1
- package/dist/signature/handlers/sign-in-person.write.js +4 -1
- package/dist/signature/i18n.js +1 -0
- package/dist/signature/index.d.ts +1 -1
- package/dist/signature/list-cursor-seal.d.ts +3 -0
- package/dist/signature/list-cursor-seal.js +44 -0
- package/dist/signature/options.d.ts +10 -1
- package/dist/signature/payloads.d.ts +17 -1
- package/dist/signature/payloads.js +11 -2
- package/dist/signature/png.js +23 -3
- package/dist/signature/screens.js +2 -0
- package/dist/signature/static-sign.d.ts +2 -0
- package/dist/signature/static-sign.js +2 -1
- package/dist/signature/subject-queries.d.ts +5 -0
- package/dist/signature/subject-queries.js +135 -0
- package/dist/signature/subject-scope.d.ts +11 -0
- package/dist/signature/subject-scope.js +20 -0
- package/dist/signature/sweep.js +26 -9
- package/dist/signature/web/constants.d.ts +9 -0
- package/dist/signature/web/constants.js +8 -0
- package/dist/subscription-stripe/plugin-methods.js +2 -0
- package/dist/subscription-stripe/verify-webhook.js +17 -16
- package/dist/tenant-inactivity/handlers/keep-account.write.js +5 -2
- package/dist/tenant-lifecycle/run-tenant-destroy.js +65 -33
- package/package.json +11 -11
- package/src/agent-tools/changes.json +6 -0
- package/src/cap-counter/changes.json +6 -0
- package/src/channel-whatsapp/changes.json +1 -1
- package/src/document-ingest-foundation/changes.json +6 -0
- package/src/signature/changes.json +25 -0
- package/src/subscription-paddle/changes.json +1 -1
- package/src/subscription-stripe/changes.json +6 -0
- package/src/tenant-lifecycle/changes.json +6 -0
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import { NotFoundError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
|
|
2
3
|
import { signerExecutor } from "../entity.js";
|
|
4
|
+
import { loadRequestOfSigner } from "../lib.js";
|
|
3
5
|
import { SignerIdSchema } from "../payloads.js";
|
|
4
|
-
export function createRevokeLinkHandler(access) {
|
|
6
|
+
export function createRevokeLinkHandler(access, scope) {
|
|
5
7
|
return defineWriteHandler({
|
|
6
8
|
name: "revoke-link",
|
|
7
9
|
schema: SignerIdSchema,
|
|
@@ -9,6 +11,13 @@ export function createRevokeLinkHandler(access) {
|
|
|
9
11
|
agent: { expose: false },
|
|
10
12
|
description: "Revokes the signing link of one signer; the token stops working at once.",
|
|
11
13
|
handler: async (event, ctx) => {
|
|
14
|
+
if (scope.isScoped(event.user)) {
|
|
15
|
+
const signer = await signerExecutor.detail({ id: event.payload.signerId }, event.user, ctx.db);
|
|
16
|
+
const request = signer === null ? null : await loadRequestOfSigner(ctx, event.user, signer);
|
|
17
|
+
if (request === null || !(await scope.allowsRequest(ctx, event.user, request))) {
|
|
18
|
+
return writeFailure(new NotFoundError("signer", event.payload.signerId));
|
|
19
|
+
}
|
|
20
|
+
}
|
|
12
21
|
const updated = await signerExecutor.update({ id: event.payload.signerId, changes: { linkAnchor: null } }, event.user, ctx.db, { skipOptimisticLock: true });
|
|
13
22
|
if (!updated.isSuccess)
|
|
14
23
|
return updated;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { type AccessRule } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import type { SubjectScope } from "../subject-scope.ts";
|
|
2
3
|
export type SignInPersonData = {
|
|
3
4
|
readonly requestStatus: string;
|
|
4
5
|
};
|
|
5
|
-
export declare function createSignInPersonHandler(access: AccessRule): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"sign-in-person", import("zod").ZodObject<{
|
|
6
|
+
export declare function createSignInPersonHandler(access: AccessRule, scope: SubjectScope): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"sign-in-person", import("zod").ZodObject<{
|
|
6
7
|
signerId: import("zod").ZodUUID;
|
|
7
8
|
imagePngBase64: import("zod").ZodString;
|
|
8
9
|
}, import("zod/v4/core").$strip>, SignInPersonData, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
|
|
@@ -6,7 +6,7 @@ import { advanceIfAllSigned, isOpenRequest, isUnsignedSigner, loadRequestOfSigne
|
|
|
6
6
|
import { SignInPersonSchema } from "../payloads.js";
|
|
7
7
|
import { decodeSignatureImage, invalidImage, recordInPersonSignature, storeSignatureImage, } from "../signing.js";
|
|
8
8
|
import { SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS } from "../web/constants.js";
|
|
9
|
-
export function createSignInPersonHandler(access) {
|
|
9
|
+
export function createSignInPersonHandler(access, scope) {
|
|
10
10
|
return defineWriteHandler({
|
|
11
11
|
name: "sign-in-person",
|
|
12
12
|
schema: SignInPersonSchema,
|
|
@@ -19,6 +19,9 @@ export function createSignInPersonHandler(access) {
|
|
|
19
19
|
if (signer === null)
|
|
20
20
|
return writeFailure(new NotFoundError("signer", event.payload.signerId));
|
|
21
21
|
const request = await loadRequestOfSigner(ctx, user, signer);
|
|
22
|
+
if (request !== null && !(await scope.allowsRequest(ctx, user, request))) {
|
|
23
|
+
return writeFailure(new NotFoundError("signer", event.payload.signerId));
|
|
24
|
+
}
|
|
22
25
|
const now = ctx.tz.now();
|
|
23
26
|
if (request === null || !isOpenRequest(request, now) || !isUnsignedSigner(signer)) {
|
|
24
27
|
return writeFailure(new UnprocessableError("signature_not_possible"));
|
package/dist/signature/i18n.js
CHANGED
|
@@ -45,5 +45,6 @@ export const SIGNATURE_I18N = {
|
|
|
45
45
|
[`${REQUEST}:status:option:completed`]: { en: "Completed", de: "Abgeschlossen" },
|
|
46
46
|
[`${REQUEST}:status:option:declined`]: { en: "Declined", de: "Abgelehnt" },
|
|
47
47
|
[`${REQUEST}:status:option:expired`]: { en: "Expired", de: "Abgelaufen" },
|
|
48
|
+
[`${REQUEST}:status:option:failed`]: { en: "Failed", de: "Fehlgeschlagen" },
|
|
48
49
|
[`${REQUEST}:status:option:cancelled`]: { en: "Cancelled", de: "Abgebrochen" },
|
|
49
50
|
};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export type { SignatureRetention } from "./entity.ts";
|
|
2
2
|
export { createSignatureFeature } from "./feature.ts";
|
|
3
|
-
export type { DeliverSignatureLink, RenderSignatureHtmlToPdf, SignatureLinkDelivery, SignatureOptions, } from "./options.ts";
|
|
3
|
+
export type { AuthorizeSignatureSubject, DeliverSignatureLink, RenderSignatureHtmlToPdf, SignatureLinkDelivery, SignatureOptions, SignatureSubject, } from "./options.ts";
|
|
4
4
|
export type { SignaturePageLabels } from "./signature-page.ts";
|
|
5
5
|
export { SIGNATURE_DEFAULT_VALIDITY_DAYS, SIGNATURE_EVENT_SHORT, SIGNATURE_FEATURE, SIGNATURE_INVALID_IMAGE_REASON, SIGNATURE_INVALID_LINK_REASON, SIGNATURE_LEVEL, SIGNATURE_LINK_TTL_DAYS, SIGNATURE_MAX_LINK_OPENS, SIGNATURE_METHOD, SIGNATURE_REQUEST_ENTITY, SIGNATURE_REQUEST_STATUS, SIGNATURE_SIGNER_ENTITY, SIGNATURE_SIGNER_STATUS, SignatureEvents, SignatureHandlers, SignatureInternalHandlers, SignatureJobs, type SignatureLevel, type SignatureMethod, SignatureQueries, type SignatureRequestStatus, type SignatureSignerStatus, } from "./web/constants.ts";
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { SessionUser } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
export declare function sealListCursor(baseCursor: string, user: SessionUser, secret: string): Promise<string>;
|
|
3
|
+
export declare function openListCursor(sealed: string, user: SessionUser, secret: string): Promise<string | null>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto";
|
|
2
|
+
import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
|
|
3
|
+
import { CompactEncrypt, compactDecrypt } from "jose";
|
|
4
|
+
// Domain separation: the same secret also keys the link HMAC.
|
|
5
|
+
const CURSOR_KEY_LABEL = "signature-list-cursor";
|
|
6
|
+
const encoder = new TextEncoder();
|
|
7
|
+
const decoder = new TextDecoder();
|
|
8
|
+
function isSealedCursorPayload(value) {
|
|
9
|
+
return (isPlainObject(value) &&
|
|
10
|
+
typeof value["c"] === "string" &&
|
|
11
|
+
typeof value["u"] === "string" &&
|
|
12
|
+
typeof value["t"] === "string");
|
|
13
|
+
}
|
|
14
|
+
function cursorKey(secret) {
|
|
15
|
+
return new Uint8Array(createHmac("sha256", secret).update(CURSOR_KEY_LABEL).digest());
|
|
16
|
+
}
|
|
17
|
+
export async function sealListCursor(baseCursor, user, secret) {
|
|
18
|
+
const payload = {
|
|
19
|
+
c: baseCursor,
|
|
20
|
+
u: String(user.id),
|
|
21
|
+
t: String(user.tenantId),
|
|
22
|
+
};
|
|
23
|
+
return new CompactEncrypt(encoder.encode(JSON.stringify(payload)))
|
|
24
|
+
.setProtectedHeader({ alg: "dir", enc: "A256GCM" })
|
|
25
|
+
.encrypt(cursorKey(secret));
|
|
26
|
+
}
|
|
27
|
+
export async function openListCursor(sealed, user, secret) {
|
|
28
|
+
try {
|
|
29
|
+
// Allowlist: a foreign header such as PBES2 would cost PBKDF2 rounds per request.
|
|
30
|
+
const { plaintext } = await compactDecrypt(sealed, cursorKey(secret), {
|
|
31
|
+
keyManagementAlgorithms: ["dir"],
|
|
32
|
+
contentEncryptionAlgorithms: ["A256GCM"],
|
|
33
|
+
});
|
|
34
|
+
const payload = JSON.parse(decoder.decode(plaintext));
|
|
35
|
+
if (!isSealedCursorPayload(payload))
|
|
36
|
+
return null;
|
|
37
|
+
if (payload.u !== String(user.id) || payload.t !== String(user.tenantId))
|
|
38
|
+
return null;
|
|
39
|
+
return payload.c;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -14,6 +14,11 @@ export type SignatureLinkDelivery = {
|
|
|
14
14
|
readonly issuedBy: SessionUser;
|
|
15
15
|
};
|
|
16
16
|
export type DeliverSignatureLink = (ctx: HandlerContext, delivery: SignatureLinkDelivery) => Promise<void>;
|
|
17
|
+
export type SignatureSubject = {
|
|
18
|
+
readonly subjectType: string;
|
|
19
|
+
readonly subjectId: string;
|
|
20
|
+
};
|
|
21
|
+
export type AuthorizeSignatureSubject = (ctx: HandlerContext, user: SessionUser, subject: SignatureSubject) => Promise<boolean>;
|
|
17
22
|
export type SignatureOptions = {
|
|
18
23
|
/** How long requests and signers are kept, data-retention keepFor syntax, counted from creation. */
|
|
19
24
|
readonly retention: SignatureRetention;
|
|
@@ -21,11 +26,15 @@ export type SignatureOptions = {
|
|
|
21
26
|
readonly renderHtmlToPdf: RenderSignatureHtmlToPdf;
|
|
22
27
|
/** HMAC secret of the signing links. Without it every link is rejected. */
|
|
23
28
|
readonly linkSecret: string;
|
|
24
|
-
/** Sends a freshly issued link to the signer, e.g. by mail.
|
|
29
|
+
/** 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. */
|
|
25
30
|
readonly deliverLink: DeliverSignatureLink;
|
|
26
31
|
/** URL of the app's signature page; the token is appended as `#<token>`. */
|
|
27
32
|
readonly signaturePageUrl: string;
|
|
28
33
|
/** Access rule of the signed-in handlers, queries, screens and nav. Default `{ roles: ["TenantAdmin", "TenantMember"] }`; set it when the app hands out other roles. The link handlers stay anonymous. */
|
|
29
34
|
readonly access?: AccessRule;
|
|
35
|
+
/** Runs for every signed-in handler and query on the subject of the request, except for `unscopedRoles`. `false` answers like "does not exist". Without it every user with `access` sees every request of the tenant. Needs a non-empty `linkSecret`, which also seals the list cursor. */
|
|
36
|
+
readonly authorizeSubject?: AuthorizeSignatureSubject;
|
|
37
|
+
/** Roles that skip `authorizeSubject`, e.g. admins. */
|
|
38
|
+
readonly unscopedRoles?: readonly string[];
|
|
30
39
|
};
|
|
31
40
|
export declare const LINK_RATE_LIMIT: RateLimitDeclaration;
|
|
@@ -11,7 +11,7 @@ export declare const RequestSignatureSchema: z.ZodObject<{
|
|
|
11
11
|
name: z.ZodString;
|
|
12
12
|
role: z.ZodOptional<z.ZodString>;
|
|
13
13
|
contactId: z.ZodOptional<z.ZodString>;
|
|
14
|
-
email: z.ZodOptional<z.ZodString
|
|
14
|
+
email: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodEmail>>;
|
|
15
15
|
}, z.core.$strip>>;
|
|
16
16
|
}, z.core.$strip>;
|
|
17
17
|
export type RequestSignatureInput = z.infer<typeof RequestSignatureSchema>;
|
|
@@ -36,6 +36,13 @@ export declare const DeclineByLinkSchema: z.ZodObject<{
|
|
|
36
36
|
token: z.ZodString;
|
|
37
37
|
reason: z.ZodOptional<z.ZodString>;
|
|
38
38
|
}, z.core.$strip>;
|
|
39
|
+
export declare const FailSchema: z.ZodObject<{
|
|
40
|
+
requestId: z.ZodUUID;
|
|
41
|
+
reason: z.ZodEnum<{
|
|
42
|
+
"document-changed": "document-changed";
|
|
43
|
+
"signature-image-missing": "signature-image-missing";
|
|
44
|
+
}>;
|
|
45
|
+
}, z.core.$strip>;
|
|
39
46
|
export declare const FinishSchema: z.ZodObject<{
|
|
40
47
|
requestId: z.ZodUUID;
|
|
41
48
|
completedFileId: z.ZodUUID;
|
|
@@ -58,3 +65,12 @@ export declare const SignatureExpiredEventSchema: z.ZodObject<{
|
|
|
58
65
|
subjectType: z.ZodString;
|
|
59
66
|
subjectId: z.ZodString;
|
|
60
67
|
}, z.core.$strip>;
|
|
68
|
+
export declare const SignatureFailedEventSchema: z.ZodObject<{
|
|
69
|
+
requestId: z.ZodString;
|
|
70
|
+
subjectType: z.ZodString;
|
|
71
|
+
subjectId: z.ZodString;
|
|
72
|
+
reason: z.ZodEnum<{
|
|
73
|
+
"document-changed": "document-changed";
|
|
74
|
+
"signature-image-missing": "signature-image-missing";
|
|
75
|
+
}>;
|
|
76
|
+
}, z.core.$strip>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as z from "zod";
|
|
2
2
|
import { MAX_SIGNATURE_PNG_BYTES } from "./png.js";
|
|
3
|
-
import { SIGNATURE_LEVEL } from "./web/constants.js";
|
|
3
|
+
import { SIGNATURE_FAILURE_REASON, SIGNATURE_LEVEL } from "./web/constants.js";
|
|
4
4
|
export const MAX_SIGNERS_PER_REQUEST = 20;
|
|
5
5
|
const MAX_VALIDITY_DAYS = 365;
|
|
6
6
|
// Base64 inflates by 4/3; the png checks apply to the decoded bytes.
|
|
@@ -10,7 +10,7 @@ const SignerInputSchema = z.object({
|
|
|
10
10
|
name: z.string().trim().min(1).max(200),
|
|
11
11
|
role: z.string().trim().min(1).max(100).optional(),
|
|
12
12
|
contactId: z.string().min(1).max(64).optional(),
|
|
13
|
-
email: z.string().trim().
|
|
13
|
+
email: z.string().trim().max(320).pipe(z.email()).optional(),
|
|
14
14
|
});
|
|
15
15
|
export const RequestSignatureSchema = z.object({
|
|
16
16
|
documentFileId: z.uuid(),
|
|
@@ -35,6 +35,11 @@ export const DeclineByLinkSchema = z.object({
|
|
|
35
35
|
token: TokenPayload,
|
|
36
36
|
reason: z.string().trim().min(1).max(1000).optional(),
|
|
37
37
|
});
|
|
38
|
+
const FailureReasonSchema = z.enum([
|
|
39
|
+
SIGNATURE_FAILURE_REASON.DocumentChanged,
|
|
40
|
+
SIGNATURE_FAILURE_REASON.SignatureImageMissing,
|
|
41
|
+
]);
|
|
42
|
+
export const FailSchema = z.object({ requestId: z.uuid(), reason: FailureReasonSchema });
|
|
38
43
|
export const FinishSchema = z.object({ requestId: z.uuid(), completedFileId: z.uuid() });
|
|
39
44
|
const OutcomeBase = {
|
|
40
45
|
requestId: z.string().min(1),
|
|
@@ -51,3 +56,7 @@ export const SignatureDeclinedEventSchema = z.object({
|
|
|
51
56
|
signerId: z.string().min(1),
|
|
52
57
|
});
|
|
53
58
|
export const SignatureExpiredEventSchema = z.object(OutcomeBase);
|
|
59
|
+
export const SignatureFailedEventSchema = z.object({
|
|
60
|
+
...OutcomeBase,
|
|
61
|
+
reason: FailureReasonSchema,
|
|
62
|
+
});
|
package/dist/signature/png.js
CHANGED
|
@@ -105,12 +105,32 @@ function unfilterRows(raw, header) {
|
|
|
105
105
|
return true;
|
|
106
106
|
}
|
|
107
107
|
function countInkPixels(raw, header) {
|
|
108
|
-
const
|
|
108
|
+
const bytesPerPixel = header.bytesPerPixel;
|
|
109
|
+
const stride = header.width * bytesPerPixel + 1;
|
|
110
|
+
const pixelStart = (row, column) => row * stride + 1 + column * bytesPerPixel;
|
|
111
|
+
const background = pixelStart(0, 0);
|
|
112
|
+
const alphaOf = (start) => raw[start + bytesPerPixel - 1] ?? 0;
|
|
113
|
+
const colorMatchesBackground = (start) => {
|
|
114
|
+
for (let i = 0; i < bytesPerPixel; i++) {
|
|
115
|
+
if (raw[start + i] !== raw[background + i])
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
return true;
|
|
119
|
+
};
|
|
120
|
+
// Only four identical, opaque corners mean a solid background; a single opaque pixel could be a stroke.
|
|
121
|
+
const corners = [
|
|
122
|
+
background,
|
|
123
|
+
pixelStart(0, header.width - 1),
|
|
124
|
+
pixelStart(header.height - 1, 0),
|
|
125
|
+
pixelStart(header.height - 1, header.width - 1),
|
|
126
|
+
];
|
|
127
|
+
const hasSolidBackground = corners.every((corner) => alphaOf(corner) > 0 && colorMatchesBackground(corner));
|
|
109
128
|
let ink = 0;
|
|
110
129
|
for (let row = 0; row < header.height; row++) {
|
|
111
130
|
for (let column = 0; column < header.width; column++) {
|
|
112
|
-
const
|
|
113
|
-
|
|
131
|
+
const start = pixelStart(row, column);
|
|
132
|
+
const isInk = alphaOf(start) > 0 && (!hasSolidBackground || !colorMatchesBackground(start));
|
|
133
|
+
if (isInk)
|
|
114
134
|
ink++;
|
|
115
135
|
}
|
|
116
136
|
}
|
|
@@ -27,6 +27,8 @@ export function createSignatureListScreen(access) {
|
|
|
27
27
|
{ field: "completedAt", hideOnNarrow: true },
|
|
28
28
|
],
|
|
29
29
|
defaultSort: { field: "expiresAt", dir: "desc" },
|
|
30
|
+
// A user bound by authorizeSubject gets no total, so the list pages by cursor.
|
|
31
|
+
pagination: "infinite",
|
|
30
32
|
access,
|
|
31
33
|
searchable: true,
|
|
32
34
|
rowActions: [
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type StaticRequestOptions, type StaticResult } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
|
|
2
|
+
import { SIGNATURE_INVALID_LINK_REASON } from "./web/constants.ts";
|
|
2
3
|
export { hrefWithoutUrlToken, readUrlToken, STATIC_NETWORK_REASON, STATIC_RATE_LIMITED_REASON, type StaticFailure, type StaticRequestOptions, type StaticResult, type StaticSuccess, } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
|
|
3
4
|
export { bytesToBase64, createSignaturePad, type SignaturePad, type SignaturePadCanvas, type SignaturePadOptions, } from "./web/pad.ts";
|
|
5
|
+
export { SIGNATURE_INVALID_LINK_REASON };
|
|
4
6
|
export type SignatureLinkView = {
|
|
5
7
|
readonly title: string;
|
|
6
8
|
readonly signerName: string;
|
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
// a signer receives carries the token in the URL fragment (`#token=`), which browsers never send to a
|
|
3
3
|
// server or in a Referer.
|
|
4
4
|
import { dispatchWrite, staticFailure, staticSuccess, takeUrlToken, } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
|
|
5
|
-
import { SignatureHandlers } from "./web/constants.js";
|
|
5
|
+
import { SIGNATURE_INVALID_LINK_REASON, SignatureHandlers } from "./web/constants.js";
|
|
6
6
|
export { hrefWithoutUrlToken, readUrlToken, STATIC_NETWORK_REASON, STATIC_RATE_LIMITED_REASON, } from "@cosmicdrift/kumiko-bundled-features/auth-email-password/static-client";
|
|
7
7
|
export { bytesToBase64, createSignaturePad, } from "./web/pad.js";
|
|
8
|
+
export { SIGNATURE_INVALID_LINK_REASON };
|
|
8
9
|
/** Reads `#token=` from the current page and removes it from the address bar. Browser only. */
|
|
9
10
|
export function takeSignatureToken() {
|
|
10
11
|
return takeUrlToken("fragment");
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type QueryHandlerDef } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import type { SubjectScope } from "./subject-scope.ts";
|
|
3
|
+
export declare function scopeRequestList(base: QueryHandlerDef, scope: SubjectScope, cursorSecret: string): QueryHandlerDef;
|
|
4
|
+
export declare function scopeRequestDetail(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef;
|
|
5
|
+
export declare function scopeSignerList(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { DEFAULT_LIST_LIMIT, entityListSchema, isUuid, MAX_LIST_LIMIT, } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import { AccessDeniedError } from "@cosmicdrift/kumiko-framework/errors";
|
|
3
|
+
import { requestExecutor } from "./entity.js";
|
|
4
|
+
import { openListCursor, sealListCursor } from "./list-cursor-seal.js";
|
|
5
|
+
function allFilters(payload) {
|
|
6
|
+
return [...(payload.filter === undefined ? [] : [payload.filter]), ...(payload.filters ?? [])];
|
|
7
|
+
}
|
|
8
|
+
function emptyPage(payload) {
|
|
9
|
+
return { rows: [], nextCursor: null, ...(payload.totalCount === true && { total: 0 }) };
|
|
10
|
+
}
|
|
11
|
+
function onlyFilterOn(payload, field) {
|
|
12
|
+
const matching = allFilters(payload).filter((filter) => filter.field === field);
|
|
13
|
+
const [first] = matching;
|
|
14
|
+
return matching.length === 1 && first !== undefined ? first : null;
|
|
15
|
+
}
|
|
16
|
+
function isRowsPage(value) {
|
|
17
|
+
return (typeof value === "object" && value !== null && "rows" in value && Array.isArray(value.rows));
|
|
18
|
+
}
|
|
19
|
+
function subjectKey(subject) {
|
|
20
|
+
return `${String(subject.subjectType)}\u0000${String(subject.subjectId)}`;
|
|
21
|
+
}
|
|
22
|
+
// ponytail: at most this many base pages per answer; a user who may see almost none of the
|
|
23
|
+
// tenant's requests gets short pages and scrolls on. Upgrade to a subject-joined query if that hurts.
|
|
24
|
+
const MAX_BASE_PAGES_PER_ANSWER = 10;
|
|
25
|
+
// authorizeSubject usually queries the database; a page of 200 subjects must not take the whole pool.
|
|
26
|
+
const SUBJECT_CHECKS_IN_PARALLEL = 10;
|
|
27
|
+
async function openFirstQuery(query, payload, user, cursorSecret) {
|
|
28
|
+
const { cursor: sealedCursor, ...payloadWithoutCursor } = payload;
|
|
29
|
+
if (sealedCursor === undefined)
|
|
30
|
+
return query;
|
|
31
|
+
const openedCursor = await openListCursor(sealedCursor, user, cursorSecret);
|
|
32
|
+
if (openedCursor === null)
|
|
33
|
+
throw new AccessDeniedError();
|
|
34
|
+
return { ...query, payload: { ...payloadWithoutCursor, cursor: openedCursor } };
|
|
35
|
+
}
|
|
36
|
+
async function sealedPage(page, visibleRows, nextCursor, user, cursorSecret) {
|
|
37
|
+
// `total` would count requests of foreign subjects. The base cursor names the last base row,
|
|
38
|
+
// which may belong to a foreign subject, so the user only gets it sealed.
|
|
39
|
+
const { total: _total, rows: _rows, nextCursor: _baseCursor, ...rest } = page;
|
|
40
|
+
return {
|
|
41
|
+
...rest,
|
|
42
|
+
rows: visibleRows,
|
|
43
|
+
nextCursor: typeof nextCursor === "string" ? await sealListCursor(nextCursor, user, cursorSecret) : null,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export function scopeRequestList(base, scope, cursorSecret) {
|
|
47
|
+
return {
|
|
48
|
+
...base,
|
|
49
|
+
handler: async (query, ctx) => {
|
|
50
|
+
const user = query.user;
|
|
51
|
+
if (!scope.isScoped(user))
|
|
52
|
+
return base.handler(query, ctx);
|
|
53
|
+
const payload = entityListSchema.parse(query.payload);
|
|
54
|
+
// Group counts would include requests of foreign subjects, and an offset counts base rows,
|
|
55
|
+
// not the rows this user sees; the screen pages by cursor. limit 0 would hand out a cursor
|
|
56
|
+
// without checking a row.
|
|
57
|
+
if (payload.aggregate !== undefined || (payload.offset ?? 0) > 0 || payload.limit === 0) {
|
|
58
|
+
throw new AccessDeniedError();
|
|
59
|
+
}
|
|
60
|
+
const limit = payload.limit ?? DEFAULT_LIST_LIMIT;
|
|
61
|
+
const verdicts = new Map();
|
|
62
|
+
const visibleRows = [];
|
|
63
|
+
const firstQuery = await openFirstQuery(query, payload, user, cursorSecret);
|
|
64
|
+
let page = await base.handler(firstQuery, ctx);
|
|
65
|
+
for (let fetched = 1;; fetched++) {
|
|
66
|
+
if (!isRowsPage(page))
|
|
67
|
+
throw new Error("signature request list did not return a rows page");
|
|
68
|
+
const unknownSubjects = new Map(page.rows
|
|
69
|
+
.map((row) => [subjectKey(subjectOf(row)), subjectOf(row)])
|
|
70
|
+
.filter(([key]) => !verdicts.has(key)));
|
|
71
|
+
const pending = [...unknownSubjects];
|
|
72
|
+
for (let start = 0; start < pending.length; start += SUBJECT_CHECKS_IN_PARALLEL) {
|
|
73
|
+
await Promise.all(pending.slice(start, start + SUBJECT_CHECKS_IN_PARALLEL).map(async ([key, subject]) => {
|
|
74
|
+
verdicts.set(key, await scope.allowsRequest(ctx, user, subject));
|
|
75
|
+
}));
|
|
76
|
+
}
|
|
77
|
+
visibleRows.push(...page.rows.filter((row) => verdicts.get(subjectKey(subjectOf(row)))));
|
|
78
|
+
const nextCursor = page["nextCursor"];
|
|
79
|
+
if (visibleRows.length >= limit ||
|
|
80
|
+
typeof nextCursor !== "string" ||
|
|
81
|
+
fetched >= MAX_BASE_PAGES_PER_ANSWER ||
|
|
82
|
+
verdicts.size >= MAX_LIST_LIMIT) {
|
|
83
|
+
return sealedPage(page, visibleRows, nextCursor, user, cursorSecret);
|
|
84
|
+
}
|
|
85
|
+
page = await base.handler({
|
|
86
|
+
...query,
|
|
87
|
+
payload: { ...payload, cursor: nextCursor, limit: limit - visibleRows.length },
|
|
88
|
+
}, ctx);
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
export function scopeRequestDetail(base, scope) {
|
|
94
|
+
return {
|
|
95
|
+
...base,
|
|
96
|
+
handler: async (query, ctx) => {
|
|
97
|
+
const row = await base.handler(query, ctx);
|
|
98
|
+
if (row === null || !scope.isScoped(query.user))
|
|
99
|
+
return row;
|
|
100
|
+
return (await scope.allowsRequest(ctx, query.user, subjectOf(row))) ? row : null;
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function subjectOf(row) {
|
|
105
|
+
if (typeof row !== "object" || row === null)
|
|
106
|
+
return {};
|
|
107
|
+
return {
|
|
108
|
+
subjectType: "subjectType" in row ? row.subjectType : undefined,
|
|
109
|
+
subjectId: "subjectId" in row ? row.subjectId : undefined,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
export function scopeSignerList(base, scope) {
|
|
113
|
+
return {
|
|
114
|
+
...base,
|
|
115
|
+
handler: async (query, ctx) => {
|
|
116
|
+
const user = query.user;
|
|
117
|
+
if (!scope.isScoped(user))
|
|
118
|
+
return base.handler(query, ctx);
|
|
119
|
+
const payload = entityListSchema.parse(query.payload);
|
|
120
|
+
const requestFilter = onlyFilterOn(payload, "requestId");
|
|
121
|
+
if (requestFilter === null ||
|
|
122
|
+
requestFilter.op !== "eq" ||
|
|
123
|
+
typeof requestFilter.value !== "string") {
|
|
124
|
+
throw new AccessDeniedError();
|
|
125
|
+
}
|
|
126
|
+
if (!isUuid(requestFilter.value))
|
|
127
|
+
return emptyPage(payload);
|
|
128
|
+
const request = await requestExecutor.detail({ id: requestFilter.value }, user, ctx.db);
|
|
129
|
+
if (request === null || !(await scope.allowsRequest(ctx, user, request))) {
|
|
130
|
+
return emptyPage(payload);
|
|
131
|
+
}
|
|
132
|
+
return base.handler(query, ctx);
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { HandlerContext, SessionUser } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import type { SignatureOptions } from "./options.ts";
|
|
3
|
+
export type SubjectScope = {
|
|
4
|
+
isScoped(user: SessionUser): boolean;
|
|
5
|
+
allows(ctx: HandlerContext, user: SessionUser, subjectType: unknown, subjectId: unknown): Promise<boolean>;
|
|
6
|
+
allowsRequest(ctx: HandlerContext, user: SessionUser, request: {
|
|
7
|
+
readonly subjectType?: unknown;
|
|
8
|
+
readonly subjectId?: unknown;
|
|
9
|
+
}): Promise<boolean>;
|
|
10
|
+
};
|
|
11
|
+
export declare function createSubjectScope(opts: Pick<SignatureOptions, "authorizeSubject" | "unscopedRoles">): SubjectScope;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
function isNonEmptyString(value) {
|
|
2
|
+
return typeof value === "string" && value !== "";
|
|
3
|
+
}
|
|
4
|
+
export function createSubjectScope(opts) {
|
|
5
|
+
const { authorizeSubject } = opts;
|
|
6
|
+
const unscopedRoles = opts.unscopedRoles ?? [];
|
|
7
|
+
const isScoped = (user) => authorizeSubject !== undefined && !user.roles.some((role) => unscopedRoles.includes(role));
|
|
8
|
+
const allows = async (ctx, user, subjectType, subjectId) => {
|
|
9
|
+
if (authorizeSubject === undefined || !isScoped(user))
|
|
10
|
+
return true;
|
|
11
|
+
if (!isNonEmptyString(subjectType) || !isNonEmptyString(subjectId))
|
|
12
|
+
return false;
|
|
13
|
+
return authorizeSubject(ctx, user, { subjectType, subjectId });
|
|
14
|
+
};
|
|
15
|
+
return {
|
|
16
|
+
isScoped,
|
|
17
|
+
allows,
|
|
18
|
+
allowsRequest: (ctx, user, request) => allows(ctx, user, request.subjectType, request.subjectId),
|
|
19
|
+
};
|
|
20
|
+
}
|
package/dist/signature/sweep.js
CHANGED
|
@@ -4,7 +4,7 @@ import { requestExecutor } from "./entity.js";
|
|
|
4
4
|
import { discardGeneratedFile, PDF_MIME_TYPE, readTenantFile, sha256Hex, storeGeneratedFile, } from "./files.js";
|
|
5
5
|
import { instantOrNull, isPastInstant, listSigners, } from "./lib.js";
|
|
6
6
|
import { appendPdfPages, buildSignaturePageHtml, DEFAULT_SIGNATURE_PAGE_LABELS, } from "./signature-page.js";
|
|
7
|
-
import { SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS, SignatureInternalHandlers, } from "./web/constants.js";
|
|
7
|
+
import { SIGNATURE_FAILURE_REASON, SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS, SignatureInternalHandlers, } from "./web/constants.js";
|
|
8
8
|
// Equals the executor's MAX_LIST_LIMIT.
|
|
9
9
|
const SWEEP_PAGE_SIZE = 200;
|
|
10
10
|
// Keyset-paged, so rows that leave the status while the sweep works on them cannot shift the next page.
|
|
@@ -47,21 +47,38 @@ async function signaturePageEntries(ctx, signers) {
|
|
|
47
47
|
}
|
|
48
48
|
return entries;
|
|
49
49
|
}
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
async function failRequest(ctx, request, reason) {
|
|
51
|
+
const failed = await ctx.dispatch.write(SignatureInternalHandlers.fail, {
|
|
52
|
+
requestId: request.id,
|
|
53
|
+
reason,
|
|
54
|
+
});
|
|
55
|
+
if (!failed.isSuccess) {
|
|
56
|
+
ctx.obs.log.error("[signature:sweep] marking the request failed was rejected", {
|
|
57
|
+
requestId: request.id,
|
|
58
|
+
reason,
|
|
59
|
+
error: failed.error,
|
|
60
|
+
});
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (propertyOf(failed.data, "failed") === true) {
|
|
64
|
+
ctx.obs.log.warn("[signature:sweep] request cannot be completed, marked failed", {
|
|
65
|
+
requestId: request.id,
|
|
66
|
+
reason,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
// Appends the signature page to the unchanged original. A missing or changed original or a
|
|
71
|
+
// missing signature image can never heal and ends the request as failed. A renderer outage
|
|
72
|
+
// throws, the request stays all-signed and the next run tries again.
|
|
52
73
|
async function finalizeRequest(ctx, opts, request) {
|
|
53
74
|
const original = await readTenantFile(ctx, ctx.systemUser.tenantId, request.documentFileId);
|
|
54
75
|
if (original === null || sha256Hex(original.content) !== request.documentSha256) {
|
|
55
|
-
ctx
|
|
56
|
-
requestId: request.id,
|
|
57
|
-
});
|
|
76
|
+
await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.DocumentChanged);
|
|
58
77
|
return;
|
|
59
78
|
}
|
|
60
79
|
const entries = await signaturePageEntries(ctx, await listSigners(ctx, ctx.systemUser, request.id));
|
|
61
80
|
if (entries === null) {
|
|
62
|
-
ctx
|
|
63
|
-
requestId: request.id,
|
|
64
|
-
});
|
|
81
|
+
await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.SignatureImageMissing);
|
|
65
82
|
return;
|
|
66
83
|
}
|
|
67
84
|
const html = buildSignaturePageHtml({
|
|
@@ -11,6 +11,7 @@ export declare const SIGNATURE_REQUEST_STATUS: {
|
|
|
11
11
|
readonly Completed: "completed";
|
|
12
12
|
readonly Declined: "declined";
|
|
13
13
|
readonly Expired: "expired";
|
|
14
|
+
readonly Failed: "failed";
|
|
14
15
|
readonly Cancelled: "cancelled";
|
|
15
16
|
};
|
|
16
17
|
export type SignatureRequestStatus = (typeof SIGNATURE_REQUEST_STATUS)[keyof typeof SIGNATURE_REQUEST_STATUS];
|
|
@@ -48,11 +49,18 @@ export declare const SIGNATURE_EVENT_SHORT: {
|
|
|
48
49
|
readonly completed: "completed";
|
|
49
50
|
readonly declined: "declined";
|
|
50
51
|
readonly expired: "expired";
|
|
52
|
+
readonly failed: "failed";
|
|
51
53
|
};
|
|
54
|
+
export declare const SIGNATURE_FAILURE_REASON: {
|
|
55
|
+
readonly DocumentChanged: "document-changed";
|
|
56
|
+
readonly SignatureImageMissing: "signature-image-missing";
|
|
57
|
+
};
|
|
58
|
+
export type SignatureFailureReason = (typeof SIGNATURE_FAILURE_REASON)[keyof typeof SIGNATURE_FAILURE_REASON];
|
|
52
59
|
export declare const SignatureEvents: {
|
|
53
60
|
readonly completed: "signature:event:completed";
|
|
54
61
|
readonly declined: "signature:event:declined";
|
|
55
62
|
readonly expired: "signature:event:expired";
|
|
63
|
+
readonly failed: "signature:event:failed";
|
|
56
64
|
};
|
|
57
65
|
export declare const SIGNATURE_INVALID_LINK_REASON = "invalid_or_expired_link";
|
|
58
66
|
export declare const SIGNATURE_INVALID_IMAGE_REASON = "invalid_signature_image";
|
|
@@ -65,5 +73,6 @@ export declare const SignatureInternalHandlers: {
|
|
|
65
73
|
readonly linkDecline: "signature:write:link-decline";
|
|
66
74
|
readonly finish: "signature:write:finish";
|
|
67
75
|
readonly expire: "signature:write:expire";
|
|
76
|
+
readonly fail: "signature:write:fail";
|
|
68
77
|
readonly reconcile: "signature:write:reconcile";
|
|
69
78
|
};
|
|
@@ -11,6 +11,7 @@ export const SIGNATURE_REQUEST_STATUS = {
|
|
|
11
11
|
Completed: "completed",
|
|
12
12
|
Declined: "declined",
|
|
13
13
|
Expired: "expired",
|
|
14
|
+
Failed: "failed",
|
|
14
15
|
Cancelled: "cancelled",
|
|
15
16
|
};
|
|
16
17
|
export const SIGNATURE_SIGNER_STATUS = {
|
|
@@ -45,11 +46,17 @@ export const SIGNATURE_EVENT_SHORT = {
|
|
|
45
46
|
completed: "completed",
|
|
46
47
|
declined: "declined",
|
|
47
48
|
expired: "expired",
|
|
49
|
+
failed: "failed",
|
|
50
|
+
};
|
|
51
|
+
export const SIGNATURE_FAILURE_REASON = {
|
|
52
|
+
DocumentChanged: "document-changed",
|
|
53
|
+
SignatureImageMissing: "signature-image-missing",
|
|
48
54
|
};
|
|
49
55
|
export const SignatureEvents = {
|
|
50
56
|
completed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.completed}`,
|
|
51
57
|
declined: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.declined}`,
|
|
52
58
|
expired: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.expired}`,
|
|
59
|
+
failed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.failed}`,
|
|
53
60
|
};
|
|
54
61
|
// Every link rejection (forged, expired, revoked, used up, already signed) carries this reason, so
|
|
55
62
|
// a caller cannot tell the cases apart.
|
|
@@ -64,5 +71,6 @@ export const SignatureInternalHandlers = {
|
|
|
64
71
|
linkDecline: `${SIGNATURE_FEATURE}:write:link-decline`,
|
|
65
72
|
finish: `${SIGNATURE_FEATURE}:write:finish`,
|
|
66
73
|
expire: `${SIGNATURE_FEATURE}:write:expire`,
|
|
74
|
+
fail: `${SIGNATURE_FEATURE}:write:fail`,
|
|
67
75
|
reconcile: `${SIGNATURE_FEATURE}:write:reconcile`,
|
|
68
76
|
};
|
|
@@ -111,6 +111,8 @@ export function createStripeCheckoutSession(runtime, { paymentInvoiceCreation =
|
|
|
111
111
|
...(mode === "subscription"
|
|
112
112
|
? { subscription_data: { metadata } }
|
|
113
113
|
: {
|
|
114
|
+
// Session metadata too: a 100% promotion code completes without a PaymentIntent.
|
|
115
|
+
metadata,
|
|
114
116
|
payment_intent_data: { metadata },
|
|
115
117
|
invoice_creation: { enabled: paymentInvoiceCreation },
|
|
116
118
|
// Without a customer, Stripe's default "if_required" makes a guest
|