@arbidocs/react 0.5.194 → 0.5.196
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/account/identity.js +5 -2
- package/dist/account/identity.js.map +2 -2
- package/dist/{chunk-XQIUGZPV.cjs → chunk-3LIPVECC.cjs} +27 -25
- package/dist/chunk-3LIPVECC.cjs.map +1 -0
- package/dist/{chunk-4LFADBRL.cjs → chunk-SYGC6Z5B.cjs} +19 -3
- package/dist/chunk-SYGC6Z5B.cjs.map +1 -0
- package/dist/document-tools/core.cjs +98 -98
- package/dist/document-tools/core.d.ts +4 -2
- package/dist/document-tools/file-shares.js +3 -1
- package/dist/document-tools/file-shares.js.map +2 -2
- package/dist/document-tools/index.cjs +100 -100
- package/dist/document-tools/signature-requests.js +5 -3
- package/dist/document-tools/signature-requests.js.map +2 -2
- package/dist/document-tools/signing.js +16 -1
- package/dist/document-tools/signing.js.map +2 -2
- package/dist/index.cjs +14 -11
- package/dist/index.cjs.map +1 -1
- package/dist/{index.d-BR7SVl6A.d.ts → index.d-BWfM5sah.d.ts} +6 -0
- package/dist/index.d.ts +2 -2
- package/dist/ui/index.d.ts +1 -1
- package/package.json +3 -3
- package/dist/chunk-4LFADBRL.cjs.map +0 -1
- package/dist/chunk-XQIUGZPV.cjs.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/document-tools/signature-requests.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Signature requests: an author places fields (signature, initials, date, name) on the PDF of one\n * exact document version and assigns each to a signer: a workspace member (a guest too), or anyone\n * by email, who is invited to the workspace and signs once they join. A Word document's own\n * signature fields (Insert \u203A Signature field) come back from `suggest` placed exactly, with their\n * signer (`source: 'anchor'`). Each signer is then walked\n * through their fields, adopts a signature once and applies it at each. They sign ONCE for all of\n * their fields: the server's statement binds the PDF they were shown, every field they applied and\n * what they adopted. The last signature draws every field and seals the signed copy as the\n * document's next version (see `src/core/signature_requests.py` in ARBI).\n */\n\nimport { signMessage, unlockIdentityWithPassword, type components } from '@arbidocs/client'\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'\nimport { workspaces } from '@arbidocs/sdk/browser'\nimport { useDocumentTools, type DocumentToolsClient } from './environment'\nimport { intentText, sha256Hex, SigningError } from './signing'\nimport { arbiQueryKeys } from '../query-keys'\nimport { useArbiHost } from '../host/config'\n\n/**\n * The open workspace, when the host has an `Arbi` with one, and a guard that keeps a read made for\n * it only if that workspace stayed open on the server meanwhile (these lists are the open\n * workspace's there): a read that crosses a switch is dropped, never cached as another's.\n */\nfunction useOpenWorkspaceRead() {\n const arbi = useArbiHost().arbi\n const workspaceId = arbi?.hasWorkspace ? arbi.getWorkspaceId() : undefined\n const read = <T>(run: () => Promise<T>): Promise<T> =>\n arbi && workspaceId ? arbi.readInWorkspace(workspaceId, run) : run()\n return { workspaceId, read }\n}\n\nexport type SignatureField = components['schemas']['SignatureField']\nexport type SignatureFieldType = SignatureField['type']\nexport type SignatureRequest = components['schemas']['SignatureRequestResponse']\nexport type SignatureRequestSigner = components['schemas']['SignatureRequestSigner']\nexport type SignerProgress = components['schemas']['SignerProgress']\nexport type SuggestedSignatureField = components['schemas']['SuggestedSignatureField']\nexport type AdoptedSignature = components['schemas']['AdoptedSignature']\nexport type SignRequestSignResponse = components['schemas']['SignRequestSignResponse']\n\n/** Field types in the order the editor offers them. */\nexport const SIGNATURE_FIELD_TYPES: readonly SignatureFieldType[] = [\n 'signature',\n 'initials',\n 'date',\n 'name',\n]\n\nexport const FIELD_TYPE_LABELS: Record<SignatureFieldType, string> = {\n signature: 'Signature',\n initials: 'Initials',\n date: 'Date signed',\n name: 'Name',\n}\n\n/**\n * Default size of a new field, as fractions of the page (the backend draws to fit the box). The\n * same sizes the server's suggester places fields in (`esign_suggest._SIZE`).\n */\nexport const DEFAULT_FIELD_SIZE: Record<SignatureFieldType, { width: number; height: number }> = {\n signature: { width: 0.28, height: 0.05 },\n initials: { width: 0.1, height: 0.04 },\n date: { width: 0.22, height: 0.028 },\n name: { width: 0.28, height: 0.028 },\n}\n\n/** How far each signer has got, as the request's sender sees it. */\nexport const SIGNER_PROGRESS_LABELS: Record<SignerProgress, string> = {\n invited: 'Invited',\n registered: 'Not opened yet',\n viewed: 'Viewed',\n signed: 'Signed',\n declined: 'Declined',\n}\n\nconst EMAIL = /^[^@\\s<>,;]{1,64}@[^@\\s<>,;]{1,255}\\.[^@\\s<>,;]{1,63}$/\n\n/** Whether a field's signer is an email (someone to invite) rather than a member or request signer. */\nexport const isEmailSigner = (signer: string) => EMAIL.test(signer.trim())\n\n/** The fields carrying a signer's mark: every signer needs at least one to be sent the request. */\nexport const MARK_FIELD_TYPES: readonly SignatureFieldType[] = ['signature', 'initials']\n\nfunction detail(error: unknown, fallback: string): string {\n const d = (error as { detail?: unknown } | undefined)?.detail\n if (typeof d === 'string') return d\n if (Array.isArray(d) && d[0] && typeof d[0] === 'object' && 'msg' in d[0]) {\n return String((d[0] as { msg: unknown }).msg)\n }\n return fallback\n}\n\n/** A short unique id for a new field (the server only needs it unique within the request). */\nexport function newFieldId(): string {\n return `f${Math.random().toString(36).slice(2, 10)}`\n}\n\n/** Initials from a name: \"Olive M. Owner\" -> \"OMO\". */\nexport function initialsOf(name: string): string {\n return name\n .split(/\\s+/)\n .filter(Boolean)\n .map((part) => part[0]!.toUpperCase())\n .join('')\n .slice(0, 4)\n}\n\n/** The fields a signer completes, in the order they are walked through: page, then top to bottom. */\nexport function fieldsInSigningOrder(fields: SignatureField[], signer: string): SignatureField[] {\n return fields\n .filter((f) => f.signer === signer)\n .sort((a, b) => a.page - b.page || a.y - b.y || a.x - b.x)\n}\n\n/** Why a draft cannot be sent yet, or null when it can. Mirrors the server's checks. */\nexport function sendBlocker(fields: SignatureField[]): string | null {\n if (fields.length === 0) return 'Place at least one field.'\n const signers = [...new Set(fields.map((f) => f.signer))]\n for (const signer of signers) {\n if (!fields.some((f) => f.signer === signer && MARK_FIELD_TYPES.includes(f.type))) {\n return 'Every signer needs a signature or initials field.'\n }\n }\n return null\n}\n\n/**\n * Suggested fields grouped by signature block; `assign` maps a block (`group`) to the signer its\n * fields go to. A field placed in the Word document that names its signer goes to them: the\n * member with that email (`members`, by lowercased email), else the email itself (an invitee).\n * Unassigned blocks are left out.\n */\nexport function fieldsFromSuggestions(\n suggestions: SuggestedSignatureField[],\n assign: Record<number, string | undefined>,\n members: ReadonlyMap<string, string> = new Map()\n): SignatureField[] {\n return suggestions.flatMap((s) => {\n const email = s.signer_email?.toLowerCase()\n const signer = email ? (members.get(email) ?? email) : assign[s.group]\n if (!signer) return []\n return [\n {\n id: newFieldId(),\n type: s.type,\n page: s.page,\n x: s.x,\n y: s.y,\n width: s.width,\n height: s.height,\n signer,\n required: s.required ?? true,\n },\n ]\n })\n}\n\n/** The Word document's own fields (found by their anchors) and the optional layout suggestions. */\nexport function splitSuggestions(suggestions: SuggestedSignatureField[]) {\n return {\n placed: suggestions.filter((s) => s.source === 'anchor'),\n extras: suggestions.filter((s) => s.source !== 'anchor'),\n }\n}\n\n// \u2500\u2500 Reads \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport async function fetchDocumentSignatureRequests(\n client: DocumentToolsClient,\n documentId: string\n): Promise<SignatureRequest[]> {\n const { data, error } = await client.GET('/v1/document/{document_ext_id}/signature-requests', {\n params: { path: { document_ext_id: documentId } },\n })\n if (!data) throw new Error(detail(error, 'The signature requests could not be read'))\n return data\n}\n\n/** A document's signature requests, newest first. */\nexport function useDocumentSignatureRequests(\n documentId: string | null | undefined,\n enabled = true\n) {\n const { client } = useDocumentTools()\n return useQuery({\n queryKey: arbiQueryKeys.signatureRequestsForDocument(documentId ?? ''),\n queryFn: () => fetchDocumentSignatureRequests(client, documentId!),\n enabled: enabled && !!documentId,\n staleTime: 15_000,\n })\n}\n\n/** A signer the Word document's placed fields name, with the name they give. */\nexport interface NamedSigner {\n email: string\n name: string\n}\n\n/** What a document asks to be signed: the fields found, and the signers its Word fields name. */\nexport interface SignatureFieldSuggestions {\n fields: SuggestedSignatureField[]\n /**\n * Named even when the PDF shows none of the Word fields' anchors (the fields are then placed by\n * hand): who each email belongs to. Empty from a server that does not report them.\n */\n signers: NamedSigner[]\n}\n\nexport async function signatureFieldSuggestions(\n client: DocumentToolsClient,\n documentId: string,\n version?: number\n): Promise<SignatureFieldSuggestions> {\n const { data, error } = await client.GET(\n '/v1/document/{document_ext_id}/signature-fields/suggest',\n {\n params: { path: { document_ext_id: documentId }, ...(version ? { query: { version } } : {}) },\n }\n )\n if (!data) throw new Error(detail(error, 'Signature blocks could not be read'))\n return { fields: data.fields, signers: (data as { signers?: NamedSigner[] }).signers ?? [] }\n}\n\nexport async function suggestSignatureFields(\n client: DocumentToolsClient,\n documentId: string,\n version?: number\n): Promise<SuggestedSignatureField[]> {\n return (await signatureFieldSuggestions(client, documentId, version)).fields\n}\n\n// \u2500\u2500 Prepare \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface SaveSignatureRequestVars {\n documentId: string\n /** The version the fields were placed on (the PDF shown). Omitted = current. */\n version?: number\n fields: SignatureField[]\n message?: string\n /** Existing draft to update instead of creating a new request. */\n requestId?: string\n /** Send it to the signers (else it is saved as a draft). */\n send: boolean\n}\n\nexport async function saveSignatureRequest(\n client: DocumentToolsClient,\n { documentId, version, fields, message, requestId, send }: SaveSignatureRequestVars\n): Promise<SignatureRequest> {\n if (!requestId) {\n const { data, error } = await client.POST('/v1/document/{document_ext_id}/signature-requests', {\n params: { path: { document_ext_id: documentId } },\n body: { fields, message: message || null, send, ...(version ? { version } : {}) },\n })\n if (!data) throw new Error(detail(error, 'The signature request could not be saved'))\n return data\n }\n const path = { request_ext_id: requestId }\n const updated = await client.PATCH('/v1/signature-requests/{request_ext_id}', {\n params: { path },\n body: { fields, message: message ?? null },\n })\n if (!updated.data) throw new Error(detail(updated.error, 'The draft could not be saved'))\n if (!send) return updated.data\n const sent = await client.POST('/v1/signature-requests/{request_ext_id}/send', {\n params: { path },\n })\n if (!sent.data) throw new Error(detail(sent.error, 'The request could not be sent'))\n return sent.data\n}\n\nfunction useInvalidateRequests() {\n const queryClient = useQueryClient()\n return () => queryClient.invalidateQueries({ queryKey: arbiQueryKeys.signatureRequests() })\n}\n\nexport function useSaveSignatureRequest() {\n const { client } = useDocumentTools()\n const invalidate = useInvalidateRequests()\n return useMutation({\n mutationFn: (vars: SaveSignatureRequestVars) => saveSignatureRequest(client, vars),\n onSuccess: invalidate,\n })\n}\n\nexport function useVoidSignatureRequest() {\n const { client } = useDocumentTools()\n const invalidate = useInvalidateRequests()\n return useMutation({\n mutationFn: async (requestId: string) => {\n const { data, error } = await client.POST('/v1/signature-requests/{request_ext_id}/void', {\n params: { path: { request_ext_id: requestId } },\n })\n if (!data) throw new Error(detail(error, 'The request could not be voided'))\n return data\n },\n onSuccess: invalidate,\n })\n}\n\nexport function useDeclineSignatureRequest() {\n const { client } = useDocumentTools()\n const invalidate = useInvalidateRequests()\n return useMutation({\n mutationFn: async ({ requestId, reason }: { requestId: string; reason?: string }) => {\n const { data, error } = await client.POST('/v1/signature-requests/{request_ext_id}/decline', {\n params: { path: { request_ext_id: requestId } },\n body: { reason: reason || null },\n })\n if (!data) throw new Error(detail(error, 'Could not decline'))\n return data\n },\n onSuccess: invalidate,\n })\n}\n\n// \u2500\u2500 Sign \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface SignRequestVars {\n request: SignatureRequest\n /** The PDF the signer was walked through (`GET /view?version=` of the request's version). */\n pdfBlob: Blob\n email: string\n password: string\n adopted: AdoptedSignature\n /** The ids of the fields the signer applied: every required one of theirs. */\n fields: string[]\n}\n\n/**\n * Sign all of the signer's fields at once: the server prepares the statement, the browser checks\n * it covers the PDF on screen under the wording the signer read, re-derives the Ed25519 key from\n * the password and signs. Resolves with `completed` when this was the last signature.\n */\nexport async function signSignatureRequest(\n client: DocumentToolsClient,\n deploymentDomain: string,\n { request, pdfBlob, email, password, adopted, fields }: SignRequestVars\n): Promise<SignRequestSignResponse> {\n const path = { request_ext_id: request.external_id }\n const body = { adopted, fields }\n const prepared = await client.POST('/v1/signature-requests/{request_ext_id}/sign/prepare', {\n params: { path },\n body,\n })\n if (!prepared.data) {\n throw new SigningError(detail(prepared.error, 'Could not prepare signing'), 'failed')\n }\n const { statement, intent, source_sha256, timestamp } = prepared.data\n if (source_sha256 !== request.source_sha256 || (await sha256Hex(pdfBlob)) !== source_sha256) {\n throw new SigningError('The document changed since it was sent. Ask for it again.', 'stale')\n }\n if (intent !== intentText({ name: adopted.name })) {\n throw new Error('Signing statement mismatch; not signed.')\n }\n const identity = await unlockIdentityWithPassword(email, password, deploymentDomain)\n const signed = await client.POST('/v1/signature-requests/{request_ext_id}/sign', {\n params: { path },\n body: { ...body, timestamp, signature: signMessage(statement, identity) },\n })\n if (!signed.data) throw new SigningError(detail(signed.error, 'Signing failed'), 'failed')\n return signed.data\n}\n\nexport function useSignSignatureRequest() {\n const env = useDocumentTools()\n const invalidate = useInvalidateRequests()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: (vars: SignRequestVars) => {\n if (!env.deploymentDomain) throw new Error('Signing is not set up: no deployment domain')\n return signSignatureRequest(env.client, env.deploymentDomain, vars)\n },\n onSuccess: async (result) => {\n await invalidate()\n if (result.completed && result.request.doc_ext_id) {\n await env.onDocumentsChanged?.([result.request.doc_ext_id], 'signed')\n await queryClient.invalidateQueries({ queryKey: arbiQueryKeys.documentSignatures() })\n }\n },\n })\n}\n\n// \u2500\u2500 Who can sign \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface SignerCandidate {\n externalId: string\n name: string\n email: string\n role: string\n}\n\n/**\n * The people in the active workspace who may sign: owners, collaborators and guests (an agent never\n * does). The first one listed is the current user when they are a member.\n */\nexport function useSignerCandidates(enabled = true) {\n const { client, user } = useDocumentTools()\n const { workspaceId, read } = useOpenWorkspaceRead()\n return useQuery({\n queryKey: arbiQueryKeys.signatureCandidates(workspaceId ?? ''),\n queryFn: async (): Promise<SignerCandidate[]> => {\n const { data, error } = await read(() => client.GET('/v1/workspace/users'))\n if (!data) throw new Error(detail(error, 'The workspace members could not be read'))\n const people = data\n .filter((m) => m.user.external_id.startsWith('usr-'))\n .map((m) => ({\n externalId: m.user.external_id,\n name: [m.user.given_name, m.user.family_name].filter(Boolean).join(' ') || m.user.email,\n email: m.user.email,\n role: String(m.role),\n }))\n const me = user?.email?.toLowerCase()\n return [...people].sort(\n (a, b) => Number(b.email.toLowerCase() === me) - Number(a.email.toLowerCase() === me)\n )\n },\n enabled,\n staleTime: 60_000,\n })\n}\n\n// \u2500\u2500 Invite \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Invite signers who are not in the workspace yet, as guests, through the workspace's own invite\n * (`POST /v1/workspace/users` with `confirm_invite`): a registered person is added at once, anyone\n * else is emailed an invitation that lands on the document. Each is asked to sign when they join.\n * Only a workspace owner can invite.\n */\nexport async function inviteSigners(\n client: DocumentToolsClient,\n documentId: string,\n emails: string[]\n): Promise<void> {\n if (!emails.length) return\n const { error, response } = await client.POST('/v1/workspace/users', {\n body: workspaces.addWorkspaceMembersBody({\n emails,\n role: 'guest',\n confirm_invite: true,\n resource_type: 'document',\n resource_ext_id: documentId,\n }),\n })\n if (response.status === 409) {\n throw new Error('Share the document with the workspace before asking others to sign it.')\n }\n // 404 \"No users found to add\": everyone is a member already (nothing to do).\n if (error && response.status !== 404) {\n throw new Error(detail(error, 'The signers could not be invited'))\n }\n}\n\nexport function useInviteSigners() {\n const { client } = useDocumentTools()\n const invalidate = useInvalidateRequests()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: ({ documentId, emails }: { documentId: string; emails: string[] }) =>\n inviteSigners(client, documentId, emails),\n onSuccess: async () => {\n await invalidate()\n await queryClient.invalidateQueries({ queryKey: arbiQueryKeys.signatureCandidates() })\n },\n })\n}\n"],
|
|
5
|
-
"mappings": "AAYA,SAAS,aAAa,kCAAmD;AACzE,SAAS,aAAa,UAAU,sBAAsB;AACtD,SAAS,kBAAkB;AAC3B,SAAS,wBAAkD;AAC3D,SAAS,YAAY,WAAW,oBAAoB;
|
|
4
|
+
"sourcesContent": ["/**\n * Signature requests: an author places fields (signature, initials, date, name) on the PDF of one\n * exact document version and assigns each to a signer: a workspace member (a guest too), or anyone\n * by email, who is invited to the workspace and signs once they join. A Word document's own\n * signature fields (Insert \u203A Signature field) come back from `suggest` placed exactly, with their\n * signer (`source: 'anchor'`). Each signer is then walked\n * through their fields, adopts a signature once and applies it at each. They sign ONCE for all of\n * their fields: the server's statement binds the PDF they were shown, every field they applied and\n * what they adopted. The last signature draws every field and seals the signed copy as the\n * document's next version (see `src/core/signature_requests.py` in ARBI).\n */\n\nimport { signMessage, unlockIdentityWithPassword, type components } from '@arbidocs/client'\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'\nimport { workspaces } from '@arbidocs/sdk/browser'\nimport { useDocumentTools, type DocumentToolsClient } from './environment'\nimport { identityRefusal, intentText, sha256Hex, SigningError } from './signing'\nimport { arbiQueryKeys } from '../query-keys'\nimport { useArbiHost } from '../host/config'\n\n/**\n * The open workspace, when the host has an `Arbi` with one, and a guard that keeps a read made for\n * it only if that workspace stayed open on the server meanwhile (these lists are the open\n * workspace's there): a read that crosses a switch is dropped, never cached as another's.\n */\nfunction useOpenWorkspaceRead() {\n const arbi = useArbiHost().arbi\n const workspaceId = arbi?.hasWorkspace ? arbi.getWorkspaceId() : undefined\n const read = <T>(run: () => Promise<T>): Promise<T> =>\n arbi && workspaceId ? arbi.readInWorkspace(workspaceId, run) : run()\n return { workspaceId, read }\n}\n\nexport type SignatureField = components['schemas']['SignatureField']\nexport type SignatureFieldType = SignatureField['type']\nexport type SignatureRequest = components['schemas']['SignatureRequestResponse']\nexport type SignatureRequestSigner = components['schemas']['SignatureRequestSigner']\nexport type SignerProgress = components['schemas']['SignerProgress']\nexport type SuggestedSignatureField = components['schemas']['SuggestedSignatureField']\nexport type AdoptedSignature = components['schemas']['AdoptedSignature']\nexport type SignRequestSignResponse = components['schemas']['SignRequestSignResponse']\n\n/** Field types in the order the editor offers them. */\nexport const SIGNATURE_FIELD_TYPES: readonly SignatureFieldType[] = [\n 'signature',\n 'initials',\n 'date',\n 'name',\n]\n\nexport const FIELD_TYPE_LABELS: Record<SignatureFieldType, string> = {\n signature: 'Signature',\n initials: 'Initials',\n date: 'Date signed',\n name: 'Name',\n}\n\n/**\n * Default size of a new field, as fractions of the page (the backend draws to fit the box). The\n * same sizes the server's suggester places fields in (`esign_suggest._SIZE`).\n */\nexport const DEFAULT_FIELD_SIZE: Record<SignatureFieldType, { width: number; height: number }> = {\n signature: { width: 0.28, height: 0.05 },\n initials: { width: 0.1, height: 0.04 },\n date: { width: 0.22, height: 0.028 },\n name: { width: 0.28, height: 0.028 },\n}\n\n/** How far each signer has got, as the request's sender sees it. */\nexport const SIGNER_PROGRESS_LABELS: Record<SignerProgress, string> = {\n invited: 'Invited',\n registered: 'Not opened yet',\n viewed: 'Viewed',\n signed: 'Signed',\n declined: 'Declined',\n}\n\nconst EMAIL = /^[^@\\s<>,;]{1,64}@[^@\\s<>,;]{1,255}\\.[^@\\s<>,;]{1,63}$/\n\n/** Whether a field's signer is an email (someone to invite) rather than a member or request signer. */\nexport const isEmailSigner = (signer: string) => EMAIL.test(signer.trim())\n\n/** The fields carrying a signer's mark: every signer needs at least one to be sent the request. */\nexport const MARK_FIELD_TYPES: readonly SignatureFieldType[] = ['signature', 'initials']\n\nfunction detail(error: unknown, fallback: string): string {\n const d = (error as { detail?: unknown } | undefined)?.detail\n if (typeof d === 'string') return d\n if (Array.isArray(d) && d[0] && typeof d[0] === 'object' && 'msg' in d[0]) {\n return String((d[0] as { msg: unknown }).msg)\n }\n return fallback\n}\n\n/** A short unique id for a new field (the server only needs it unique within the request). */\nexport function newFieldId(): string {\n return `f${Math.random().toString(36).slice(2, 10)}`\n}\n\n/** Initials from a name: \"Olive M. Owner\" -> \"OMO\". */\nexport function initialsOf(name: string): string {\n return name\n .split(/\\s+/)\n .filter(Boolean)\n .map((part) => part[0]!.toUpperCase())\n .join('')\n .slice(0, 4)\n}\n\n/** The fields a signer completes, in the order they are walked through: page, then top to bottom. */\nexport function fieldsInSigningOrder(fields: SignatureField[], signer: string): SignatureField[] {\n return fields\n .filter((f) => f.signer === signer)\n .sort((a, b) => a.page - b.page || a.y - b.y || a.x - b.x)\n}\n\n/** Why a draft cannot be sent yet, or null when it can. Mirrors the server's checks. */\nexport function sendBlocker(fields: SignatureField[]): string | null {\n if (fields.length === 0) return 'Place at least one field.'\n const signers = [...new Set(fields.map((f) => f.signer))]\n for (const signer of signers) {\n if (!fields.some((f) => f.signer === signer && MARK_FIELD_TYPES.includes(f.type))) {\n return 'Every signer needs a signature or initials field.'\n }\n }\n return null\n}\n\n/**\n * Suggested fields grouped by signature block; `assign` maps a block (`group`) to the signer its\n * fields go to. A field placed in the Word document that names its signer goes to them: the\n * member with that email (`members`, by lowercased email), else the email itself (an invitee).\n * Unassigned blocks are left out.\n */\nexport function fieldsFromSuggestions(\n suggestions: SuggestedSignatureField[],\n assign: Record<number, string | undefined>,\n members: ReadonlyMap<string, string> = new Map()\n): SignatureField[] {\n return suggestions.flatMap((s) => {\n const email = s.signer_email?.toLowerCase()\n const signer = email ? (members.get(email) ?? email) : assign[s.group]\n if (!signer) return []\n return [\n {\n id: newFieldId(),\n type: s.type,\n page: s.page,\n x: s.x,\n y: s.y,\n width: s.width,\n height: s.height,\n signer,\n required: s.required ?? true,\n },\n ]\n })\n}\n\n/** The Word document's own fields (found by their anchors) and the optional layout suggestions. */\nexport function splitSuggestions(suggestions: SuggestedSignatureField[]) {\n return {\n placed: suggestions.filter((s) => s.source === 'anchor'),\n extras: suggestions.filter((s) => s.source !== 'anchor'),\n }\n}\n\n// \u2500\u2500 Reads \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport async function fetchDocumentSignatureRequests(\n client: DocumentToolsClient,\n documentId: string\n): Promise<SignatureRequest[]> {\n const { data, error } = await client.GET('/v1/document/{document_ext_id}/signature-requests', {\n params: { path: { document_ext_id: documentId } },\n })\n if (!data) throw new Error(detail(error, 'The signature requests could not be read'))\n return data\n}\n\n/** A document's signature requests, newest first. */\nexport function useDocumentSignatureRequests(\n documentId: string | null | undefined,\n enabled = true\n) {\n const { client } = useDocumentTools()\n return useQuery({\n queryKey: arbiQueryKeys.signatureRequestsForDocument(documentId ?? ''),\n queryFn: () => fetchDocumentSignatureRequests(client, documentId!),\n enabled: enabled && !!documentId,\n staleTime: 15_000,\n })\n}\n\n/** A signer the Word document's placed fields name, with the name they give. */\nexport interface NamedSigner {\n email: string\n name: string\n}\n\n/** What a document asks to be signed: the fields found, and the signers its Word fields name. */\nexport interface SignatureFieldSuggestions {\n fields: SuggestedSignatureField[]\n /**\n * Named even when the PDF shows none of the Word fields' anchors (the fields are then placed by\n * hand): who each email belongs to. Empty from a server that does not report them.\n */\n signers: NamedSigner[]\n}\n\nexport async function signatureFieldSuggestions(\n client: DocumentToolsClient,\n documentId: string,\n version?: number\n): Promise<SignatureFieldSuggestions> {\n const { data, error } = await client.GET(\n '/v1/document/{document_ext_id}/signature-fields/suggest',\n {\n params: { path: { document_ext_id: documentId }, ...(version ? { query: { version } } : {}) },\n }\n )\n if (!data) throw new Error(detail(error, 'Signature blocks could not be read'))\n return { fields: data.fields, signers: (data as { signers?: NamedSigner[] }).signers ?? [] }\n}\n\nexport async function suggestSignatureFields(\n client: DocumentToolsClient,\n documentId: string,\n version?: number\n): Promise<SuggestedSignatureField[]> {\n return (await signatureFieldSuggestions(client, documentId, version)).fields\n}\n\n// \u2500\u2500 Prepare \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface SaveSignatureRequestVars {\n documentId: string\n /** The version the fields were placed on (the PDF shown). Omitted = current. */\n version?: number\n fields: SignatureField[]\n message?: string\n /** Existing draft to update instead of creating a new request. */\n requestId?: string\n /** Send it to the signers (else it is saved as a draft). */\n send: boolean\n}\n\nexport async function saveSignatureRequest(\n client: DocumentToolsClient,\n { documentId, version, fields, message, requestId, send }: SaveSignatureRequestVars\n): Promise<SignatureRequest> {\n if (!requestId) {\n const { data, error } = await client.POST('/v1/document/{document_ext_id}/signature-requests', {\n params: { path: { document_ext_id: documentId } },\n body: { fields, message: message || null, send, ...(version ? { version } : {}) },\n })\n if (!data) throw new Error(detail(error, 'The signature request could not be saved'))\n return data\n }\n const path = { request_ext_id: requestId }\n const updated = await client.PATCH('/v1/signature-requests/{request_ext_id}', {\n params: { path },\n body: { fields, message: message ?? null },\n })\n if (!updated.data) throw new Error(detail(updated.error, 'The draft could not be saved'))\n if (!send) return updated.data\n const sent = await client.POST('/v1/signature-requests/{request_ext_id}/send', {\n params: { path },\n })\n if (!sent.data) throw new Error(detail(sent.error, 'The request could not be sent'))\n return sent.data\n}\n\nfunction useInvalidateRequests() {\n const queryClient = useQueryClient()\n return () => queryClient.invalidateQueries({ queryKey: arbiQueryKeys.signatureRequests() })\n}\n\nexport function useSaveSignatureRequest() {\n const { client } = useDocumentTools()\n const invalidate = useInvalidateRequests()\n return useMutation({\n mutationFn: (vars: SaveSignatureRequestVars) => saveSignatureRequest(client, vars),\n onSuccess: invalidate,\n })\n}\n\nexport function useVoidSignatureRequest() {\n const { client } = useDocumentTools()\n const invalidate = useInvalidateRequests()\n return useMutation({\n mutationFn: async (requestId: string) => {\n const { data, error } = await client.POST('/v1/signature-requests/{request_ext_id}/void', {\n params: { path: { request_ext_id: requestId } },\n })\n if (!data) throw new Error(detail(error, 'The request could not be voided'))\n return data\n },\n onSuccess: invalidate,\n })\n}\n\nexport function useDeclineSignatureRequest() {\n const { client } = useDocumentTools()\n const invalidate = useInvalidateRequests()\n return useMutation({\n mutationFn: async ({ requestId, reason }: { requestId: string; reason?: string }) => {\n const { data, error } = await client.POST('/v1/signature-requests/{request_ext_id}/decline', {\n params: { path: { request_ext_id: requestId } },\n body: { reason: reason || null },\n })\n if (!data) throw new Error(detail(error, 'Could not decline'))\n return data\n },\n onSuccess: invalidate,\n })\n}\n\n// \u2500\u2500 Sign \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface SignRequestVars {\n request: SignatureRequest\n /** The PDF the signer was walked through (`GET /view?version=` of the request's version). */\n pdfBlob: Blob\n email: string\n password: string\n adopted: AdoptedSignature\n /** The ids of the fields the signer applied: every required one of theirs. */\n fields: string[]\n}\n\n/**\n * Sign all of the signer's fields at once: the server prepares the statement, the browser checks\n * it covers the PDF on screen under the wording the signer read, re-derives the Ed25519 key from\n * the password and signs. Resolves with `completed` when this was the last signature.\n */\nexport async function signSignatureRequest(\n client: DocumentToolsClient,\n deploymentDomain: string,\n { request, pdfBlob, email, password, adopted, fields }: SignRequestVars\n): Promise<SignRequestSignResponse> {\n const path = { request_ext_id: request.external_id }\n const body = { adopted, fields }\n const prepared = await client.POST('/v1/signature-requests/{request_ext_id}/sign/prepare', {\n params: { path },\n body,\n })\n if (!prepared.data) {\n throw (\n identityRefusal(prepared.error) ??\n new SigningError(detail(prepared.error, 'Could not prepare signing'), 'failed')\n )\n }\n const { statement, intent, source_sha256, timestamp } = prepared.data\n if (source_sha256 !== request.source_sha256 || (await sha256Hex(pdfBlob)) !== source_sha256) {\n throw new SigningError('The document changed since it was sent. Ask for it again.', 'stale')\n }\n if (intent !== intentText({ name: adopted.name })) {\n throw new Error('Signing statement mismatch; not signed.')\n }\n const identity = await unlockIdentityWithPassword(email, password, deploymentDomain)\n const signed = await client.POST('/v1/signature-requests/{request_ext_id}/sign', {\n params: { path },\n body: { ...body, timestamp, signature: signMessage(statement, identity) },\n })\n if (!signed.data) {\n throw (\n identityRefusal(signed.error) ??\n new SigningError(detail(signed.error, 'Signing failed'), 'failed')\n )\n }\n return signed.data\n}\n\nexport function useSignSignatureRequest() {\n const env = useDocumentTools()\n const invalidate = useInvalidateRequests()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: (vars: SignRequestVars) => {\n if (!env.deploymentDomain) throw new Error('Signing is not set up: no deployment domain')\n return signSignatureRequest(env.client, env.deploymentDomain, vars)\n },\n onSuccess: async (result) => {\n await invalidate()\n if (result.completed && result.request.doc_ext_id) {\n await env.onDocumentsChanged?.([result.request.doc_ext_id], 'signed')\n await queryClient.invalidateQueries({ queryKey: arbiQueryKeys.documentSignatures() })\n }\n },\n })\n}\n\n// \u2500\u2500 Who can sign \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface SignerCandidate {\n externalId: string\n name: string\n email: string\n role: string\n}\n\n/**\n * The people in the active workspace who may sign: owners, collaborators and guests (an agent never\n * does). The first one listed is the current user when they are a member.\n */\nexport function useSignerCandidates(enabled = true) {\n const { client, user } = useDocumentTools()\n const { workspaceId, read } = useOpenWorkspaceRead()\n return useQuery({\n queryKey: arbiQueryKeys.signatureCandidates(workspaceId ?? ''),\n queryFn: async (): Promise<SignerCandidate[]> => {\n const { data, error } = await read(() => client.GET('/v1/workspace/users'))\n if (!data) throw new Error(detail(error, 'The workspace members could not be read'))\n const people = data\n .filter((m) => m.user.external_id.startsWith('usr-'))\n .map((m) => ({\n externalId: m.user.external_id,\n name: [m.user.given_name, m.user.family_name].filter(Boolean).join(' ') || m.user.email,\n email: m.user.email,\n role: String(m.role),\n }))\n const me = user?.email?.toLowerCase()\n return [...people].sort(\n (a, b) => Number(b.email.toLowerCase() === me) - Number(a.email.toLowerCase() === me)\n )\n },\n enabled,\n staleTime: 60_000,\n })\n}\n\n// \u2500\u2500 Invite \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Invite signers who are not in the workspace yet, as guests, through the workspace's own invite\n * (`POST /v1/workspace/users` with `confirm_invite`): a registered person is added at once, anyone\n * else is emailed an invitation that lands on the document. Each is asked to sign when they join.\n * Only a workspace owner can invite.\n */\nexport async function inviteSigners(\n client: DocumentToolsClient,\n documentId: string,\n emails: string[]\n): Promise<void> {\n if (!emails.length) return\n const { error, response } = await client.POST('/v1/workspace/users', {\n body: workspaces.addWorkspaceMembersBody({\n emails,\n role: 'guest',\n confirm_invite: true,\n resource_type: 'document',\n resource_ext_id: documentId,\n }),\n })\n if (response.status === 409) {\n throw new Error('Share the document with the workspace before asking others to sign it.')\n }\n // 404 \"No users found to add\": everyone is a member already (nothing to do).\n if (error && response.status !== 404) {\n throw new Error(detail(error, 'The signers could not be invited'))\n }\n}\n\nexport function useInviteSigners() {\n const { client } = useDocumentTools()\n const invalidate = useInvalidateRequests()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: ({ documentId, emails }: { documentId: string; emails: string[] }) =>\n inviteSigners(client, documentId, emails),\n onSuccess: async () => {\n await invalidate()\n await queryClient.invalidateQueries({ queryKey: arbiQueryKeys.signatureCandidates() })\n },\n })\n}\n"],
|
|
5
|
+
"mappings": "AAYA,SAAS,aAAa,kCAAmD;AACzE,SAAS,aAAa,UAAU,sBAAsB;AACtD,SAAS,kBAAkB;AAC3B,SAAS,wBAAkD;AAC3D,SAAS,iBAAiB,YAAY,WAAW,oBAAoB;AACrE,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAO5B,SAAS,uBAAuB;AAC9B,QAAM,OAAO,YAAY,EAAE;AAC3B,QAAM,cAAc,MAAM,eAAe,KAAK,eAAe,IAAI;AACjE,QAAM,OAAO,CAAI,QACf,QAAQ,cAAc,KAAK,gBAAgB,aAAa,GAAG,IAAI,IAAI;AACrE,SAAO,EAAE,aAAa,KAAK;AAC7B;AAYO,MAAM,wBAAuD;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,MAAM,oBAAwD;AAAA,EACnE,WAAW;AAAA,EACX,UAAU;AAAA,EACV,MAAM;AAAA,EACN,MAAM;AACR;AAMO,MAAM,qBAAoF;AAAA,EAC/F,WAAW,EAAE,OAAO,MAAM,QAAQ,KAAK;AAAA,EACvC,UAAU,EAAE,OAAO,KAAK,QAAQ,KAAK;AAAA,EACrC,MAAM,EAAE,OAAO,MAAM,QAAQ,MAAM;AAAA,EACnC,MAAM,EAAE,OAAO,MAAM,QAAQ,MAAM;AACrC;AAGO,MAAM,yBAAyD;AAAA,EACpE,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,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B,CAAC,GAAG,MAAM,OAAO,EAAE,MAAM,YAAY,MAAM,EAAE,IAAI,OAAO,EAAE,MAAM,YAAY,MAAM,EAAE;AAAA,MACtF;AAAA,IACF;AAAA,IACA;AAAA,IACA,WAAW;AAAA,EACb,CAAC;AACH;AAUA,eAAsB,cACpB,QACA,YACA,QACe;AACf,MAAI,CAAC,OAAO,OAAQ;AACpB,QAAM,EAAE,OAAO,SAAS,IAAI,MAAM,OAAO,KAAK,uBAAuB;AAAA,IACnE,MAAM,WAAW,wBAAwB;AAAA,MACvC;AAAA,MACA,MAAM;AAAA,MACN,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,iBAAiB;AAAA,IACnB,CAAC;AAAA,EACH,CAAC;AACD,MAAI,SAAS,WAAW,KAAK;AAC3B,UAAM,IAAI,MAAM,wEAAwE;AAAA,EAC1F;AAEA,MAAI,SAAS,SAAS,WAAW,KAAK;AACpC,UAAM,IAAI,MAAM,OAAO,OAAO,kCAAkC,CAAC;AAAA,EACnE;AACF;AAEO,SAAS,mBAAmB;AACjC,QAAM,EAAE,OAAO,IAAI,iBAAiB;AACpC,QAAM,aAAa,sBAAsB;AACzC,QAAM,cAAc,eAAe;AACnC,SAAO,YAAY;AAAA,IACjB,YAAY,CAAC,EAAE,YAAY,OAAO,MAChC,cAAc,QAAQ,YAAY,MAAM;AAAA,IAC1C,WAAW,YAAY;AACrB,YAAM,WAAW;AACjB,YAAM,YAAY,kBAAkB,EAAE,UAAU,cAAc,oBAAoB,EAAE,CAAC;AAAA,IACvF;AAAA,EACF,CAAC;AACH;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -20,7 +20,13 @@ function isLegibleSignatureBox(rect) {
|
|
|
20
20
|
const SIGNATURES_PATH = "/v1/document/{document_ext_id}/signatures";
|
|
21
21
|
function errorDetail(error, fallback) {
|
|
22
22
|
const detail = error?.detail;
|
|
23
|
-
|
|
23
|
+
if (typeof detail === "string") return detail;
|
|
24
|
+
const message = detail?.message;
|
|
25
|
+
return typeof message === "string" ? message : fallback;
|
|
26
|
+
}
|
|
27
|
+
function errorCode(error) {
|
|
28
|
+
const code = error?.detail?.code;
|
|
29
|
+
return typeof code === "string" ? code : void 0;
|
|
24
30
|
}
|
|
25
31
|
async function fetchDocumentSignatures(client, documentRef) {
|
|
26
32
|
const { docId, version } = parseVersionRef(documentRef);
|
|
@@ -40,6 +46,7 @@ function useDocumentSignatures(documentId, enabled = true) {
|
|
|
40
46
|
staleTime: 6e4
|
|
41
47
|
});
|
|
42
48
|
}
|
|
49
|
+
const IDENTITY_VERIFICATION_REQUIRED = "IDENTITY_VERIFICATION_REQUIRED";
|
|
43
50
|
class SigningError extends Error {
|
|
44
51
|
reason;
|
|
45
52
|
constructor(message, reason) {
|
|
@@ -53,8 +60,14 @@ function signingErrorReason(detail) {
|
|
|
53
60
|
if (/no longer the current version/i.test(detail)) return "stale";
|
|
54
61
|
return "failed";
|
|
55
62
|
}
|
|
63
|
+
function identityRefusal(error) {
|
|
64
|
+
if (errorCode(error) !== IDENTITY_VERIFICATION_REQUIRED) return void 0;
|
|
65
|
+
return new SigningError(errorDetail(error, "Verify your identity before signing."), "identity");
|
|
66
|
+
}
|
|
56
67
|
function signingError(error, fallback) {
|
|
57
68
|
const detail = errorDetail(error, fallback);
|
|
69
|
+
if (errorCode(error) === IDENTITY_VERIFICATION_REQUIRED)
|
|
70
|
+
return new SigningError(detail, "identity");
|
|
58
71
|
return new SigningError(detail, signingErrorReason(detail));
|
|
59
72
|
}
|
|
60
73
|
const PREPARE_RETRIES = 3;
|
|
@@ -113,9 +126,11 @@ function useSignDocument() {
|
|
|
113
126
|
});
|
|
114
127
|
}
|
|
115
128
|
export {
|
|
129
|
+
IDENTITY_VERIFICATION_REQUIRED,
|
|
116
130
|
PREPARE_RETRIES,
|
|
117
131
|
SigningError,
|
|
118
132
|
fetchDocumentSignatures,
|
|
133
|
+
identityRefusal,
|
|
119
134
|
intentText,
|
|
120
135
|
isLegibleSignatureBox,
|
|
121
136
|
sha256Hex,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/document-tools/signing.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Electronic signing. The backend (`src/core/esign.py` in ARBI) defines what a signature binds;\n * the helpers mirror the two pieces the browser must reproduce exactly: the statement of intent\n * shown to the signer, and the SHA-256 of the PDF the viewer displayed.\n */\n\nimport { signMessage, unlockIdentityWithPassword, type components } from '@arbidocs/client'\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'\nimport { parseVersionRef } from '../artifacts/versions'\nimport { useDocumentTools, type DocumentToolsClient } from './environment'\nimport { arbiQueryKeys } from '../query-keys'\n\n/**\n * Who signs: the name only. A role, a firm or a place go on the page as ordinary annotation text,\n * which is not part of the signature.\n */\nexport type SignerDetails = components['schemas']['SignerDetails']\n\n/** Same sentence as `esign.intent_text`; the dialog refuses to sign if the server's differs. */\nexport function intentText(signer: SignerDetails): string {\n return `I, ${signer.name.trim()}, sign this document electronically. I intend this electronic signature to have the same effect as my handwritten signature.`\n}\n\nexport async function sha256Hex(blob: Blob): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new Uint8Array(await blob.arrayBuffer()))\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** A signature box drawn on the annotation overlay, as the signing API's placement. */\nexport function toAppearance(box: {\n page: number\n rect: { x: number; y: number; w: number; h: number }\n}): { page: number; x: number; y: number; width: number; height: number } {\n // The layer counts pages from 1, the signing API from 0. Both use fractions of the page as\n // displayed, origin top-left.\n return { page: box.page - 1, x: box.rect.x, y: box.rect.y, width: box.rect.w, height: box.rect.h }\n}\n\n/**\n * The smallest box the backend can draw a legible signature in: the signer's name and the\n * details line shrink to fit, so a box under these fractions of the page is shrunk to near\n * unreadable size. The backend's own default box is 0.40 x 0.10.\n */\nconst MIN_SIGNATURE_BOX = { width: 0.3, height: 0.07 }\n\nexport function isLegibleSignatureBox(rect: { w: number; h: number }): boolean {\n return rect.w >= MIN_SIGNATURE_BOX.width && rect.h >= MIN_SIGNATURE_BOX.height\n}\n\n// \u2500\u2500 Signing through the API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type SignatureAppearance = components['schemas']['SignatureAppearance']\nexport type SignatureStatusResponse = components['schemas']['SignatureStatusResponse']\nexport type SignatureRecord = components['schemas']['SignatureRecord']\nexport type SignDocumentResponse = components['schemas']['SignDocumentResponse']\n\nconst SIGNATURES_PATH = '/v1/document/{document_ext_id}/signatures'\n/**\n * The same key openapi-react-query gives this request (`['get', path, init]`), so a host that\n * reads or persists the API cache by path treats it like its own queries.\n */\n\nfunction errorDetail(error: unknown, fallback: string): string {\n const detail = (error as { detail?: unknown } | undefined)?.detail\n return typeof detail === 'string' ? detail : fallback\n}\n\n/** Whether a document version is a signed copy, and its signatures. */\nexport async function fetchDocumentSignatures(\n client: DocumentToolsClient,\n documentRef: string\n): Promise<SignatureStatusResponse> {\n const { docId, version } = parseVersionRef(documentRef)\n const { data, error } = await client.GET(SIGNATURES_PATH, {\n params: { path: { document_ext_id: docId }, ...(version ? { query: { version } } : {}) },\n })\n if (!data) throw new Error(errorDetail(error, 'The signatures could not be read'))\n return data\n}\n\n/**\n * Is a document version a signed copy? `documentId` is a document id (its current version) or a\n * version reference `doc-\u2026@v{n}`. Needs a React Query `QueryClientProvider`.\n */\nexport function useDocumentSignatures(documentId: string | null | undefined, enabled = true) {\n const { client } = useDocumentTools()\n const { docId, version } = parseVersionRef(documentId)\n return useQuery({\n queryKey: arbiQueryKeys.documentSignatures(docId ?? '', version),\n queryFn: () => fetchDocumentSignatures(client, documentId!),\n enabled: enabled && !!docId,\n staleTime: 60_000,\n })\n}\n\n/**\n * Why the server would not sign: the PDF of a Word or text document is still being rendered\n * (`preparing`, worth another try in a moment), or the version on screen is no longer the current\n * one (`stale`: only the current version can be signed, so the signer reopens it).\n */\nexport type SigningErrorReason = 'preparing' | 'stale' | 'failed'\n\nexport class SigningError extends Error {\n readonly reason: SigningErrorReason\n constructor(message: string, reason: SigningErrorReason) {\n super(message)\n this.name = 'SigningError'\n this.reason = reason\n }\n}\n\n/** The 409s the backend's signing router raises, told apart by their wording. */\nfunction signingErrorReason(detail: string): SigningErrorReason {\n if (/still being prepared/i.test(detail)) return 'preparing'\n if (/no longer the current version/i.test(detail)) return 'stale'\n return 'failed'\n}\n\nfunction signingError(error: unknown, fallback: string): SigningError {\n const detail = errorDetail(error, fallback)\n return new SigningError(detail, signingErrorReason(detail))\n}\n\n/** How often, and how long apart, a prepare is retried while the PDF is still being rendered. */\nexport const PREPARE_RETRIES = 3\nconst PREPARE_RETRY_DELAY_MS = 1500\n\nconst wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\nexport interface SignDocumentVars {\n documentId: string\n /**\n * The PDF bytes the viewer is showing (`GET /view?version=`, never the original's download): the\n * signer signs exactly these.\n */\n pdfBlob: Blob\n /**\n * The version `pdfBlob` is of. The server signs only the current version and refuses\n * (`SigningError` `stale`) when this one has been superseded. Omitted = the current version.\n */\n version?: number\n email: string\n password: string\n signer: SignerDetails\n /** Where the signature goes; omitted = the backend default (bottom of the last page). */\n appearance?: SignatureAppearance\n /** Draw the signing date under the signature. Default off: only the signature is drawn. */\n includeDate?: boolean\n}\n\n/**\n * Sign a document: the server prepares the statement, the browser checks that it covers the PDF\n * on screen under the wording the signer read, re-derives the user's Ed25519 key from their\n * password and signs it, and the server seals the signed copy as a new version.\n *\n * What is drawn on the page is only the signature (the signer's name as the signature mark) and,\n * with `includeDate`, the date; anyone can click it to open its certificate. A role, a firm or a\n * place go on the page as ordinary annotation text, which is not part of the signature.\n */\nexport async function signDocument(\n client: DocumentToolsClient,\n deploymentDomain: string,\n {\n documentId,\n pdfBlob,\n email,\n password,\n signer,\n appearance,\n includeDate = false,\n version,\n }: SignDocumentVars\n): Promise<SignDocumentResponse> {\n const path = { document_ext_id: documentId }\n // One body for both calls: the server refuses a /sign whose include_date (or placement) differs\n // from what was prepared, since what the signature shows is part of what is signed.\n const body = {\n signer: { name: signer.name },\n ...(appearance ? { appearance } : {}),\n include_date: includeDate,\n ...(version ? { version } : {}),\n }\n\n // A Word or text document's PDF is rendered after upload: while it is, prepare says so, and a\n // short wait usually sees it ready.\n const prepare = () =>\n client.POST('/v1/document/{document_ext_id}/sign/prepare', { params: { path }, body })\n let prepared = await prepare()\n for (let attempt = 0; !prepared.data && attempt < PREPARE_RETRIES; attempt++) {\n if (signingError(prepared.error, '').reason !== 'preparing') break\n await wait(PREPARE_RETRY_DELAY_MS)\n prepared = await prepare()\n }\n if (!prepared.data) throw signingError(prepared.error, 'Could not prepare signing')\n const { statement, intent, source_sha256, timestamp } = prepared.data\n // Sign only what was on screen, under the wording the signer read.\n if ((await sha256Hex(pdfBlob)) !== source_sha256) {\n throw new Error('The document changed since it was opened. Reopen it and sign again.')\n }\n if (intent !== intentText(signer)) throw new Error('Signing statement mismatch; not signed.')\n\n // The re-typed password must open the session's identity, which is the key the server verifies.\n const identity = await unlockIdentityWithPassword(email, password, deploymentDomain)\n const signed = await client.POST('/v1/document/{document_ext_id}/sign', {\n params: { path },\n body: { ...body, timestamp, signature: signMessage(statement, identity) },\n })\n if (!signed.data) throw signingError(signed.error, 'Signing failed')\n return signed.data\n}\n\n/** The signing mutation. On success the host hears the document changed (`'signed'`). */\nexport function useSignDocument() {\n const env = useDocumentTools()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: (vars: SignDocumentVars) => {\n if (!env.deploymentDomain) throw new Error('Signing is not set up: no deployment domain')\n return signDocument(env.client, env.deploymentDomain, vars)\n },\n onSuccess: async (result) => {\n // The signed copy is the document's new current version: the host refreshes its row,\n // versions and rendered PDF, and the signature badge reads again.\n await env.onDocumentsChanged?.([result.doc_ext_id], 'signed')\n await queryClient.invalidateQueries({ queryKey: arbiQueryKeys.documentSignatures() })\n },\n })\n}\n"],
|
|
5
|
-
"mappings": "AAMA,SAAS,aAAa,kCAAmD;AACzE,SAAS,aAAa,UAAU,sBAAsB;AACtD,SAAS,uBAAuB;AAChC,SAAS,wBAAkD;AAC3D,SAAS,qBAAqB;AASvB,SAAS,WAAW,QAA+B;AACxD,SAAO,MAAM,OAAO,KAAK,KAAK,CAAC;AACjC;AAEA,eAAsB,UAAU,MAA6B;AAC3D,QAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI,WAAW,MAAM,KAAK,YAAY,CAAC,CAAC;AAC7F,SAAO,MAAM,KAAK,IAAI,WAAW,MAAM,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAC3F;AAGO,SAAS,aAAa,KAG6C;AAGxE,SAAO,EAAE,MAAM,IAAI,OAAO,GAAG,GAAG,IAAI,KAAK,GAAG,GAAG,IAAI,KAAK,GAAG,OAAO,IAAI,KAAK,GAAG,QAAQ,IAAI,KAAK,EAAE;AACnG;AAOA,MAAM,oBAAoB,EAAE,OAAO,KAAK,QAAQ,KAAK;AAE9C,SAAS,sBAAsB,MAAyC;AAC7E,SAAO,KAAK,KAAK,kBAAkB,SAAS,KAAK,KAAK,kBAAkB;AAC1E;AASA,MAAM,kBAAkB;AAMxB,SAAS,YAAY,OAAgB,UAA0B;AAC7D,QAAM,SAAU,OAA4C;AAC5D,
|
|
4
|
+
"sourcesContent": ["/**\n * Electronic signing. The backend (`src/core/esign.py` in ARBI) defines what a signature binds;\n * the helpers mirror the two pieces the browser must reproduce exactly: the statement of intent\n * shown to the signer, and the SHA-256 of the PDF the viewer displayed.\n */\n\nimport { signMessage, unlockIdentityWithPassword, type components } from '@arbidocs/client'\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'\nimport { parseVersionRef } from '../artifacts/versions'\nimport { useDocumentTools, type DocumentToolsClient } from './environment'\nimport { arbiQueryKeys } from '../query-keys'\n\n/**\n * Who signs: the name only. A role, a firm or a place go on the page as ordinary annotation text,\n * which is not part of the signature.\n */\nexport type SignerDetails = components['schemas']['SignerDetails']\n\n/** Same sentence as `esign.intent_text`; the dialog refuses to sign if the server's differs. */\nexport function intentText(signer: SignerDetails): string {\n return `I, ${signer.name.trim()}, sign this document electronically. I intend this electronic signature to have the same effect as my handwritten signature.`\n}\n\nexport async function sha256Hex(blob: Blob): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new Uint8Array(await blob.arrayBuffer()))\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** A signature box drawn on the annotation overlay, as the signing API's placement. */\nexport function toAppearance(box: {\n page: number\n rect: { x: number; y: number; w: number; h: number }\n}): { page: number; x: number; y: number; width: number; height: number } {\n // The layer counts pages from 1, the signing API from 0. Both use fractions of the page as\n // displayed, origin top-left.\n return { page: box.page - 1, x: box.rect.x, y: box.rect.y, width: box.rect.w, height: box.rect.h }\n}\n\n/**\n * The smallest box the backend can draw a legible signature in: the signer's name and the\n * details line shrink to fit, so a box under these fractions of the page is shrunk to near\n * unreadable size. The backend's own default box is 0.40 x 0.10.\n */\nconst MIN_SIGNATURE_BOX = { width: 0.3, height: 0.07 }\n\nexport function isLegibleSignatureBox(rect: { w: number; h: number }): boolean {\n return rect.w >= MIN_SIGNATURE_BOX.width && rect.h >= MIN_SIGNATURE_BOX.height\n}\n\n// \u2500\u2500 Signing through the API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type SignatureAppearance = components['schemas']['SignatureAppearance']\nexport type SignatureStatusResponse = components['schemas']['SignatureStatusResponse']\nexport type SignatureRecord = components['schemas']['SignatureRecord']\nexport type SignDocumentResponse = components['schemas']['SignDocumentResponse']\n\nconst SIGNATURES_PATH = '/v1/document/{document_ext_id}/signatures'\n/**\n * The same key openapi-react-query gives this request (`['get', path, init]`), so a host that\n * reads or persists the API cache by path treats it like its own queries.\n */\n\nfunction errorDetail(error: unknown, fallback: string): string {\n const detail = (error as { detail?: unknown } | undefined)?.detail\n if (typeof detail === 'string') return detail\n // A coded refusal carries `{code, message}` as its detail.\n const message = (detail as { message?: unknown } | null | undefined)?.message\n return typeof message === 'string' ? message : fallback\n}\n\n/** The backend's code on a refusal (`detail.code`), if it sent one. */\nfunction errorCode(error: unknown): string | undefined {\n const code = ((error as { detail?: unknown } | undefined)?.detail as { code?: unknown } | null)\n ?.code\n return typeof code === 'string' ? code : undefined\n}\n\n/** Whether a document version is a signed copy, and its signatures. */\nexport async function fetchDocumentSignatures(\n client: DocumentToolsClient,\n documentRef: string\n): Promise<SignatureStatusResponse> {\n const { docId, version } = parseVersionRef(documentRef)\n const { data, error } = await client.GET(SIGNATURES_PATH, {\n params: { path: { document_ext_id: docId }, ...(version ? { query: { version } } : {}) },\n })\n if (!data) throw new Error(errorDetail(error, 'The signatures could not be read'))\n return data\n}\n\n/**\n * Is a document version a signed copy? `documentId` is a document id (its current version) or a\n * version reference `doc-\u2026@v{n}`. Needs a React Query `QueryClientProvider`.\n */\nexport function useDocumentSignatures(documentId: string | null | undefined, enabled = true) {\n const { client } = useDocumentTools()\n const { docId, version } = parseVersionRef(documentId)\n return useQuery({\n queryKey: arbiQueryKeys.documentSignatures(docId ?? '', version),\n queryFn: () => fetchDocumentSignatures(client, documentId!),\n enabled: enabled && !!docId,\n staleTime: 60_000,\n })\n}\n\n/**\n * Why the server would not sign: the PDF of a Word or text document is still being rendered\n * (`preparing`, worth another try in a moment), or the version on screen is no longer the current\n * one (`stale`: only the current version can be signed, so the signer reopens it), or the signing\n * step asks the signer for a verified identity first (`identity`: 403 `IDENTITY_VERIFICATION_REQUIRED`;\n * the signer completes the ID check, then signs).\n */\nexport type SigningErrorReason = 'preparing' | 'stale' | 'identity' | 'failed'\n\n/** The code of the 403 a signing call answers while the signer's identity is not verified. */\nexport const IDENTITY_VERIFICATION_REQUIRED = 'IDENTITY_VERIFICATION_REQUIRED'\n\nexport class SigningError extends Error {\n readonly reason: SigningErrorReason\n constructor(message: string, reason: SigningErrorReason) {\n super(message)\n this.name = 'SigningError'\n this.reason = reason\n }\n}\n\n/** The 409s the backend's signing router raises, told apart by their wording. */\nfunction signingErrorReason(detail: string): SigningErrorReason {\n if (/still being prepared/i.test(detail)) return 'preparing'\n if (/no longer the current version/i.test(detail)) return 'stale'\n return 'failed'\n}\n\n/** The identity refusal (403 `IDENTITY_VERIFICATION_REQUIRED`) of any signing route, else undefined. */\nexport function identityRefusal(error: unknown): SigningError | undefined {\n if (errorCode(error) !== IDENTITY_VERIFICATION_REQUIRED) return undefined\n return new SigningError(errorDetail(error, 'Verify your identity before signing.'), 'identity')\n}\n\nfunction signingError(error: unknown, fallback: string): SigningError {\n const detail = errorDetail(error, fallback)\n if (errorCode(error) === IDENTITY_VERIFICATION_REQUIRED)\n return new SigningError(detail, 'identity')\n return new SigningError(detail, signingErrorReason(detail))\n}\n\n/** How often, and how long apart, a prepare is retried while the PDF is still being rendered. */\nexport const PREPARE_RETRIES = 3\nconst PREPARE_RETRY_DELAY_MS = 1500\n\nconst wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\nexport interface SignDocumentVars {\n documentId: string\n /**\n * The PDF bytes the viewer is showing (`GET /view?version=`, never the original's download): the\n * signer signs exactly these.\n */\n pdfBlob: Blob\n /**\n * The version `pdfBlob` is of. The server signs only the current version and refuses\n * (`SigningError` `stale`) when this one has been superseded. Omitted = the current version.\n */\n version?: number\n email: string\n password: string\n signer: SignerDetails\n /** Where the signature goes; omitted = the backend default (bottom of the last page). */\n appearance?: SignatureAppearance\n /** Draw the signing date under the signature. Default off: only the signature is drawn. */\n includeDate?: boolean\n}\n\n/**\n * Sign a document: the server prepares the statement, the browser checks that it covers the PDF\n * on screen under the wording the signer read, re-derives the user's Ed25519 key from their\n * password and signs it, and the server seals the signed copy as a new version.\n *\n * What is drawn on the page is only the signature (the signer's name as the signature mark) and,\n * with `includeDate`, the date; anyone can click it to open its certificate. A role, a firm or a\n * place go on the page as ordinary annotation text, which is not part of the signature.\n */\nexport async function signDocument(\n client: DocumentToolsClient,\n deploymentDomain: string,\n {\n documentId,\n pdfBlob,\n email,\n password,\n signer,\n appearance,\n includeDate = false,\n version,\n }: SignDocumentVars\n): Promise<SignDocumentResponse> {\n const path = { document_ext_id: documentId }\n // One body for both calls: the server refuses a /sign whose include_date (or placement) differs\n // from what was prepared, since what the signature shows is part of what is signed.\n const body = {\n signer: { name: signer.name },\n ...(appearance ? { appearance } : {}),\n include_date: includeDate,\n ...(version ? { version } : {}),\n }\n\n // A Word or text document's PDF is rendered after upload: while it is, prepare says so, and a\n // short wait usually sees it ready.\n const prepare = () =>\n client.POST('/v1/document/{document_ext_id}/sign/prepare', { params: { path }, body })\n let prepared = await prepare()\n for (let attempt = 0; !prepared.data && attempt < PREPARE_RETRIES; attempt++) {\n if (signingError(prepared.error, '').reason !== 'preparing') break\n await wait(PREPARE_RETRY_DELAY_MS)\n prepared = await prepare()\n }\n if (!prepared.data) throw signingError(prepared.error, 'Could not prepare signing')\n const { statement, intent, source_sha256, timestamp } = prepared.data\n // Sign only what was on screen, under the wording the signer read.\n if ((await sha256Hex(pdfBlob)) !== source_sha256) {\n throw new Error('The document changed since it was opened. Reopen it and sign again.')\n }\n if (intent !== intentText(signer)) throw new Error('Signing statement mismatch; not signed.')\n\n // The re-typed password must open the session's identity, which is the key the server verifies.\n const identity = await unlockIdentityWithPassword(email, password, deploymentDomain)\n const signed = await client.POST('/v1/document/{document_ext_id}/sign', {\n params: { path },\n body: { ...body, timestamp, signature: signMessage(statement, identity) },\n })\n if (!signed.data) throw signingError(signed.error, 'Signing failed')\n return signed.data\n}\n\n/** The signing mutation. On success the host hears the document changed (`'signed'`). */\nexport function useSignDocument() {\n const env = useDocumentTools()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: (vars: SignDocumentVars) => {\n if (!env.deploymentDomain) throw new Error('Signing is not set up: no deployment domain')\n return signDocument(env.client, env.deploymentDomain, vars)\n },\n onSuccess: async (result) => {\n // The signed copy is the document's new current version: the host refreshes its row,\n // versions and rendered PDF, and the signature badge reads again.\n await env.onDocumentsChanged?.([result.doc_ext_id], 'signed')\n await queryClient.invalidateQueries({ queryKey: arbiQueryKeys.documentSignatures() })\n },\n })\n}\n"],
|
|
5
|
+
"mappings": "AAMA,SAAS,aAAa,kCAAmD;AACzE,SAAS,aAAa,UAAU,sBAAsB;AACtD,SAAS,uBAAuB;AAChC,SAAS,wBAAkD;AAC3D,SAAS,qBAAqB;AASvB,SAAS,WAAW,QAA+B;AACxD,SAAO,MAAM,OAAO,KAAK,KAAK,CAAC;AACjC;AAEA,eAAsB,UAAU,MAA6B;AAC3D,QAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI,WAAW,MAAM,KAAK,YAAY,CAAC,CAAC;AAC7F,SAAO,MAAM,KAAK,IAAI,WAAW,MAAM,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAC3F;AAGO,SAAS,aAAa,KAG6C;AAGxE,SAAO,EAAE,MAAM,IAAI,OAAO,GAAG,GAAG,IAAI,KAAK,GAAG,GAAG,IAA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,7 @@ var chunkT5FZICXN_cjs = require('./chunk-T5FZICXN.cjs');
|
|
|
8
8
|
var chunkKAMOFYV2_cjs = require('./chunk-KAMOFYV2.cjs');
|
|
9
9
|
var chunkEM6DP62E_cjs = require('./chunk-EM6DP62E.cjs');
|
|
10
10
|
var chunkBEOHXA2Z_cjs = require('./chunk-BEOHXA2Z.cjs');
|
|
11
|
-
var
|
|
11
|
+
var chunkSYGC6Z5B_cjs = require('./chunk-SYGC6Z5B.cjs');
|
|
12
12
|
var chunkWYZJLZ67_cjs = require('./chunk-WYZJLZ67.cjs');
|
|
13
13
|
var chunkSJZRVX7T_cjs = require('./chunk-SJZRVX7T.cjs');
|
|
14
14
|
var chunkUMQY6L7P_cjs = require('./chunk-UMQY6L7P.cjs');
|
|
@@ -2491,7 +2491,7 @@ function useDownloadDocuments({ workspaceName } = {}) {
|
|
|
2491
2491
|
const [isDownloading, setIsDownloading] = React.useState(false);
|
|
2492
2492
|
const fetchNamedFile = React.useCallback(
|
|
2493
2493
|
async (doc) => {
|
|
2494
|
-
const blob = await
|
|
2494
|
+
const blob = await chunkSYGC6Z5B_cjs.fetchDocumentFile(arbi.getClient().fetch, doc.external_id);
|
|
2495
2495
|
return { blob, name: blob instanceof File && blob.name ? blob.name : fallbackFileName(doc) };
|
|
2496
2496
|
},
|
|
2497
2497
|
[arbi]
|
|
@@ -2533,7 +2533,7 @@ function useDownloadDocuments({ workspaceName } = {}) {
|
|
|
2533
2533
|
);
|
|
2534
2534
|
}
|
|
2535
2535
|
const zipFileName = archiveName(workspaceName, `${successCount}_documents`);
|
|
2536
|
-
|
|
2536
|
+
chunkSYGC6Z5B_cjs.downloadBlob(await zip.generateAsync({ type: "blob" }), zipFileName);
|
|
2537
2537
|
const documentsLabel = `${successCount} document${successCount !== 1 ? "s" : ""}`;
|
|
2538
2538
|
const contents = includeMetadataCsv ? `${documentsLabel} and index.csv in ${zipFileName}` : `${documentsLabel} in ${zipFileName}`;
|
|
2539
2539
|
if (failedDocs.length === 0) chunk5ECKSF6H_cjs.notify.success(`Successfully downloaded ${contents}`);
|
|
@@ -2552,7 +2552,7 @@ function useDownloadDocuments({ workspaceName } = {}) {
|
|
|
2552
2552
|
setIsDownloading(true);
|
|
2553
2553
|
try {
|
|
2554
2554
|
const file = await fetchNamedFile(doc);
|
|
2555
|
-
|
|
2555
|
+
chunkSYGC6Z5B_cjs.downloadBlob(file.blob, file.name);
|
|
2556
2556
|
chunk5ECKSF6H_cjs.notify.success(`Successfully downloaded ${file.name}`);
|
|
2557
2557
|
} catch (error) {
|
|
2558
2558
|
console.error("Failed to download document", error);
|
|
@@ -4231,7 +4231,7 @@ async function keepDocumentsOffline(client$1, docs) {
|
|
|
4231
4231
|
if (!keypair) throw new Error("Could not derive an encryption key for the offline copy.");
|
|
4232
4232
|
for (const doc of docs) {
|
|
4233
4233
|
const original = chunkCQLUDYB4_cjs.usesOriginalBytesForViewer(doc.file_name);
|
|
4234
|
-
const blob = original ? await
|
|
4234
|
+
const blob = original ? await chunkSYGC6Z5B_cjs.fetchDocumentFile(client$1, doc.external_id) : await chunkSYGC6Z5B_cjs.fetchDocumentPdf(client$1, doc.external_id);
|
|
4235
4235
|
const plain = new Uint8Array(await blob.arrayBuffer());
|
|
4236
4236
|
await putOfflineDocument({
|
|
4237
4237
|
docExtId: doc.external_id,
|
|
@@ -9854,12 +9854,12 @@ function useWorkspaceExportDownload({
|
|
|
9854
9854
|
const client = arbi.getClient().fetch;
|
|
9855
9855
|
const archive = await buildWorkspaceArchive({
|
|
9856
9856
|
exportData: data,
|
|
9857
|
-
fetchFile: async (docExtId, version, kind) => kind === "markup" ? (await
|
|
9857
|
+
fetchFile: async (docExtId, version, kind) => kind === "markup" ? (await chunkSYGC6Z5B_cjs.fetchMarkupPdf(client, docExtId, version, workspaceId)).blob : chunkSYGC6Z5B_cjs.fetchDocumentFile(client, docExtId, { version, workspaceExtId: workspaceId }),
|
|
9858
9858
|
metadataCsv,
|
|
9859
9859
|
onProgress: (done, total) => setProgress({ done, total })
|
|
9860
9860
|
});
|
|
9861
9861
|
const fileName = archiveName(workspaceName, "export");
|
|
9862
|
-
|
|
9862
|
+
chunkSYGC6Z5B_cjs.downloadBlob(archive.blob, fileName);
|
|
9863
9863
|
const files = `${archive.fileCount} file${archive.fileCount !== 1 ? "s" : ""}`;
|
|
9864
9864
|
if (archive.failed.length === 0) {
|
|
9865
9865
|
chunk5ECKSF6H_cjs.notify.success(`Successfully downloaded ${files} and data in ${fileName}`);
|
|
@@ -13957,8 +13957,9 @@ function problemOf(error, fallback) {
|
|
|
13957
13957
|
}
|
|
13958
13958
|
function identityStepFor(status) {
|
|
13959
13959
|
if (!status) return "pay";
|
|
13960
|
+
if (status.free && ["none", "in_progress"].includes(status.state)) return "verify";
|
|
13960
13961
|
if (["name_mismatch", "in_review", "verified"].includes(status.state)) return "result";
|
|
13961
|
-
if (status.state === "declined") return status.attempts_left > 0 ? "result" : "pay";
|
|
13962
|
+
if (status.state === "declined") return status.attempts_left > 0 || status.free ? "result" : "pay";
|
|
13962
13963
|
if (status.state === "in_progress" || status.attempts_left > 0) return "verify";
|
|
13963
13964
|
return "pay";
|
|
13964
13965
|
}
|
|
@@ -13990,6 +13991,8 @@ function useIdentityVerificationFlow(api, {
|
|
|
13990
13991
|
staleTime: 6e4
|
|
13991
13992
|
});
|
|
13992
13993
|
const status = query.data;
|
|
13994
|
+
const statusRef = React.useRef(status);
|
|
13995
|
+
statusRef.current = status;
|
|
13993
13996
|
const [isOpen2, setIsOpen] = React.useState(false);
|
|
13994
13997
|
const [step, setStep] = React.useState("pay");
|
|
13995
13998
|
const [busy, setBusy] = React.useState(null);
|
|
@@ -14066,7 +14069,7 @@ function useIdentityVerificationFlow(api, {
|
|
|
14066
14069
|
setSessionUrl(url);
|
|
14067
14070
|
return;
|
|
14068
14071
|
}
|
|
14069
|
-
setStep("pay");
|
|
14072
|
+
if (!statusRef.current?.free) setStep("pay");
|
|
14070
14073
|
}, [run2]);
|
|
14071
14074
|
startVerifyRef.current = startVerify;
|
|
14072
14075
|
React.useEffect(() => {
|
|
@@ -14212,7 +14215,7 @@ async function downloadRecoveryFile(params) {
|
|
|
14212
14215
|
...params,
|
|
14213
14216
|
origin: params.origin ?? window.location.origin
|
|
14214
14217
|
});
|
|
14215
|
-
|
|
14218
|
+
chunkSYGC6Z5B_cjs.downloadBlob(new Blob([file.html], { type: "text/html" }), file.filename);
|
|
14216
14219
|
}
|
|
14217
14220
|
async function documentMailAttachment(arbi, doc, maxBytes, version) {
|
|
14218
14221
|
const older = version && version !== (doc.current_version ?? 1) ? version : null;
|
|
@@ -18269,7 +18272,7 @@ function useDmFileShares(peer) {
|
|
|
18269
18272
|
const queryClient = reactQuery.useQueryClient();
|
|
18270
18273
|
const me = chunkTKPBJCWQ_cjs.myChatId(arbi);
|
|
18271
18274
|
const person = peer && peer.external_id.startsWith("usr-") && me ? peer : null;
|
|
18272
|
-
const list =
|
|
18275
|
+
const list = chunkSYGC6Z5B_cjs.useFileShares(person && arbi.isLoggedIn ? arbi.getClient().fetch : null);
|
|
18273
18276
|
const { data: notifications = [] } = useNotifications({ enabled: !!person });
|
|
18274
18277
|
const entries = React.useMemo(
|
|
18275
18278
|
() => person && me ? dmFileShareEntries({
|