Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@
use OCA\Libresign\Events\SendSignNotificationEvent;
use OCA\Libresign\Events\SignatureRejectedEvent;
use OCA\Libresign\Events\SignedEvent;
use OCA\Libresign\Events\SigningRequestCompletedEvent;
use OCA\Libresign\Events\SignRequestCanceledEvent;
use OCA\Libresign\Files\TemplateLoader;
use OCA\Libresign\Listener\BeforeNodeDeletedListener;
use OCA\Libresign\Listener\LoadAdditionalListener;
use OCA\Libresign\Listener\MailNotifyListener;
use OCA\Libresign\Listener\NotificationListener;
use OCA\Libresign\Listener\RevokeClickToSignCertificateListener;
use OCA\Libresign\Listener\SignedCopyMailListener;
use OCA\Libresign\Listener\TwofactorGatewayListener;
use OCA\Libresign\Listener\UserDeletedListener;
use OCA\Libresign\Middleware\GlobalInjectionMiddleware;
Expand Down Expand Up @@ -98,6 +100,8 @@ public function register(IRegistrationContext $context): void {
$context->registerEventListener(SignedEvent::class, NotificationEventRouter::class);
$context->registerEventListener(SignRequestCanceledEvent::class, NotificationEventRouter::class);

$context->registerEventListener(SigningRequestCompletedEvent::class, SignedCopyMailListener::class);

$context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class);

$context->registerDashboardWidget(PendingSignaturesWidget::class);
Expand Down
2 changes: 1 addition & 1 deletion lib/Controller/RequestSignatureController.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public function __construct(
* For `nodeType=file`, `filesCount=1` and `files` contains the current file.
* For `nodeType=envelope`, `files` contains envelope child files.
*
* @param list<LibresignNewSigner> $signers Collection of signers who must sign the document. Use identifyMethods as the canonical format. Other supported fields: displayName, description, notify, signingOrder, status, deviceGeolocationRequired
* @param list<LibresignNewSigner> $signers Collection of signers who must sign the document. Use identifyMethods as the canonical format. Other supported fields: displayName, description, notify, signingOrder, status, deviceGeolocationRequired, sendSignedCopy
* @param string $name The name of file to sign
* @param LibresignFolderSettings $settings Settings to define how and where the file should be stored
* @param LibresignNewFile $file File object. Supports nodeId (a non-negative integer or its canonical decimal string, as Nextcloud node ids can exceed a JavaScript number), url, base64 or path.
Expand Down
4 changes: 4 additions & 0 deletions lib/Events/SigningRequestCompletedEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ public static function fromTransition(FileEntity $request, int $previousStatus):
return new self($request->getUuid(), $request->isEnvelope() ? 'envelope' : 'document');
}

public function getRequestUuid(): string {
return $this->requestUuid;
}

#[\Override]
public function getWebhookSerializable(): array {
return [
Expand Down
43 changes: 43 additions & 0 deletions lib/Listener/SignedCopyMailListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Libresign\Listener;

use OCA\Libresign\Db\FileMapper;
use OCA\Libresign\Events\SigningRequestCompletedEvent;
use OCA\Libresign\Service\SignedCopyMailService;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;

/**
* Queues the signed copy mails once a request is complete. They are sent
* by the notification delivery job, never from the signing request.
*
* @template-implements IEventListener<Event>
*/
final class SignedCopyMailListener implements IEventListener {
public function __construct(
private FileMapper $fileMapper,
private SignedCopyMailService $signedCopyMailService,
) {
}

#[\Override]
public function handle(Event $event): void {
if (!$event instanceof SigningRequestCompletedEvent) {
return;
}
try {
$file = $this->fileMapper->getByUuid($event->getRequestUuid());
} catch (DoesNotExistException) {
return;
}
$this->signedCopyMailService->queue($file);
}
}
2 changes: 2 additions & 0 deletions lib/ResponseDefinitions.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@
* status?: int,
* participantRole?: LibresignParticipantRole,
* deviceGeolocationRequired?: bool,
* sendSignedCopy?: bool,
* }
* @psalm-type LibresignNewFile = array{
* base64?: string,
Expand Down Expand Up @@ -271,6 +272,7 @@
* uid?: string,
* metadata?: LibresignSignerMetadata,
* rejection?: LibresignSignerRejection,
* sendSignedCopy?: bool,
* }
*
* Notification delivery status
Expand Down
6 changes: 6 additions & 0 deletions lib/Service/File/FileListService.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
use OCA\Libresign\Service\IdentifyMethodService;
use OCA\Libresign\Service\SignatureRejection\RejectionViewer;
use OCA\Libresign\Service\SignatureRejection\SignatureRejectionVisibilityService;
use OCA\Libresign\Service\SignedCopyMailService;
use OCA\Libresign\Service\SignerGeolocation\SignerGeolocationMetadataValidator;
use OCA\Libresign\Service\SignerGeolocation\SignerGeolocationPolicyService;
use OCP\AppFramework\Db\DoesNotExistException;
Expand Down Expand Up @@ -508,6 +509,11 @@ private function formatSignerData(
$data['metadata'] = $geolocationMetadata;
}

if ($requesterUserId !== '' && $user?->getUID() === $requesterUserId
&& ($signer->getMetadata()[SignedCopyMailService::METADATA_KEY] ?? false) === true) {
$data['sendSignedCopy'] = true;
}

/** @var LibresignSignerDetail $data */
$data = $this->signatureRejectionVisibilityService->presentSigner(
$signer,
Expand Down
43 changes: 43 additions & 0 deletions lib/Service/MailService.php
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,49 @@ public function notifySignedUser(SignRequest $signRequest, string $email, File $
}
}

/**
* Sends the fully signed documents of a completed request. Without
* attachments the mail links to the validation page instead.
*
* @param array<string, string> $attachments file name => PDF content
*/
public function notifySignedCopy(File $request, string $email, string $displayName, array $attachments): void {
$emailTemplate = $this->mailer->createEMailTemplate('settings.TestEmail');
// TRANSLATORS Email subject sent with the fully signed document after every participant signed. %s is the document or envelope name.
$emailTemplate->setSubject($this->l10n->t('LibreSign: "%s" has been signed by everyone', [$request->getName()]));
$emailTemplate->addHeader();
// TRANSLATORS Email heading shown when every participant signed the document.
$emailTemplate->addHeading($this->l10n->t('Signed document'), false);
if ($attachments !== []) {
$emailTemplate->addBodyText($this->l10n->n(
// TRANSLATORS Email body sent with the fully signed document attached. %s is the document or envelope name.
'All signatures on "%s" are complete. The signed document is attached.',
'All signatures on "%s" are complete. The signed documents are attached.',
count($attachments),
[$request->getName()],
));
} else {
// TRANSLATORS Email body sent when the fully signed document cannot be attached, for example because it is too large. %s is the document or envelope name.
$emailTemplate->addBodyText($this->l10n->t('All signatures on "%s" are complete. The signed document is too large to attach. You can access it using the link below:', [$request->getName()]));
$emailTemplate->addBodyButton(
// TRANSLATORS Email button label that opens the validation view of the signed document. %s is the document filename.
$this->l10n->t('View signed document "%s"', [$request->getName()]),
$this->buildValidationLink($request),
);
}
$message = $this->mailer->createMessage();
$message->setTo($displayName !== '' ? [$email => $displayName] : [$email]);
$replyTo = $this->replyToAddress($this->userManager->get($request->getUserId()));
if ($replyTo !== null) {
$message->setReplyTo($replyTo);
}
$message->useTemplate($emailTemplate);
foreach ($attachments as $name => $content) {
$message->attach($this->mailer->createAttachment($content, (string)$name, 'application/pdf'));
}
$this->sendAndCheck($message);
}

public function notifyCanceledRequest(SignRequest $signRequest, string $email, File $libreSignFile): void {
$emailTemplate = $this->mailer->createEMailTemplate('settings.TestEmail');
// TRANSLATORS Email subject shown when the requester cancels a pending signature request.
Expand Down
11 changes: 11 additions & 0 deletions lib/Service/Notification/MailChannel.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@
namespace OCA\Libresign\Service\Notification;

use OCA\Libresign\Service\MailService;
use OCA\Libresign\Service\SignedCopyAttachmentProvider;
use OCA\Libresign\Service\SignedCopyMailService;

final class MailChannel implements NotificationChannel {
public function __construct(
private MailService $mail,
private SignedCopyAttachmentProvider $signedCopyAttachments,
) {
}

Expand Down Expand Up @@ -42,6 +45,14 @@ public function deliver(NotificationMessage $message): void {
case 'sign_request_canceled':
$this->mail->notifyCanceledRequest($signRequest, $email, $message->file);
break;
case SignedCopyMailService::EVENT_TYPE:
$this->mail->notifySignedCopy(
$message->file,
$email,
$message->payload->displayName ?? '',
$this->signedCopyAttachments->load($message->file, $message->payload->documentIds),
);
break;
default:
throw new \InvalidArgumentException('Unsupported mail notification event');
}
Expand Down
2 changes: 2 additions & 0 deletions lib/Service/Notification/MailPayload.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@

/** The caller selects the business event; the mail adapter selects its template. */
final readonly class MailPayload implements NotificationPayload {
/** @param list<int> $documentIds Documents attached to a signed copy mail. */
public function __construct(
public ?string $displayName = null,
public bool $firstNotification = false,
public array $documentIds = [],
) {
}
}
4 changes: 4 additions & 0 deletions lib/Service/Notification/NotificationEnvelopeCodec.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public function encode(NotificationMessage $message): string {
'type' => 'mail',
'displayName' => $message->payload->displayName,
'firstNotification' => $message->payload->firstNotification,
'documentIds' => $message->payload->documentIds,
],
$message->payload instanceof GatewayPayload => [
'type' => 'gateway',
Expand Down Expand Up @@ -138,6 +139,9 @@ private function restorePayload(array $payload): NotificationPayload {
'mail' => new MailPayload(
isset($payload['displayName']) ? (string)$payload['displayName'] : null,
$payload['firstNotification'] === true,
array_values(array_map('intval', is_array($payload['documentIds'] ?? [])
? $payload['documentIds'] ?? []
: throw new \UnexpectedValueException('Invalid mail delivery documents'))),
),
'gateway' => new GatewayPayload(
(string)$payload['gatewayName'],
Expand Down
2 changes: 2 additions & 0 deletions lib/Service/Policy/Provider/PolicyProviders.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
use OCA\Libresign\Service\Policy\Provider\SignatureHashAlgorithm\SignatureHashAlgorithmPolicy;
use OCA\Libresign\Service\Policy\Provider\SignatureRejection\SignatureRejectionPolicy;
use OCA\Libresign\Service\Policy\Provider\SignatureText\SignatureTextPolicy;
use OCA\Libresign\Service\Policy\Provider\SignedCopyMail\SignedCopyMailPolicy;
use OCA\Libresign\Service\Policy\Provider\SignerGeolocation\SignerGeolocationPolicy;
use OCA\Libresign\Service\Policy\Provider\SignerIpGeolocation\SignerIpGeolocationPolicy;
use OCA\Libresign\Service\Policy\Provider\Tsa\TsaPolicy;
Expand Down Expand Up @@ -71,6 +72,7 @@ final class PolicyProviders {
IdentifyMethodsPolicy::KEY => IdentifyMethodsPolicy::class,
ObserverProfilePolicy::KEY => ObserverProfilePolicy::class,
SignatureTextPolicy::KEY => SignatureTextPolicy::class,
SignedCopyMailPolicy::KEY => SignedCopyMailPolicy::class,
SignerGeolocationPolicy::KEY => SignerGeolocationPolicy::class,
SignerIpGeolocationPolicy::KEY => SignerIpGeolocationPolicy::class,
TsaPolicy::KEY => TsaPolicy::class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Libresign\Service\Policy\Provider\SignedCopyMail;

use OCA\Libresign\Service\Policy\Contract\IPolicyDefinition;
use OCA\Libresign\Service\Policy\Contract\IPolicyDefinitionProvider;
use OCA\Libresign\Service\Policy\Model\PolicyContext;
use OCA\Libresign\Service\Policy\Model\PolicyLayer;
use OCA\Libresign\Service\Policy\Model\PolicySpec;
use OCA\Libresign\Service\Policy\Provider\Helper\DelegationLayerHelper;
use OCA\Libresign\Service\Policy\Provider\Helper\PolicyKeyNormalizer;

/**
* Mails the fully signed document to the signers chosen by the requester
* and to optional archive addresses once every signature is complete.
* Resolved for the requester when the request completes; disabled by default.
*/
final class SignedCopyMailPolicy implements IPolicyDefinitionProvider {
public const KEY = 'signed_copy_mail';
public const SYSTEM_APP_CONFIG_KEY = self::KEY;

#[\Override]
public function keys(): array {
return [
self::KEY,
];
}

#[\Override]
public function get(string|\BackedEnum $policyKey): IPolicyDefinition {
return match (PolicyKeyNormalizer::normalize($policyKey)) {
self::KEY => new PolicySpec(
key: self::KEY,
defaultSystemValue: SignedCopyMailPolicyValue::encode(SignedCopyMailPolicyValue::defaults()),
allowedValues: static fn (): array => [],
normalizer: static fn (mixed $rawValue): string => SignedCopyMailPolicyValue::encode(SignedCopyMailPolicyValue::normalize($rawValue)),
appConfigKey: self::SYSTEM_APP_CONFIG_KEY,
supportsRequestOverride: false,
requestLifecycle: PolicySpec::LIFECYCLE_RUNTIME,
groupPolicyManager: static function (PolicyContext $context, ?PolicyLayer $systemPolicy, array $groupLayers): bool {
$actorRole = $context->getActorRole();
if ($actorRole->canManageSystemPolicies) {
return true;
}

if (!$actorRole->canManageGroupPolicies || $actorRole->manageableGroupCount < 1) {
return false;
}

return DelegationLayerHelper::hasExplicitGlobalDelegation($systemPolicy)
|| DelegationLayerHelper::hasSystemCreatedGroupDelegation($groupLayers);
},
systemCreatedGroupRuleEditor: static function (PolicyContext $context, ?PolicyLayer $systemPolicy, PolicyLayer $existingPolicy): bool {
$actorRole = $context->getActorRole();
if ($actorRole->canManageSystemPolicies) {
return true;
}

if (!$actorRole->canManageGroupPolicies) {
return false;
}

if (!$existingPolicy->isVisibleToChild() || !$existingPolicy->isAllowChildOverride() || $existingPolicy->getValue() === null) {
return false;
}

if (DelegationLayerHelper::hasExplicitGlobalDelegation($systemPolicy)) {
return true;
}

return $existingPolicy->isCreatedBySystemAdmin();
},
supportsGroupAdminDelegation: true,
),
default => throw new \InvalidArgumentException('Unknown policy key: ' . PolicyKeyNormalizer::normalize($policyKey)),
};
}
}
Loading