1 package File
::KDBX
::Object
;
2 # ABSTRACT: A KDBX database object
7 use Devel
::GlobalDestruction
;
9 use File
::KDBX
::Util
qw(:uuid);
10 use Hash
::Util
::FieldHash
qw(fieldhashes);
11 use List
::Util
qw(first);
12 use Ref
::Util
qw(is_arrayref is_plain_arrayref is_plain_hashref is_ref);
13 use Scalar
::Util
qw(blessed weaken);
16 our $VERSION = '999.999'; # VERSION
18 fieldhashes \
my (%KDBX, %PARENT, %TXNS, %REFS, %SIGNALS);
22 $object = File
::KDBX
::Object-
>new;
23 $object = File
::KDBX
::Object-
>new(%attributes);
24 $object = File
::KDBX
::Object-
>new(\
%data);
25 $object = File
::KDBX
::Object-
>new(\
%data, $kdbx);
27 Construct a new KDBX object
.
29 There
is a subtlety to
take note of
. There
is a significant difference between
:
31 File
::KDBX
::Entry-
>new(username
=> 'iambatman');
35 File
::KDBX
::Entry-
>new({username
=> 'iambatman'}); # WRONG
37 In the first
, an empty object
is first created
and then initialized with whatever I
<attributes
> are
given. In
38 the second
, a hashref
is blessed
and essentially becomes the object
. The significance
is that the hashref
39 key-value pairs will remain as-is so the structure
is expected to adhere to the shape of a raw B
<Object
>
40 (which varies based on the type of object
), whereas with the first the attributes will set the structure
in
41 the correct way
(just like using the object accessors
/ getters / setters
).
43 The second example isn
't I<generally> wrong -- this type of construction is supported for a reason, to allow
44 for working with KDBX objects at a low level -- but it is wrong in this specific case only because
45 C<< {username => $str} >> isn't a valid raw KDBX entry object
. The L
</username
> attribute
is really a proxy
46 for the C
<UserName
> string
, so the equivalent raw entry object should be
47 C
<< {strings
=> {UserName
=> {value
=> $str}}} >>. These are roughly equivalent
:
49 File
::KDBX
::Entry-
>new(username
=> 'iambatman');
50 File
::KDBX
::Entry-
>new({strings
=> {UserName
=> {value
=> 'iambatman'}}});
52 If this explanation went over your head
, that
's fine. Just stick with the attributes since they are typically
53 easier to use correctly and provide the most convenience. If in the future you think of some kind of KDBX
54 object manipulation you want to do that isn't supported by the accessors
and methods
, just know you I
<can
>
55 access an object
's data directly.
63 return $_[0]->clone if @_ == 1 && blessed $_[0] && $_[0]->isa($class);
66 $data = shift if is_plain_hashref($_[0]);
69 $kdbx = shift if @_ % 2 == 1;
72 $args{kdbx} //= $kdbx if defined $kdbx;
74 my $self = bless $data // {}, $class;
76 $self->_set_default_attributes if !$data;
80 sub _set_default_attributes { die 'Not implemented
' }
84 $object = $object->init(%attributes);
86 Called by the constructor to set attributes. You normally should not call this.
94 while (my ($key, $val) = each %args) {
95 if (my $method = $self->can($key)) {
105 $object = File::KDBX::Object->wrap($object);
107 Ensure that a KDBX object is blessed.
114 return $object if blessed $object && $object->isa($class);
115 return $class->new(@_, @$object) if is_arrayref($object);
116 return $class->new($object, @_);
121 $label = $object->label;
122 $object->label($label);
124 Get or set the object's label
, a text string that can act as a non-unique identifier
. For an entry
, the label
125 is its title string
. For a group
, the label
is its name
.
129 sub label
{ die 'Not implemented' }
133 $object_copy = $object->clone;
134 $object_copy = File
::KDBX
::Object-
>new($object);
136 Make a clone of an object
. By
default the clone
is indeed an exact copy that
is associated with the same
137 database but
not actually included
in the object tree
(i
.e
. it
has no parent
). Some options are allowed to
138 get different effects
:
141 * C<new_uuid> - If set, generate a new UUID for the copy (default: false)
142 * C<parent> - If set, add the copy to the same parent group, if any (default: false)
143 * C<relabel> - If set, append " - Copy" to the object's title or name (default: false)
144 * C<entries> - If set, copy child entries, if any (default: true)
145 * C<groups> - If set, copy child groups, if any (default: true)
146 * C<history> - If set, copy entry history, if any (default: true)
147 * C<reference_password> - Toggle whether or not cloned entry's Password string should be set as a field
148 reference to the original entry's Password string (default: false)
149 * C<reference_username> - Toggle whether or not cloned entry's UserName string should be set as a field
150 reference to the original entry's UserName string (default: false)
154 my %CLONE = (entries
=> 1, groups
=> 1, history
=> 1);
159 local $CLONE{new_uuid
} = $args{new_uuid
} // $args{parent
} // 0;
160 local $CLONE{entries
} = $args{entries
} // 1;
161 local $CLONE{groups
} = $args{groups
} // 1;
162 local $CLONE{history
} = $args{history
} // 1;
163 local $CLONE{reference_password
} = $args{reference_password
} // 0;
164 local $CLONE{reference_username
} = $args{reference_username
} // 0;
167 my $copy = Storable
::dclone
($self);
169 if ($args{relabel
} and my $label = $self->label) {
170 $copy->label("$label - Copy");
172 if ($args{parent
} and my $parent = $self->parent) {
173 $parent->add_object($copy);
179 sub STORABLE_freeze
{
184 delete $copy->{entries
} if !$CLONE{entries
};
185 delete $copy->{groups
} if !$CLONE{groups
};
186 delete $copy->{history
} if !$CLONE{history
};
188 return ($cloning ? Hash
::Util
::FieldHash
::id
($self) : ''), $copy;
197 @$self{keys %$copy} = values %$copy;
200 my $kdbx = $KDBX{$addr};
201 $self->kdbx($kdbx) if $kdbx;
204 if (defined $self->{uuid
}) {
205 if (($CLONE{reference_password
} || $CLONE{reference_username
}) && $self->can('strings')) {
206 my $uuid = format_uuid
($self->{uuid
});
208 local $CLONE{new_uuid
} = 0;
209 local $CLONE{entries
} = 1;
210 local $CLONE{groups
} = 1;
211 local $CLONE{history
} = 1;
212 local $CLONE{reference_password
} = 0;
213 local $CLONE{reference_username
} = 0;
214 # Clone only the entry's data and manually bless to avoid infinite recursion.
215 bless Storable
::dclone
({%$copy}), 'File::KDBX::Entry';
217 my $txn = $self->begin_work(snapshot
=> $clone_obj);
218 if ($CLONE{reference_password
}) {
219 $self->password("{REF:P\@I:$uuid}");
221 if ($CLONE{reference_username
}) {
222 $self->username("{REF:U\@I:$uuid}");
226 $self->uuid(generate_uuid
) if $CLONE{new_uuid
};
229 # Dualvars aren't cloned as dualvars, so dualify the icon.
230 $self->icon_id($self->{icon_id
}) if defined $self->{icon_id
};
235 $kdbx = $object->kdbx;
236 $object->kdbx($kdbx);
238 Get
or set the L
<File
::KDBX
> instance associated with this object
.
244 $self = $self->new if !ref $self;
246 if (my $kdbx = shift) {
247 $KDBX{$self} = $kdbx;
254 $KDBX{$self} or throw
'Object is disassociated from a KDBX database', object
=> $self;
259 $string_uuid = $object->id;
260 $string_uuid = $object->id($delimiter);
262 Get the unique identifier
for this object as a B
<formatted
> UUID string
, typically
for display purposes
. You
263 could
use this to compare with other identifiers formatted with the same delimiter
, but it
is more efficient
264 to
use the raw UUID
for that purpose
(see L
</uuid
>).
266 A delimiter can optionally be provided to
break up the UUID string visually
. See
267 L
<File
::KDBX
::Util
/format_uuid
>.
271 sub id
{ format_uuid
(shift-
>uuid, @_) }
277 $group = $object->group;
279 $group = $object->parent;
281 Get the parent group to which an object belongs
or C
<undef> if it belongs to
no group
.
287 my $id = Hash
::Util
::FieldHash
::id
($self);
288 if (my $group = $PARENT{$self}) {
289 my $method = $self->_parent_container;
290 return $group if first
{ $id == Hash
::Util
::FieldHash
::id
($_) } @{$group->$method};
291 delete $PARENT{$self};
293 # always get lineage from root to leaf because the other way requires parent, so it would be recursive
294 my $lineage = $self->kdbx->_trace_lineage($self) or return;
295 my $group = pop @$lineage or return;
296 $PARENT{$self} = $group; weaken
$PARENT{$self};
300 sub parent
{ shift-
>group(@_) }
304 if (my $parent = shift) {
305 $PARENT{$self} = $parent;
306 weaken
$PARENT{$self};
309 delete $PARENT{$self};
314 ### Name of the parent attribute expected to contain the object
315 sub _parent_container
{ die 'Not implemented' }
319 \
@lineage = $object->lineage;
320 \
@lineage = $object->lineage($base_group);
322 Get the direct line of ancestors from C
<$base_group> (default: the root group
) to an object
. The lineage
323 includes the base group but I
<not> the target object
. Returns C
<undef> if the target
is not in the database
324 structure
. Returns an empty arrayref
is the object itself
is a root group
.
332 my $base_addr = $base ? Hash
::Util
::FieldHash
::id
($base) : 0;
337 while ($o = $o->parent) {
339 last if $base_addr == Hash
::Util
::FieldHash
::id
($o);
341 return \
@path if @path && ($base_addr == Hash
::Util
::FieldHash
::id
($path[0]) || $path[0]->is_root);
344 return $self->kdbx->_trace_lineage($self, $base);
349 $object = $object->remove;
351 Remove the object from the database
. If the object
is a group
, all contained objects are removed as well
.
357 my $parent = $self->parent;
358 $parent->remove_object($self) if $parent;
364 @tags = $entry->tag_list;
366 Get a list of tags
, split from L
</tag
> using delimiters C
<,>, C
<.>, C
<:>, C
<;> and whitespace
.
372 return grep { $_ ne '' } split(/[,\.:;]|\s+/, trim
($self->tags) // '');
377 $image_data = $object->custom_icon;
378 $image_data = $object->custom_icon($image_data, %attributes);
380 Get
or set an icon image
. Returns C
<undef> if there
is no custom icon set
. Setting a custom icon will change
381 the L
</custom_icon_uuid
> attribute
.
383 Custom icon attributes
(supported
in KDBX4
.1
and greater
):
386 * C<name> - Name of the icon (text)
387 * C<last_modification_time> - Just what it says (datetime)
393 my $kdbx = $self->kdbx;
396 my $uuid = defined $img ? $kdbx->add_custom_icon($img, @_) : undef;
397 $self->icon_id(0) if $uuid;
398 $self->custom_icon_uuid($uuid);
401 return $kdbx->custom_icon_data($self->custom_icon_uuid);
406 \
%all_data = $object->custom_data;
407 $object->custom_data(\
%all_data);
409 \
%data = $object->custom_data($key);
410 $object->custom_data($key => \
%data);
411 $object->custom_data(%data);
412 $object->custom_data(key
=> $value, %data);
414 Get
and set custom data
. Custom data
is metadata associated with an object
.
416 Each data item can have a few attributes associated with it
.
419 * C<key> - A unique text string identifier used to look up the data item (required)
420 * C<value> - A text string value (required)
421 * C<last_modification_time> (optional, KDBX4.1+)
427 $self->{custom_data
} = shift if @_ == 1 && is_plain_hashref
($_[0]);
428 return $self->{custom_data
} //= {} if !@_;
430 my %args = @_ == 2 ? (key
=> shift, value
=> shift)
431 : @_ % 2 == 1 ? (key
=> shift, @_) : @_;
433 if (!$args{key
} && !$args{value
}) {
434 my %standard = (key
=> 1, value
=> 1, last_modification_time
=> 1);
435 my @other_keys = grep { !$standard{$_} } keys %args;
436 if (@other_keys == 1) {
437 my $key = $args{key
} = $other_keys[0];
438 $args{value
} = delete $args{$key};
442 my $key = $args{key
} or throw
'Must provide a custom_data key to access';
444 return $self->{custom_data
}{$key} = $args{value
} if is_plain_hashref
($args{value
});
446 while (my ($field, $value) = each %args) {
447 $self->{custom_data
}{$key}{$field} = $value;
449 return $self->{custom_data
}{$key};
452 =method custom_data_value
454 $value = $object->custom_data_value($key);
456 Exactly the same as L
</custom_data
> except returns just the custom data
's value rather than a structure of
457 attributes. This is a shortcut for:
459 my $data = $object->custom_data($key);
460 my $value = defined $data ? $data->{value} : undef;
464 sub custom_data_value {
466 my $data = $self->custom_data(@_) // return undef;
467 return $data->{value};
470 ##############################################################################
476 if ($self->_in_txn) {
477 my $stack = $self->_signal_stack;
478 my $queue = $stack->[-1];
479 push @$queue, [$type, @_];
482 $self->_signal_send([[$type, @_]]);
485 sub _signal_stack { $SIGNALS{$_[0]} //= [] }
487 sub _signal_begin_work {
489 push @{$self->_signal_stack}, [];
494 my $signals = pop @{$self->_signal_stack};
495 my $previous = $self->_signal_stack->[-1] // [];
496 push @$previous, @$signals;
500 sub _signal_rollback {
502 pop @{$self->_signal_stack};
507 my $signals = shift // [];
509 my $kdbx = $KDBX{$self} or return;
511 # de-duplicate, keeping the most recent signal for each type
513 my @signals = grep { !$seen{$_->[0]}++ } reverse @$signals;
515 for my $sig (reverse @signals) {
516 $kdbx->_handle_signal($self, @$sig);
520 ##############################################################################
524 $txn = $object->begin_work(%options);
525 $object->begin_work(%options);
527 Begin a new transaction. Returns a L<File::KDBX::Transaction> object that can be scoped to ensure a rollback
528 occurs if exceptions are thrown. Alternatively, if called in void context, there will be no
529 B<File::KDBX::Transaction> and it is instead your responsibility to call L</commit> or L</rollback> as
530 appropriate. It is undefined behavior to call these if a B<File::KDBX::Transaction> exists. Recursive
531 transactions are allowed.
533 Signals created during a transaction are delayed until all transactions are resolved. If the outermost
534 transaction is committed, then the signals are de-duplicated and delivered. Otherwise the signals are dropped.
535 This means that the KDBX database will not fix broken references or mark itself dirty until after the
536 transaction is committed.
538 How it works: With the beginning of a transaction, a snapshot of the object is created. In the event of
539 a rollback, the object's data
is replaced with data from the snapshot
.
541 By
default, the snapshot
is shallow
(i
.e
. does not include subroups
, entries
or historical entries
). This
542 means that only modifications to the object itself
(its data
, fields
, strings
, etc
.) are atomic
; modifications
543 to subroups etc
., including adding
or removing items
, are auto-committed instantly
and will persist regardless
544 of the result of the pending transaction
. You can override this
for groups
, entries
and history independently
548 * C<entries> - If set, snapshot entries within a group, deeply (default: false)
549 * C<groups> - If set, snapshot subroups within a group, deeply (default: false)
550 * C<history> - If set, snapshot historical entries within an entry (default: false)
552 For example, if you begin a transaction on a group object using the C<entries> option, like this:
554 $group->begin_work(entries => 1);
556 Then if you modify any of the group's entries OR add new entries OR delete entries, all of that will be undone
557 if the transaction is rolled back. With a default-configured transaction, however, changes to entries are kept
558 even if the transaction is rolled back.
565 if (defined wantarray) {
566 require File
::KDBX
::Transaction
;
567 return File
::KDBX
::Transaction-
>new($self, @_);
571 my $orig = $args{snapshot
} // do {
572 my $c = $self->clone(
573 entries
=> $args{entries
} // 0,
574 groups
=> $args{groups
} // 0,
575 history
=> $args{history
} // 0,
577 $c->{entries
} = $self->{entries
} if !$args{entries
};
578 $c->{groups
} = $self->{groups
} if !$args{groups
};
579 $c->{history
} = $self->{history
} if !$args{history
};
583 my $id = Hash
::Util
::FieldHash
::id
($orig);
584 _save_references
($id, $self, $orig);
586 $self->_signal_begin_work;
588 push @{$self->_txns}, $orig;
595 Commit a transaction
, making updates to C
<$object> permanent
. Returns itself to allow
method chaining
.
601 my $orig = pop @{$self->_txns} or return $self;
602 $self->_commit($orig);
603 my $signals = $self->_signal_commit;
604 $self->_signal_send($signals) if !$self->_in_txn;
608 sub _commit
{ die 'Not implemented' }
609 sub _in_txn
{ scalar @{$_[0]->_txns} }
610 sub _txns
{ $TXNS{$_[0]} //= [] }
616 Roll back the most recent transaction
, throwing away any updates to the L
</object
> made since the transaction
617 began
. Returns itself to allow
method chaining
.
624 my $orig = pop @{$self->_txns} or return $self;
626 my $id = Hash
::Util
::FieldHash
::id
($orig);
627 _restore_references
($id, $orig);
629 $self->_signal_rollback;
634 sub _save_references
{
639 if (is_plain_arrayref
($orig)) {
640 for (my $i = 0; $i < @$orig; ++$i) {
641 _save_references
($id, $self->[$i], $orig->[$i]);
643 $REFS{$id}{Hash
::Util
::FieldHash
::id
($orig)} = $self;
645 elsif (is_plain_hashref
($orig) || (blessed
$orig && $orig->isa(__PACKAGE__
))) {
646 for my $key (keys %$orig) {
647 _save_references
($id, $self->{$key}, $orig->{$key});
649 $REFS{$id}{Hash
::Util
::FieldHash
::id
($orig)} = $self;
653 sub _restore_references
{
655 my $orig = shift // return;
656 my $self = delete $REFS{$id}{Hash
::Util
::FieldHash
::id
($orig) // ''} // return $orig;
658 if (is_plain_arrayref
($orig)) {
659 @$self = map { _restore_references
($id, $_) } @$orig;
661 elsif (is_plain_hashref
($orig) || (blessed
$orig && $orig->isa(__PACKAGE__
))) {
662 for my $key (keys %$orig) {
663 # next if is_ref($orig->{$key}) &&
664 # (Hash::Util::FieldHash::id($self->{$key}) // 0) == Hash::Util::FieldHash::id($orig->{$key});
665 $self->{$key} = _restore_references
($id, $orig->{$key});
674 my ($orig) = @{$self->_txns};
675 return $orig // $self;
678 ##############################################################################
683 require File
::KDBX
::Group
;
684 return File
::KDBX
::Group-
>wrap($group, $KDBX{$self});
690 require File
::KDBX
::Entry
;
691 return File
::KDBX
::Entry-
>wrap($entry, $KDBX{$self});
694 sub TO_JSON
{ +{%{$_[0]}} }
699 =for Pod::Coverage STORABLE_freeze STORABLE_thaw TO_JSON
703 KDBX is an object database. This abstract class represents an object. You should not use this class directly
704 but instead use its subclasses:
707 * L<File::KDBX::Entry>
708 * L<File::KDBX::Group>
710 There is some functionality shared by both types of objects, and that's what this class provides.
712 Each object can be associated with a L<File::KDBX> database or be disassociated. A disassociated object will
713 not be persisted when dumping a database. It is also possible for an object to be associated with a database
714 but not be part of the object tree (i.e. is not the root group or any subroup or entry). A disassociated
715 object or an object not part of the object tree of a database can be added to a database using one of:
718 * L<File::KDBX/add_entry>
719 * L<File::KDBX/add_group>
720 * L<File::KDBX::Group/add_entry>
721 * L<File::KDBX::Group/add_group>
722 * L<File::KDBX::Entry/add_historical_entry>
724 It is possible to copy or move objects between databases, but you B<DO NOT> include the same object in more
725 than one database at once or there could some strange aliasing effects (i.e. changes in one database might
726 effect another in unexpected ways). This could lead to difficult-to-debug problems. It is similarly not safe
727 or valid to add the same object multiple times to the same database. For example:
729 my $entry = File::KDBX::Entry->(title => 'Whatever');
732 $kdbx->add_entry($entry);
733 $another_kdbx->add_entry($entry);
736 $kdbx->add_entry($entry);
737 $kdbx->add_entry($entry); # again
741 # Copy an entry to multiple databases:
742 $kdbx->add_entry($entry);
743 $another_kdbx->add_entry($entry->clone);
745 # OR move an existing entry from one database to another:
746 $kdbx->add_entry($entry->remove);