Compare commits

..

307 Commits

Author SHA1 Message Date
4cb6f07a68 Merge pull request 'issue-236-fixed' (#239) from issue-236-fixed into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m22s
Reviewed-on: #239
Reviewed-by: enes <enes@noreply.git.nostrdev.com>
2024-11-04 07:43:58 +00:00
NostrDev
5b1654c341 chore: added handleEscapeButtonDown description
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 35s
2024-11-04 10:42:55 +03:00
.
02f651acc7 chore: revert (wrong site)
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m25s
2024-11-02 11:40:20 +00:00
.
cd0e4523e1 chore: goat@nostrdev.com
Some checks failed
Release to Staging / build_and_release (push) Has been cancelled
2024-11-02 11:39:36 +00:00
NostrDev
76b1fa792c feat(signers-dropdown): improved hiding/displaying logic
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 31s
2024-11-01 17:00:46 +03:00
NostrDev
3a94fbc0ae chore(types): used KeyboardCode enum
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 31s
2024-11-01 11:23:05 +03:00
NostrDev
e37f90d6db feat(pdf-fields): add logic to hide signers on ESC 2024-11-01 11:22:31 +03:00
b
cc059f6cb4 Merge pull request 'feat: signature squiggle' (#237) from feat/signature into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m33s
Reviewed-on: #237
Reviewed-by: b <b@4j.cx>
2024-10-28 16:23:28 +00:00
enes
de44370a96 feat: add squiggle support
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 36s
2024-10-25 18:42:16 +02:00
enes
dfa2832e8d feat: add MarkConfig and components 2024-10-25 18:40:50 +02:00
enes
9286e4304f feat: add SVGO, enable signature 2024-10-25 18:38:47 +02:00
aae11589a4 Merge pull request 'issue-166-open-timestamps' (#220) from issue-166-open-timestamps into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m16s
Reviewed-on: #220
Reviewed-by: enes <enes@noreply.git.nostrdev.com>
2024-10-25 11:18:46 +00:00
69f67fc812 chore: disables rules for specific parts of code
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 30s
2024-10-25 14:15:12 +03:00
38cd88fd86 fix: moves styling to SVG
Some checks failed
Open PR on Staging / audit_and_check (pull_request) Failing after 32s
2024-10-25 13:13:22 +03:00
dbcd54cec0 chore: merge branch 'main' into issue-166-open-timestamps
Some checks failed
Open PR on Staging / audit_and_check (pull_request) Failing after 27s
2024-10-24 15:58:39 +03:00
2d0212fd6c fix: redundant updates
Some checks failed
Open PR on Staging / audit_and_check (pull_request) Failing after 32s
2024-10-24 12:54:47 +03:00
19b815e528 feat(opentimestamps): updates tooltip
Some checks failed
Open PR on Staging / audit_and_check (pull_request) Failing after 27s
2024-10-24 12:42:21 +03:00
b
33e7fc7771 Merge pull request 'Release' (#233) from staging into main
All checks were successful
Release to Production / build_and_release (push) Successful in 1m9s
Reviewed-on: #233
2024-10-18 15:09:39 +00:00
97d9857bef Merge branch 'main' into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m18s
2024-10-18 14:59:01 +00:00
enes
4465b8c3ac refactor(landing): cards description
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m19s
2024-10-18 16:54:31 +02:00
54047740f9 chore: updates packages 2024-10-18 11:26:25 +03:00
7f411f09a7 chore: merge branch 'main' into issue-166-open-timestamps 2024-10-18 11:24:31 +03:00
849e47da00 chore: updates packages 2024-10-18 11:03:51 +03:00
b
bb323be87c Merge pull request 'Release' (#228) from staging into main
All checks were successful
Release to Production / build_and_release (push) Successful in 1m8s
Reviewed-on: #228
2024-10-14 09:02:41 +00:00
b
fd2f179273 Merge branch 'main' into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m18s
2024-10-14 09:02:14 +00:00
b
4559f16d86 Merge pull request 'fix: add files and marked to sign page exports' (#226) from fixes-10-11 into staging
Some checks failed
Release to Staging / build_and_release (push) Has been cancelled
Reviewed-on: #226
2024-10-14 09:01:42 +00:00
d6f92accb0 chore(git): merge branch 'origin/fixes-10-11' into fixes-10-11
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-10-14 09:56:22 +02:00
b
ee03cc545e Merge branch 'staging' into fixes-10-11
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-10-13 12:47:38 +00:00
b
70e525357c Merge pull request 'feat: handle root _@ users on add counterpart' (#225) from adding-domain-user-10-10 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m23s
Reviewed-on: #225
Reviewed-by: eugene <eugene@nostrdev.com>
2024-10-13 12:46:55 +00:00
b
3eed2964a0 Merge branch 'staging' into fixes-10-11
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-10-12 11:19:14 +00:00
b
3a0f155010 Merge pull request 'fix: processing events, stale sigits' (#227) from hotfix-processing-events-10-12 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m21s
Reviewed-on: #227
2024-10-12 11:18:46 +00:00
1d1986f082 fix: clear hasSubscribed after the logout
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 35s
2024-10-12 12:05:55 +02:00
25764c7ab4 fix: processing events
Partially revert to before 23a04faad8
2024-10-12 11:52:43 +02:00
cc382f0726 fix: show error if decrypt fails 2024-10-11 16:43:55 +02:00
9dd190d65b fix: add files and marked to sign page exports
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
Skip marked if the file contains  no marks
2024-10-11 16:16:59 +02:00
c3dacbe111 fix: add mark label
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-10-11 15:05:28 +02:00
897daaa1fa feat: handle root _@ users on add counterpart
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 35s
2024-10-10 13:56:08 +02:00
b
ed90168e5d Merge pull request 'staging' (#223) from staging into main
All checks were successful
Release to Production / build_and_release (push) Successful in 1m8s
Reviewed-on: #223
2024-10-09 13:50:23 +00:00
b
7f5fd4534f Merge branch 'main' into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m20s
2024-10-09 13:48:05 +00:00
b
7f172178a1 Merge pull request 'feat: include marked and original files in zip' (#222) from 203-export-original-and-modified into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m23s
Reviewed-on: #222
Reviewed-by: b <b@4j.cx>
2024-10-09 13:43:02 +00:00
1116867224 refactor: rename functions and labels
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-10-09 11:52:32 +02:00
db9cf9d20c feat: include the original files always 2024-10-09 11:51:26 +02:00
58c457b62c fix: profile image scale 2024-10-09 10:58:31 +02:00
b6846c0006 chore(git): merge pull request #217 from nostr-login-9-30 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m18s
Reviewed-on: #217
Reviewed-by: eugene <eugene@nostrdev.com>
2024-10-09 08:54:33 +00:00
8deb5bd7cd Merge branch 'staging' into nostr-login-9-30
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-10-09 08:35:13 +00:00
7b7f23a779 chore(git): merge pull request #221 from beta-release into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m16s
Reviewed-on: #221
2024-10-09 08:33:52 +00:00
db4a202363 refactor: update banner and package for beta release
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-10-08 20:31:03 +02:00
3a507246ca refactor: add comments
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-10-08 20:25:34 +02:00
f09d9b2378 refactor(ts): remove type assertion
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-10-08 20:14:44 +02:00
fe9f282984 Merge branch 'staging' into nostr-login-9-30
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-10-08 18:06:40 +00:00
aa4637dd0d refactor(login): add comments
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-10-08 19:12:21 +02:00
23a04faad8 refactor(auth): main effect order and deps
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-10-08 18:50:33 +02:00
ad2ec070be refactor(reducers): match state types and reducers 2024-10-08 18:42:34 +02:00
d610c79cad refactor: use useAppDispatch, useAppSelector hooks 2024-10-08 17:08:43 +02:00
b7bd922af3 fix: removes unneeded notification
Some checks failed
Open PR on Staging / audit_and_check (pull_request) Failing after 31s
2024-10-08 17:04:07 +02:00
f12aaf1c2b feat(opentimestamps): amends to flow to only upgrade users timestamps
Some checks failed
Open PR on Staging / audit_and_check (pull_request) Failing after 32s
2024-10-08 17:01:51 +02:00
6c5ed3a69c fix: typo 2024-10-08 13:47:30 +02:00
862012e405 refactor: update kind 27235 auth event with recommendations from nip98 2024-10-08 13:46:54 +02:00
8689c7f753 fix: remove screen on nostr-login launch
Ignores the init options param when screen is passed
2024-10-08 13:45:58 +02:00
b
a3c45b504e Merge pull request 'Release Oct 7th' (#218) from staging into main
All checks were successful
Release to Production / build_and_release (push) Successful in 1m10s
Reviewed-on: #218
2024-10-08 09:02:11 +00:00
b
da30dba368 Merge branch 'main' into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m15s
2024-10-08 08:59:35 +00:00
.
51e2ab6f8a chore: lint fix
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m18s
2024-10-08 09:57:44 +01:00
.
9091bbc251 chore: landing page wording
Some checks failed
Release to Staging / build_and_release (push) Failing after 33s
2024-10-07 22:55:48 +01:00
331759de5c refactor: add useCallback, add methods and split effects
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-10-07 20:37:46 +02:00
995c7ce293 feat(auth): nsec login with url params
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-10-07 19:17:19 +02:00
3d5006a715 fix: removes retrier and updates notification
Some checks failed
Open PR on Staging / audit_and_check (pull_request) Failing after 30s
2024-10-07 17:24:25 +02:00
f38344b9ac fix: adds notifications 2024-10-07 17:20:00 +02:00
2b630c94b6 feat(opentimestamps): updates the flow and adds notifications 2024-10-07 17:19:32 +02:00
edeb22fb37 chore: updates namings 2024-10-07 17:18:27 +02:00
a2138f1de1 feat(opentimestamps): updates utils and adds comments 2024-10-07 17:18:06 +02:00
85bf907f54 feat(opentimestamps): updates data model 2024-10-07 17:17:37 +02:00
3b447dcf6a chore: merge branch 'main' into issue-166-open-timestamps 2024-10-07 16:18:29 +02:00
532cdaed8e refactor(auth): open nostr-login directly 2024-10-07 15:36:29 +02:00
67d545de2f fix: show import/export only for local 2024-10-07 13:44:04 +02:00
637e26bf35 refactor: init nostr-login, login method strategies, remove bunker 2024-10-07 13:36:45 +02:00
110621a125 feat: add nostrLoginAuthMethod to state 2024-10-07 13:36:45 +02:00
59e153595a refactor: z-index levels 2024-10-07 13:36:45 +02:00
0b79ebd909 refactor: z-index levels 2024-10-07 13:36:45 +02:00
e2dbed2b03 refactor: add nostr-login package, show not-allowed on disabled form fields 2024-10-07 13:36:45 +02:00
7c26edf84e chore(git): merge pull request #219 from fixes-10-7 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m20s
Reviewed-on: #219
Reviewed-by: eugene <eugene@nostrdev.com>
2024-10-07 11:27:41 +00:00
2d7bb234f4 refactor: next on each mark, including the final one
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-10-07 12:59:55 +02:00
c4d50293ff refactor: toolbox order 2024-10-07 12:53:43 +02:00
b
89971fb176 Merge pull request 'Add Sigit ID as a path param' (#195) from issue-171 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m17s
Reviewed-on: #195
Reviewed-by: enes <enes@noreply.git.nostrdev.com>
2024-10-07 09:16:30 +00:00
b
acad24dc06 Merge branch 'staging' into issue-171
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-10-07 09:15:38 +00:00
.
55abe814c9 fix: AGPL Licence, closes #197
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m21s
2024-10-06 20:28:27 +01:00
21aa25a42a feat(opentimestamps): update the full flow 2024-10-06 15:37:04 +02:00
b
e33996c1f9 Merge branch 'staging' into issue-171
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 35s
2024-10-05 21:02:40 +00:00
edbe708b65 feat(opentimestamps): updates data model and useSigitMeta hook 2024-10-02 14:47:32 +02:00
b
7056ad3cd3 Merge pull request 'Release to main' (#216) from staging into main
All checks were successful
Release to Production / build_and_release (push) Successful in 1m16s
Reviewed-on: #216
2024-10-01 20:19:09 +00:00
b
7dffe75bd7 Merge branch 'main' into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m24s
2024-10-01 20:15:23 +00:00
8da2510a18 Merge pull request #206 from 201-toolbox-update into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m20s
Reviewed-on: #206
Reviewed-by: eugene <eugene@nostrdev.com>
2024-09-30 14:20:07 +00:00
b92790ceed feat(opentimestamps): updates opentimestamps type 2024-09-27 16:03:40 +03:00
7f00f9e8bf feat(opentimestamps): updates signing flow 2024-09-27 16:00:48 +03:00
07f1a15aa1 feat(opentimestamps): refactors to timestamp the nostr event id 2024-09-27 14:18:26 +03:00
85bcfac2e0 feat(opentimestamps): adds timestamps to create flow 2024-09-26 15:54:06 +03:00
edfe9a2954 feat(opentimestamps): adds OTS library and retrier function 2024-09-26 15:50:28 +03:00
633c23e459 refactor: center banner notice text
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-20 11:29:35 +02:00
2e1d48168a refactor: rename userId to npub
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-20 11:13:48 +02:00
e05d3e53a2 fix: remove duplicate states and fix default signer 2024-09-20 10:26:32 +02:00
d8d51be603 fix: add small avatar when select is not showing 2024-09-19 15:05:03 +02:00
5f92906032 fix: add file and page index, hide select if not active 2024-09-19 15:02:19 +02:00
70cca9dd10 refactor: add getProfileUsername utility func 2024-09-19 14:46:22 +02:00
9bae5b9ba2 Merge branch 'staging' into 201-toolbox-update
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-09-19 11:31:03 +00:00
9432e99b3b chore(git): merge pull request #212 from 186-header-design into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m17s
Reviewed-on: #212
Reviewed-by: eugene <eugene@nostrdev.com>
2024-09-19 11:30:46 +00:00
ff875cc9d7 chore(git): merge pull request #208 from 184-upload-add into staging
Some checks failed
Release to Staging / build_and_release (push) Has been cancelled
Reviewed-on: #208
Reviewed-by: eugene <eugene@nostrdev.com>
2024-09-19 11:29:44 +00:00
a1bf88d243 chore(git): merge pull request #207 from 145-default-signer into 201-toolbox-update
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
Reviewed-on: #207
2024-09-19 11:24:16 +00:00
67c3c74515 Merge branch '201-toolbox-update' into 145-default-signer 2024-09-19 11:20:05 +00:00
f81f2b0523 refactor: better variable names
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-09-19 13:15:54 +02:00
182ef40d8d Merge branch 'staging' into 201-toolbox-update
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-19 10:00:45 +00:00
39934f59c3 fix: last signer as default next
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-19 11:46:34 +02:00
d45ea63c20 refactor: remove header height from calc
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-19 10:53:53 +02:00
b
dd97dfbaf0 Merge pull request 'New release' (#210) from staging into main
All checks were successful
Release to Production / build_and_release (push) Successful in 1m11s
Reviewed-on: #210
Reviewed-by: eugene <eugene@nostrdev.com>
2024-09-19 08:23:14 +00:00
aec0d0bdd8 fix: center block scrolling on mark items 2024-09-19 09:54:51 +02:00
5f39b55f68 feat: add banner and styling 2024-09-19 09:54:19 +02:00
ebd59471c7 fix: footer portal on relays 2024-09-19 09:53:16 +02:00
c2a149c872 Merge branch 'main' into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m18s
2024-09-18 15:12:47 +00:00
0091d3ec9e Merge pull request 'Update Blossom Event' (#209) from blossom-upgrade into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m20s
Reviewed-on: #209
Reviewed-by: enes <enes@noreply.git.nostrdev.com>
2024-09-18 15:09:31 +00:00
dd53ded518 fix: updates blossom authorisation event
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-18 17:57:36 +03:00
6d78d9ed64 fix(create): uploading file adds to the existing file list, dedupe file list
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
Closes #184
2024-09-17 17:56:53 +02:00
dfdcb8419d fix(marks): add default signer
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-09-17 17:27:37 +02:00
f8a4480994 refactor(toolbox): reduce number of mark types
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
Closes #201
2024-09-17 17:22:15 +02:00
c52fecdf4e chore(git): merge pull request #204 from 176-178-pdf-quality-multiline into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m18s
Reviewed-on: #204
Reviewed-by: eugene <eugene@nostrdev.com>
2024-09-17 13:59:17 +00:00
43beac48e8 fix(pdf): keep upscaling to match viewport
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-17 14:41:54 +02:00
f35e2718ab fix(pdf): mark embedding, position, multiline, & placeholder
Closes  #176, #178
2024-09-17 14:33:50 +02:00
6ba3b6ec89 Merge branch 'staging' into issue-171
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-16 12:37:39 +00:00
84c374bb2c chore(git): merge pull request #198 from 196-ext-login-infinite-loading into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m18s
Reviewed-on: #198
Reviewed-by: eugene <eugene@nostrdev.com>
2024-09-16 12:27:43 +00:00
a53914b59d Merge branch 'staging' into 196-ext-login-infinite-loading
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 35s
2024-09-16 12:19:09 +00:00
68c10d1831 chore(git): merge pull request #202 from offline-flow-9-13 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m19s
Reviewed-on: #202
Reviewed-by: s <s@noreply.git.nostrdev.com>
2024-09-16 12:18:18 +00:00
b
5a2a0ad9c4 Merge branch 'staging' into 196-ext-login-infinite-loading
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-09-16 11:45:22 +00:00
62c1f1b37b fix: add show username
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-16 12:06:11 +02:00
8267eb624b fix: add keys and show name for counterparts
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-16 11:06:55 +02:00
e1c750495e refactor: useSigitProfiles removed, per user profile hook in avatar, refactor name tooltip 2024-09-16 11:06:55 +02:00
8b00ef538b fix: unzip and use timeout util 2024-09-16 11:06:55 +02:00
13254fbe06 feat: add exportedBy to useSigitMeta 2024-09-16 11:06:55 +02:00
1dfab7b82b refactor: metadatacontroller as singleton 2024-09-16 11:06:55 +02:00
759a40a4f9 fix(verify): offline flow 2024-09-16 11:06:55 +02:00
8b4f1a8973 fix(online-detection): use relative url
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 35s
2024-09-16 11:00:16 +02:00
79ef9eb8d6 fix: url
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-13 17:47:55 +02:00
b
aa8214d015 Merge branch 'staging' into issue-171
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-13 10:07:24 +00:00
ba24e7417d refactor: log timeout error only, no toast
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-13 11:14:10 +02:00
ea7e3a0964 refactor: update url for online status 2024-09-13 11:06:06 +02:00
b
675a763af3 Merge pull request 'New Release' (#200) from staging into main
All checks were successful
Release to Production / build_and_release (push) Successful in 1m13s
Reviewed-on: #200
Reviewed-by: enes <enes@noreply.git.nostrdev.com>
2024-09-12 12:17:47 +00:00
bf1b3beb63 Merge branch 'main' into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m17s
2024-09-12 12:09:40 +00:00
2e58b58a6a refactor: move publish button to the bottom
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-09-12 13:30:59 +02:00
17c1700554 fix(login): use const and make sure to clear timeout always
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-12 13:24:05 +02:00
9191336722 refactor(login): update the delay message and increase timers 2024-09-12 12:17:58 +02:00
32a6f9d7a3 Merge pull request #199 from hotfix-remove-loop-9-12 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m16s
Reviewed-on: #199
Reviewed-by: eugene <eugene@nostrdev.com>
2024-09-12 09:32:54 +00:00
5f0234a358 fix: remove unstable fetch events loop
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-12 11:27:55 +02:00
235e76be4e fix: processing gift wraps and notifications (#193)
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m16s
This change will potentially close multiple issues related to the gift-wrapped events processing (#168, #158). Further testing will be required to confirm before closing each.

The commented-out code causes the race condition during the processing of the gift wraps with sigits.

During the processing we perform checks to see if sigit is outdated. In cases where sigit includes multiple signers it's possible for a signer to receive multiple sigit updates at once (especially noticeable for 3rd, 4th signer). Due to async nature of processing we can have same sigit enter processing flow with different states. Since this code also updates user's app state, which includes uploads to the blossom server it takes time to upload local user state which causes both to check against the stale data and un-updated app state. This results in both sigits being "new" and both proceed to update user state and upload app data. We have no guarantees as in which event will update last, meaning that the final state we end up with could be already stale.

The issue is also complicated due to the fact that we mark the gift wraps as processed and it's impossible to update the state without creating a new gift wrap with correct state and processing it last to overwrite stale state.

This is temporary solution to stop broken sigit states until proper async implementation is ready.

Co-authored-by: b
Reviewed-on: #193
Reviewed-by: eugene <eugene@nostrdev.com>
Co-authored-by: enes <mulahasanovic@outlook.com>
Co-committed-by: enes <mulahasanovic@outlook.com>
2024-09-12 08:26:59 +00:00
e48a396990 fix: verify/sign link
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-11 17:29:47 +02:00
7c80643aba fix(login): extension login infinite loading
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
Fixes #196
2024-09-11 16:44:45 +02:00
9c545a477c fix(errors): add custom timeout error 2024-09-11 16:33:53 +02:00
4d1e672268 feat(loading-spinner): add children support for default variant 2024-09-11 16:33:13 +02:00
79e14d45a1 chore: comment fix
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-11 15:41:42 +02:00
64e8ebba85 chore: renamed sigitKey to sigitCreateId
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-11 13:30:39 +02:00
4bc5882ab6 fix(loading): make sure the default spinner is absolute relative to root always 2024-09-11 13:27:50 +02:00
5dc8d53503 chore: sigitCreateId naming
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-09-11 12:33:40 +02:00
86a16c13ce chore: comments and lint (typing)
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-09-11 12:29:38 +02:00
7c027825cd style: lint fix
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-11 12:03:23 +02:00
8e71592d88 fix: routing, removed useEffect 2024-09-11 11:59:12 +02:00
75a715d002 feat: Add Sigit ID as a path param
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-09-10 16:00:48 +02:00
e2b3dc13fb chore(git): merge pull request #192 from cache-checks-9-9 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m16s
Reviewed-on: #192
Reviewed-by: s <s@noreply.git.nostrdev.com>
2024-09-10 08:48:53 +00:00
b
0244090c6a Merge branch 'staging' into cache-checks-9-9
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 35s
2024-09-09 18:44:36 +00:00
f0ba9da8af fix: outdated cache checks
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-09-09 14:16:58 +02:00
1d1c675dd7 Merge pull request #191 from lint-0-warnings into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m17s
Reviewed-on: #191
Reviewed-by: s
2024-09-09 08:55:28 +00:00
70f646444b fix: add types to rootReducer, rename userRobotImage types
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-09 10:19:37 +02:00
b
09229f42c7 Merge pull request 'new release' (#190) from staging into main
All checks were successful
Release to Production / build_and_release (push) Successful in 1m10s
Reviewed-on: #190
Reviewed-by: enes <enes@noreply.git.nostrdev.com>
Reviewed-by: eugene <eugene@nostrdev.com>
2024-09-06 18:59:34 +00:00
b
f516fe82d7 Merge branch 'main' into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m18s
2024-09-06 15:37:16 +00:00
bf506705e6 chore(git): merge pull request #182 from 174-add-users-updates into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m20s
Reviewed-on: #182
Reviewed-by: s <sabir@4gl.io>
2024-09-06 10:22:56 +00:00
b8811d730a fix(review): remove inline styles
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 35s
2024-09-05 13:24:34 +02:00
479cca2180 chore(git): merge pull request #183 from 172-sign-marks-scroll into 174-add-users-updates
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-05 09:09:11 +00:00
82b7b9f7ce fix(mark): scroll into marks, add scroll margin and forwardRef
Closes #172
2024-09-05 09:32:01 +02:00
3e075754e5 feat(create): touch support for dnd
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 35s
2024-09-05 09:31:52 +02:00
c6010a5bef refactor(create): add counterpart design update 2024-09-05 09:31:52 +02:00
81f40c345a refactor: use ellipsis instead of 3 dots 2024-09-05 09:31:52 +02:00
734026b2ee fix: bad margin value 2024-09-05 09:31:52 +02:00
5caa7f2282 refactor: update add counterparty design 2024-09-05 09:31:52 +02:00
fa7f0e2fc0 refactor(create): move add counterpart below, select role to toggle, remove duplicate code 2024-09-05 09:31:51 +02:00
7d0d4fcb48 chore(git): merge pull request #179 from 177-sticky-side-columns into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m16s
Reviewed-on: #179
Reviewed-by: b <b@4j.cx>
Reviewed-by: eugene <eugene@nostrdev.com>
2024-09-05 07:30:55 +00:00
9223857e18 refactor(drawing): fix mouse comments, use pointer
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-04 14:44:27 +02:00
2be7f3d51b fix(tabs): add tab icons
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-09-04 14:05:36 +02:00
36281376bc fix(mobile): use dynamic vh and one-by-one horizontal scroll 2024-09-04 13:44:10 +02:00
a3effd878b fix(pdf): use minified version of pdf 2024-09-03 16:46:54 +02:00
b20ffe6e87 refactor(mobile): drawing mouse to pointer events, field colors and actions feedback, touch action 2024-09-03 10:14:43 +02:00
757012399a fix: main css background, avoid overscroll showing white edge 2024-09-02 14:41:25 +02:00
c2d065a8a5 refactor(pdf-dist): optimize workers 2024-09-02 12:59:35 +02:00
d1b9eb55d8 fix(spinner): remove dummy desc and use variants 2024-09-02 12:49:51 +02:00
e5f8b797bb refactor(spinner): use data variant for styles 2024-09-02 11:36:31 +02:00
d627db5ac0 refactor(spinner): new default design 2024-09-02 11:35:39 +02:00
6abdb0ae2b refactor: files styling, move styling reset to app from module 2024-08-30 17:58:40 +02:00
be9bfc28c8 refactor(mobile): tabs navigation, observer active for tabs, tabs layout scrolling 2024-08-30 17:39:32 +02:00
2e9e9b0a06 refactor(mobile): styling for sign actions box 2024-08-30 17:37:57 +02:00
15aaef948d fix(create): block if no signers 2024-08-30 13:27:10 +02:00
bee566424d refactor: split signers and viewers in the users section 2024-08-30 12:55:04 +02:00
f8533b0ffd refactor(content): add small loading spinner to content sections
Closes #141
2024-08-30 12:28:33 +02:00
6f7d4c9dcf fix(mobile): active tab default state and styling 2024-08-30 10:57:51 +02:00
d9be05165f feat(mobile): tabs and scrolling 2024-08-29 17:18:32 +02:00
2367eb1887 chore(browser-warn): add alt attribute to image, part 2 2024-08-29 17:03:16 +02:00
156bc59e1a chore(browser-warn): add alt attribute to image 2024-08-29 17:02:32 +02:00
a48751b9a8 refactor(footer): make footer a portal and use as needed 2024-08-29 16:43:09 +02:00
b3564389f9 refactor(sticky-columns-layout): initial responsiveness and breakpoints 2024-08-29 13:09:56 +02:00
5c8cbc1956 refactor(toolbox): responsiveness and cleanup 2024-08-29 13:09:56 +02:00
791c213e3a chore(git): merge pull request #170 from 137-sign-loading-error into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m14s
Reviewed-on: #170
Reviewed-by: eugene <eugene@nostrdev.com>
2024-08-29 11:02:19 +00:00
e2b12afc72 refactor(review): handle loading state, browser warnings
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-08-29 12:54:51 +02:00
20d1170f7d fix(sign): allow signing without marks, hide loading and show toast for prevSig error
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 36s
2024-08-28 13:25:56 +02:00
a8020e6db2 fix(column-layout): wrap content column to prevent expanding 2024-08-28 13:25:56 +02:00
1c998ab99f refactor(error): refactor MetaParseError 2 2024-08-28 13:25:56 +02:00
fa1811a330 refactor(error): refactor SigitMetaParseError 2024-08-28 13:25:56 +02:00
624afae851 fix(create): throw on mark with no counterpart 2024-08-28 13:25:56 +02:00
3a03e3c7e8 chore: comment typo 2024-08-28 13:25:56 +02:00
5570d72f79 chore(git): merge pr #165 from 146-pdf-scaling into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m21s
Reviewed-on: #165
Reviewed-by: eugene <eugene@nostrdev.com>
2024-08-28 11:23:33 +00:00
59c3fc69a2 fix(pdf): reuse content width function
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-28 11:41:29 +02:00
9dc160e89c Merge pull request 'Signing Order' (#167) from issue-158 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m13s
Reviewed-on: #167
Reviewed-by: enes <enes@noreply.git.nostrdev.com>
2024-08-28 08:41:33 +00:00
a442e71087 fix(pdf): add proper default width value
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-08-27 17:28:18 +02:00
923a47b4d0 fix(drawfield): match label and select
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 36s
2024-08-27 16:10:57 +02:00
4712031615 fix(pdf): scaling on resize, add avatars to counterpart select
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-08-27 15:24:19 +02:00
ec305c417b fix: signing order
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-08-27 16:17:34 +03:00
722aecda39 chore(git): merge pull request #164 from 154-drawfield-escaping into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m17s
Reviewed-on: #164
Reviewed-by: eugene <eugene@nostrdev.com>
2024-08-27 10:29:42 +00:00
8c5be3713d refactor(pdf): remove unused code
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-08-26 14:10:11 +02:00
f4aefbb200 chore(git): merge pull request #163 from 138-other-file-types into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m15s
Reviewed-on: #163
Reviewed-by: s <sabir@4gl.io>
2024-08-26 12:00:32 +00:00
ea09daa669 fix(pdf): dynamic mark scaling
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
Caveat: scaling is not fluid, refresh is required
2024-08-23 21:30:32 +02:00
ecc1707212 fix(pdf): add border to style 2024-08-23 13:49:47 +02:00
ac3186a02e fix(pdf): scaling and font styles consistency
Closes #146
2024-08-23 13:39:49 +02:00
31f36750cd fix(pdf): font style consistency 2024-08-23 11:06:25 +02:00
2f54184625 fix(drawing): clamp DrawField within img
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
Closes #154
2024-08-23 10:09:29 +02:00
acc8c84617 fix(home-page): sigit file type display now correctly shows multiple file types
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 40s
2024-08-22 18:58:30 +02:00
ae08b07d74 feat: add uploaded image file as preview 2024-08-22 18:48:03 +02:00
05a2dba164 fix: show extension box for non-mark files, de-dupe css and code
Closes #138
2024-08-22 18:20:54 +02:00
c9d7d0a6f5 feat(content): show other file types as gray box 2024-08-22 18:19:16 +02:00
86095cba5c fix(files): show other file types in content for create, fix sign and verify error 2024-08-22 18:19:16 +02:00
0b9c9906b7 chore(git): merge pull request #162 from nip44 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m25s
Reviewed-on: #162
Reviewed-by: enes <enes@noreply.git.nostrdev.com>
2024-08-22 13:52:19 +00:00
daniyal
070b02abee chore: quick fix
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 43s
2024-08-22 16:12:58 +05:00
daniyal
49c1714962 fix: use old approach of using sha256 for generating d tag
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 44s
2024-08-22 16:11:20 +05:00
daniyal
73a5d42fcf chore(workflow-audit): omit dev dependencies in npm audit
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 41s
2024-08-22 14:37:23 +05:00
daniyal
18270c5d8a feat: use nip04 for encryption and decryption of userData to store on blossom server
Some checks failed
Open PR on Staging / audit_and_check (pull_request) Failing after 17s
2024-08-22 13:08:30 +05:00
b
20496c7e3e Merge pull request 'Releasing new design' (#161) from staging into main
All checks were successful
Release to Production / build_and_release (push) Successful in 1m9s
Reviewed-on: #161
Reviewed-by: eugene <eugene@nostrdev.com>
2024-08-21 11:38:24 +00:00
eb08760f87 chore(git): merge pull request #160 from fix-collection-21-8 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m20s
Reviewed-on: #160
Reviewed-by: eugene <eugene@nostrdev.com>
2024-08-21 11:15:44 +00:00
15d4d0a752 fix: review suggestion
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-21 13:11:56 +02:00
7b33e37ca5 refactor(toolbox): make Text default
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-21 11:37:07 +02:00
329fd3d27b fix: useSigitProfile dep
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
Remove unecessary dep and disable lint line
2024-08-21 11:30:20 +02:00
58f70db7f6 fix(verify-page): map item keys 2024-08-21 11:26:17 +02:00
8c974768a8 fix: sign buttons styles
Fix issue caused by styles change from 6f88f22933
2024-08-21 11:25:35 +02:00
e7b0bbe23c fix: update user placeholder for create 2024-08-21 11:21:57 +02:00
3c230e6fb4 fix: optional label for download button in filelist 2024-08-21 11:21:26 +02:00
35f6a639e6 Merge pull request 'fix: manage pending relay connection requests' (#159) from reduce-relay-connection-attempts into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m12s
Reviewed-on: #159
2024-08-21 08:06:38 +00:00
daniyal
d7b5ea9b9e fix: use default relayMap if its undefined in redux store
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-21 12:53:19 +05:00
b
c1b1c5a075 Merge branch 'staging' into reduce-relay-connection-attempts
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-21 07:42:43 +00:00
daniyal
4a553c047c chore: addressed PR comments
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-21 12:41:59 +05:00
7bb83695c9 Merge pull request 'fix: displays complete marks from other users' (#156) from issue-155 into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m11s
Reviewed-on: #156
Reviewed-by: enes <enes@noreply.git.nostrdev.com>
2024-08-21 07:32:14 +00:00
b
603b01d400 Merge pull request 'chore: updating licence' (#150) from licence into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m12s
Reviewed-on: #150
2024-08-21 07:30:30 +00:00
b
2d82521641 Merge branch 'staging' into licence
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-21 07:30:21 +00:00
daniyal
42d74c656a fix: in pdf marking if counterpart does not have any of name, displayname, username then show pubkey
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-21 00:43:41 +05:00
daniyal
2c18c51029 chore: quick fix
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-21 00:34:39 +05:00
daniyal
f9fcfb1c9e fix: manage pending relay connection requests
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
Also remove the getMostPopularRelays function and use a hardcoded list of relays
Further, if metadata event is not found from relays cache an empty metadata for that pubkey
2024-08-21 00:16:21 +05:00
07d25ebbd2 fix: add parantheses, invoke unixNow
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m15s
2024-08-20 17:37:32 +02:00
23a7dc4269 Merge branch 'staging' into issue-155
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-20 14:08:18 +00:00
4d4a5b63cf fix: displays complete marks from other users
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-20 17:04:27 +03:00
c3a39157ff fix(verify-page): remove mark border in production, enable dev flag for css classes
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m14s
Hotfix
2024-08-20 15:47:51 +02:00
4d794e1e53 Merge pull request 'feat(create-page): new create page design' (#153) from 148-create-page into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m12s
Reviewed-on: #153
2024-08-20 12:43:20 +00:00
404f4aa3a1 fix(lint): update warning limit
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-20 14:40:12 +02:00
15e01f530f chore(git): merge branch 'staging' into 148-create-page 2024-08-20 14:39:19 +02:00
61f39d17ff fix(lint): add deps, remove any, update warning limit
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s
2024-08-20 14:38:03 +02:00
bec3c92b03 fix: add missing null and reduce warning limit
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-20 14:28:34 +02:00
s
ba7d3fadbd Merge pull request 'feat: implemented relay controller and use that for fetching and publishing events' (#149) from relay-controller into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m12s
Reviewed-on: #149
Reviewed-by: enes <enes@noreply.git.nostrdev.com>
2024-08-20 12:13:23 +00:00
s
0f8a40e9f0 Merge branch 'staging' into relay-controller
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-20 12:12:11 +00:00
3d3b8ba6e1 chore(git): merge branch 'staging' into 148-create-page
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-20 14:05:07 +02:00
b6e739bc14 chore(git): merge pull request 'feat(verify-page): new verify page design' (#151) from 136-verify-page-after-merges into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m12s
Reviewed-on: #151
2024-08-20 11:57:40 +00:00
17c91b5507 chore(git): merge branch 'staging' into 136-verify-page-after-merges
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-20 13:55:07 +02:00
e0d6c03639 fix(relay-controller): sigit relay immutability and relay list
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-20 13:52:24 +02:00
f162baadbb Merge pull request 'Signing Page - New Design' (#152) from sigit-info-signing-page into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 1m12s
Reviewed-on: #152
2024-08-20 11:29:11 +00:00
3a6c5ae8e3 chore: formatting
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-20 14:27:35 +03:00
55bf90e93c chore: linting
Some checks failed
Open PR on Staging / audit_and_check (pull_request) Failing after 32s
2024-08-20 14:21:45 +03:00
b12ce258eb fix(create-page): show other file types in content 2024-08-20 11:46:45 +02:00
6f88f22933 fix: leaky styling and warnings
Closes #147
2024-08-20 11:46:45 +02:00
0d1a7ba171 fix(draw): add resize cursor to resize handle 2024-08-20 11:46:45 +02:00
19f7151db7 refactor(create-page): toolbox update 2024-08-20 11:46:45 +02:00
05b9248375 refactor(create-page): users design update 2024-08-20 11:46:24 +02:00
1caeb48e6c fix(create-page): file list 2024-08-20 11:44:54 +02:00
48f54d8568 refactor(create-page): update designs and add files navigation 2024-08-20 11:44:54 +02:00
29e6c85150 fix(create-page): only show signers in counterpart select 2024-08-20 11:44:54 +02:00
c2199b79bd refactor(create-page): styling 2024-08-20 11:44:54 +02:00
6641cf2ee7 fix: simplify events, more ts and clean up 2024-08-20 11:44:54 +02:00
4cf578b514 chore(lint): reduce max warnings 2024-08-20 11:44:54 +02:00
86c8cc00fd feat(create-page): intial layout and page styling
Additional linting fixes
2024-08-20 11:44:54 +02:00
18637bbbc1 fix: update verify to use file signature check 2024-08-20 11:44:34 +02:00
eca31cea4f feat(pdf-marking): adds file validity check 2024-08-20 11:31:11 +02:00
b6479db266 fix(marks): add file grouping for marks, fix read pdf types
Some checks failed
Open PR on Staging / audit_and_check (pull_request) Failing after 33s
2024-08-20 11:18:30 +02:00
b2c3cf2aca fix(sigit): add to submittedBy avatar badge for verified sigit creation 2024-08-20 11:18:30 +02:00
423b6b6792 fix(verify-page): add mark styling 2024-08-20 11:18:30 +02:00
268a4db3ff revert: "feat(pdf-marking): adds file validity check"
Refs: ed7acd6cb4
2024-08-20 11:18:30 +02:00
7278485b76 fix(verify-page): export (download) files now includes files
The issue was noticed on the windows machine, removing forward slash made it work
2024-08-20 11:18:30 +02:00
78060fa15f fix(marks): assign selectedMarkValue to currentValue and mark.value 2024-08-20 11:18:30 +02:00
f88e2ad680 fix(verify-page): parse and show mark values 2024-08-20 11:18:30 +02:00
2c586f3c13 feat(verify-page): add files view and content images 2024-08-20 11:18:30 +02:00
daniyal
a788309126 chore: update tsdoc for function defination in relay controller
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-20 13:55:31 +05:00
daniyal
c274879adc chore: use spread operator in relay reducer for setting mostPopular relays
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-20 12:53:07 +05:00
daniyal
3ae1a74dcd chore: compare objects before dispatching redux action 2024-08-19 21:29:15 +05:00
daniyal
2f1423a35a chore: added a timeout of 30 seconds to subscription
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 32s
2024-08-19 16:34:42 +05:00
79f37a842f fix: file path
Some checks failed
Open PR on Staging / audit_and_check (pull_request) Failing after 30s
2024-08-19 11:07:19 +03:00
daniyal
12765cf758 chore: remove relay connection status from redux
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-18 22:55:13 +05:00
daniyal
66c7182fa4 chore(refactor): move dvm related function to dvm utils file and relay related to relays utils file
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-18 22:48:48 +05:00
daniyal
03cb6b1732 chore(refactor): move getNostrJoiningBlockNumber function to a separate dvm utils file 2024-08-16 11:42:28 +05:00
b
c40651631f chore: updating licence
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-15 18:30:00 +01:00
daniyal
a775d7b265 feat: implemented relay controller and use that for fetching and publishing events
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 33s
2024-08-15 22:13:39 +05:00
ed7acd6cb4 feat(pdf-marking): adds file validity check 2024-08-15 15:35:37 +03:00
b22f577cc2 fix: marking 2024-08-15 12:25:37 +03:00
2becab9f79 feat(pdf-marking): integrates UserDetails 2024-08-15 12:23:35 +03:00
130 changed files with 9391 additions and 4872 deletions

View File

@ -6,7 +6,7 @@ module.exports = {
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended'
],
ignorePatterns: ['dist', '.eslintrc.cjs', 'licenseChecker.cjs'],
ignorePatterns: ['dist', '.eslintrc.cjs', 'licenseChecker.cjs', "*.min.js"],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {

View File

@ -18,7 +18,7 @@ jobs:
node-version: 18
- name: Audit
run: npm audit
run: npm audit --omit=dev
- name: Install Dependencies
run: npm ci

View File

@ -19,7 +19,7 @@ jobs:
node-version: 18
- name: Audit
run: npm audit
run: npm audit --omit=dev
- name: Install Dependencies
run: npm ci

662
LICENSE
View File

@ -1,9 +1,661 @@
MIT License
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (c) 2024 sig
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Preamble
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View File

@ -8,6 +8,7 @@
</head>
<body>
<div id="root"></div>
<script src="/opentimestamps.min.js"></script>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

2242
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,14 @@
{
"name": "web",
"name": "sigit",
"private": true,
"version": "0.0.0",
"version": "0.0.0-beta",
"type": "module",
"homepage": "https://sigit.io/",
"license": "AGPL-3.0-or-later ",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 25",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"lint:fix": "eslint . --fix --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"lint:staged": "eslint --fix --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"formatter:check": "prettier --check \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
@ -30,6 +31,7 @@
"@mui/material": "5.15.11",
"@noble/hashes": "^1.4.0",
"@nostr-dev-kit/ndk": "2.5.0",
"@pdf-lib/fontkit": "^1.1.1",
"@reduxjs/toolkit": "2.2.1",
"axios": "^1.7.4",
"crypto-hash": "3.0.0",
@ -40,18 +42,22 @@
"jszip": "3.10.1",
"lodash": "4.17.21",
"mui-file-input": "4.0.4",
"nostr-login": "^1.6.6",
"nostr-tools": "2.7.0",
"pdf-lib": "^1.17.1",
"pdfjs-dist": "^4.4.168",
"rdndmb-html5-to-touch": "^8.0.3",
"react": "^18.2.0",
"react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1",
"react-dnd": "^16.0.1",
"react-dnd-multi-backend": "^8.0.3",
"react-dom": "^18.2.0",
"react-dropzone": "^14.2.3",
"react-redux": "9.1.0",
"react-router-dom": "6.22.1",
"react-singleton-hook": "^4.0.1",
"react-toastify": "10.0.4",
"redux": "5.0.1",
"svgo": "^3.3.2",
"tseep": "1.2.1"
},
"devDependencies": {
@ -61,6 +67,7 @@
"@types/pdfjs-dist": "^2.10.378",
"@types/react": "^18.2.56",
"@types/react-dom": "^18.2.19",
"@types/svgo": "^3.0.0",
"@typescript-eslint/eslint-plugin": "^7.0.2",
"@typescript-eslint/parser": "^7.0.2",
"@vitejs/plugin-react": "^4.2.1",
@ -73,6 +80,7 @@
"ts-css-modules-vite-plugin": "1.0.20",
"typescript": "^5.2.2",
"vite": "^5.1.4",
"vite-plugin-node-polyfills": "^0.22.0",
"vite-tsconfig-paths": "4.3.2"
},
"lint-staged": {

View File

@ -1,15 +1,15 @@
{
"names": {
"_": "6bf1024c6336093b632db2da21b65a44c7d82830454fb4d75634ba281e161c90"
},
"relays": {
"6bf1024c6336093b632db2da21b65a44c7d82830454fb4d75634ba281e161c90": [
"wss://brb.io",
"wss://nostr.v0l.io",
"wss://nostr.coinos.io",
"wss://rsslay.nostr.net",
"wss://relay.current.fyi",
"wss://nos.io"
]
}
"names": {
"_": "6bf1024c6336093b632db2da21b65a44c7d82830454fb4d75634ba281e161c90"
},
"relays": {
"6bf1024c6336093b632db2da21b65a44c7d82830454fb4d75634ba281e161c90": [
"wss://brb.io",
"wss://nostr.v0l.io",
"wss://nostr.coinos.io",
"wss://rsslay.nostr.net",
"wss://relay.current.fyi",
"wss://nos.io"
]
}
}

2
public/opentimestamps.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -41,6 +41,7 @@ p {
body {
color: $text-color;
background: $body-background-color;
font-family: $font-familiy;
letter-spacing: $letter-spacing;
font-size: $body-font-size;
@ -69,3 +70,102 @@ a {
input {
font-family: inherit;
}
ul {
list-style-type: none; /* Removes bullet points */
margin: 0; /* Removes default margin */
padding: 0; /* Removes default padding */
}
li {
list-style-type: none; /* Removes the bullets */
margin: 0; /* Removes any default margin */
padding: 0; /* Removes any default padding */
}
// Shared styles for center content (Create, Sign, Verify)
.files-wrapper {
display: flex;
flex-direction: column;
gap: 25px;
}
.file-wrapper {
display: flex;
flex-direction: column;
gap: 15px;
position: relative;
// CSS, scroll position when scrolling to the files is adjusted by
// - first-child Header height, default body padding, and center content border (10px) and padding (10px)
// - others We don't include border and padding and scroll to the top of the image
&:first-child {
scroll-margin-top: $body-vertical-padding + 20px;
}
&:not(:first-child) {
scroll-margin-top: $body-vertical-padding;
}
}
// For pdf marks
.image-wrapper {
position: relative;
-webkit-user-select: none;
user-select: none;
> img {
display: block;
width: 100%;
height: auto;
object-fit: contain; /* Ensure the image fits within the container */
}
}
// For image rendering (uploaded image as a file)
.file-image {
-webkit-user-select: none;
user-select: none;
display: block;
width: 100%;
height: auto;
object-fit: contain; /* Ensure the image fits within the container */
}
// Consistent styling for every file mark
// Reverts some of the design defaults for font
.file-mark {
font-family: 'Roboto';
font-style: normal;
font-weight: normal;
letter-spacing: normal;
line-height: 1;
font-size: 16px;
color: black;
outline: 1px solid transparent;
justify-content: start;
align-items: start;
scroll-margin-top: $body-vertical-padding;
}
[data-dev='true'] {
.image-wrapper {
// outline: 1px solid #ccc; /* Optional: for visual debugging */
background-color: #e0f7fa; /* Optional: for visual debugging */
}
}
.extension-file-box {
border-radius: 4px;
background: rgba(255, 255, 255, 0.5);
height: 100px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: rgba(0, 0, 0, 0.25);
font-size: 14px;
}

View File

@ -1,7 +1,7 @@
import { useEffect } from 'react'
import { useSelector } from 'react-redux'
import { useAppSelector } from './hooks/store'
import { Navigate, Route, Routes } from 'react-router-dom'
import { AuthController, NostrController } from './controllers'
import { AuthController } from './controllers'
import { MainLayout } from './layouts/Main'
import {
appPrivateRoutes,
@ -10,12 +10,10 @@ import {
publicRoutes,
recursiveRouteRenderer
} from './routes'
import { State } from './store/rootReducer'
import { getNsecBunkerDelegatedKey, saveNsecBunkerDelegatedKey } from './utils'
import './App.scss'
const App = () => {
const authState = useSelector((state: State) => state.auth)
const authState = useAppSelector((state) => state.auth)
useEffect(() => {
if (window.location.hostname === '0.0.0.0') {
@ -25,23 +23,10 @@ const App = () => {
window.location.hostname = 'localhost'
}
generateBunkerDelegatedKey()
const authController = new AuthController()
authController.checkSession()
}, [])
const generateBunkerDelegatedKey = () => {
const existingKey = getNsecBunkerDelegatedKey()
if (!existingKey) {
const nostrController = NostrController.getInstance()
const newDelegatedKey = nostrController.generateDelegatedKey()
saveNsecBunkerDelegatedKey(newDelegatedKey)
}
}
const handleRootRedirect = () => {
if (authState.loggedIn) return appPrivateRoutes.homePage
const callbackPathEncoded = btoa(

Binary file not shown.

View File

@ -9,55 +9,42 @@ import {
} from '@mui/material'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import {
setAuthState,
setMetadataEvent,
userLogOutAction
} from '../../store/actions'
import { State } from '../../store/rootReducer'
import { Dispatch } from '../../store/store'
import { useAppSelector } from '../../hooks/store'
import Username from '../username'
import { Link, useNavigate } from 'react-router-dom'
import { MetadataController, NostrController } from '../../controllers'
import {
appPublicRoutes,
appPrivateRoutes,
getProfileRoute
} from '../../routes'
import {
clearAuthToken,
hexToNpub,
saveNsecBunkerDelegatedKey,
shorten
} from '../../utils'
import { getProfileUsername, hexToNpub } from '../../utils'
import styles from './style.module.scss'
import { setUserRobotImage } from '../../store/userRobotImage/action'
import { Container } from '../Container'
import { ButtonIcon } from '../ButtonIcon'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faClose } from '@fortawesome/free-solid-svg-icons'
import useMediaQuery from '@mui/material/useMediaQuery'
import { useLogout } from '../../hooks/useLogout'
const metadataController = new MetadataController()
import { launch as launchNostrLoginDialog } from 'nostr-login'
export const AppBar = () => {
const navigate = useNavigate()
const dispatch: Dispatch = useDispatch()
const logout = useLogout()
const [username, setUsername] = useState('')
const [userAvatar, setUserAvatar] = useState('')
const [anchorElUser, setAnchorElUser] = useState<null | HTMLElement>(null)
const authState = useSelector((state: State) => state.auth)
const metadataState = useSelector((state: State) => state.metadata)
const userRobotImage = useSelector((state: State) => state.userRobotImage)
const authState = useAppSelector((state) => state.auth)
const metadataState = useAppSelector((state) => state.metadata)
const userRobotImage = useAppSelector((state) => state.userRobotImage)
useEffect(() => {
if (metadataState) {
if (metadataState.content) {
const { picture, display_name, name } = JSON.parse(
metadataState.content
)
const profileMetadata = JSON.parse(metadataState.content)
const { picture } = profileMetadata
if (picture || userRobotImage) {
setUserAvatar(picture || userRobotImage)
@ -67,7 +54,7 @@ export const AppBar = () => {
? hexToNpub(authState.usersPubkey)
: ''
setUsername(shorten(display_name || name || npub, 7))
setUsername(getProfileUsername(npub, profileMetadata))
} else {
setUserAvatar(userRobotImage || '')
setUsername('')
@ -92,151 +79,157 @@ export const AppBar = () => {
const handleLogout = () => {
handleCloseUserMenu()
dispatch(
setAuthState({
keyPair: undefined,
loggedIn: false,
usersPubkey: undefined,
loginMethod: undefined,
nsecBunkerPubkey: undefined
})
)
dispatch(setMetadataEvent(metadataController.getEmptyMetadataEvent()))
dispatch(setUserRobotImage(null))
// clear authToken saved in local storage
clearAuthToken()
dispatch(userLogOutAction())
// update nsecBunker delegated key after logout
const nostrController = NostrController.getInstance()
const newDelegatedKey = nostrController.generateDelegatedKey()
saveNsecBunkerDelegatedKey(newDelegatedKey)
logout()
navigate('/')
}
const isAuthenticated = authState?.loggedIn === true
const matches = useMediaQuery('(max-width:767px)')
const [isBannerVisible, setIsBannerVisible] = useState(true)
const handleBannerHide = () => {
setIsBannerVisible(false)
}
return (
<AppBarMui
position="fixed"
className={styles.AppBar}
sx={{
boxShadow: 'none'
}}
>
<Container>
<Toolbar className={styles.toolbar} disableGutters={true}>
<Box className={styles.logoWrapper}>
<img src="/logo.svg" alt="Logo" onClick={() => navigate('/')} />
</Box>
<Box className={styles.rightSideBox}>
{!isAuthenticated && (
<>
{isAuthenticated && isBannerVisible && (
<div className={styles.banner}>
<Container>
<div className={styles.bannerInner}>
<p className={styles.bannerText}>
SIGit is currently Beta software (available for user experience
testing), use at your own risk!
</p>
<Button
startIcon={<ButtonIcon />}
onClick={() => {
navigate(appPublicRoutes.nostr)
}}
variant="contained"
aria-label={`close banner`}
variant="text"
onClick={handleBannerHide}
>
LOGIN
<FontAwesomeIcon icon={faClose} />
</Button>
)}
</div>
</Container>
</div>
)}
<AppBarMui
position={matches ? 'sticky' : 'static'}
className={styles.AppBar}
sx={{
boxShadow: 'none'
}}
>
<Container>
<Toolbar className={styles.toolbar} disableGutters={true}>
<Box className={styles.logoWrapper}>
<img src="/logo.svg" alt="Logo" onClick={() => navigate('/')} />
</Box>
{isAuthenticated && (
<>
<Username
username={username}
avatarContent={userAvatar}
handleClick={handleOpenUserMenu}
/>
<Menu
id="menu-appbar"
anchorEl={anchorElUser}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center'
<Box className={styles.rightSideBox}>
{!isAuthenticated && (
<Button
startIcon={<ButtonIcon />}
onClick={() => {
launchNostrLoginDialog()
}}
keepMounted
transformOrigin={{
vertical: 'top',
horizontal: 'center'
}}
open={!!anchorElUser}
onClose={handleCloseUserMenu}
variant="contained"
>
<MenuItem
sx={{
justifyContent: 'center',
display: { md: 'none' },
fontWeight: 500,
fontSize: '14px',
color: 'var(--text-color)'
}}
>
<Typography variant="h6">{username}</Typography>
</MenuItem>
<MenuItem
onClick={handleProfile}
sx={{
justifyContent: 'center'
}}
>
Profile
</MenuItem>
<MenuItem
onClick={() => {
setAnchorElUser(null)
LOGIN
</Button>
)}
navigate(appPrivateRoutes.settings)
{isAuthenticated && (
<>
<Username
username={username}
avatarContent={userAvatar}
handleClick={handleOpenUserMenu}
/>
<Menu
id="menu-appbar"
anchorEl={anchorElUser}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center'
}}
sx={{
justifyContent: 'center'
keepMounted
transformOrigin={{
vertical: 'top',
horizontal: 'center'
}}
>
Settings
</MenuItem>
<MenuItem
onClick={() => {
setAnchorElUser(null)
navigate(appPublicRoutes.verify)
}}
sx={{
justifyContent: 'center'
}}
>
Verify
</MenuItem>
<Link
to={appPublicRoutes.source}
target="_blank"
style={{ color: 'inherit', textDecoration: 'inherit' }}
open={!!anchorElUser}
onClose={handleCloseUserMenu}
>
<MenuItem
sx={{
justifyContent: 'center',
display: { md: 'none' },
fontWeight: 500,
fontSize: '14px',
color: 'var(--text-color)'
}}
>
<Typography variant="h6">{username}</Typography>
</MenuItem>
<MenuItem
onClick={handleProfile}
sx={{
justifyContent: 'center'
}}
>
Source
Profile
</MenuItem>
</Link>
<MenuItem
onClick={handleLogout}
sx={{
justifyContent: 'center'
}}
>
Logout
</MenuItem>
</Menu>
</>
)}
</Box>
</Toolbar>
</Container>
</AppBarMui>
<MenuItem
onClick={() => {
setAnchorElUser(null)
navigate(appPrivateRoutes.settings)
}}
sx={{
justifyContent: 'center'
}}
>
Settings
</MenuItem>
<MenuItem
onClick={() => {
setAnchorElUser(null)
navigate(appPublicRoutes.verify)
}}
sx={{
justifyContent: 'center'
}}
>
Verify
</MenuItem>
<Link
to={appPublicRoutes.source}
target="_blank"
style={{ color: 'inherit', textDecoration: 'inherit' }}
>
<MenuItem
sx={{
justifyContent: 'center'
}}
>
Source
</MenuItem>
</Link>
<MenuItem
onClick={handleLogout}
sx={{
justifyContent: 'center'
}}
>
Logout
</MenuItem>
</Menu>
</>
)}
</Box>
</Toolbar>
</Container>
</AppBarMui>
</>
)
}

View File

@ -34,3 +34,42 @@
justify-content: flex-end;
}
}
.banner {
color: #ffffff;
background-color: $primary-main;
}
.bannerInner {
display: flex;
gap: 10px;
padding-block: 10px;
z-index: 1;
width: 100%;
justify-content: space-between;
flex-direction: row;
button {
min-width: 44px;
color: inherit;
}
&:hover,
&.active,
&:focus-within {
background: $primary-main;
color: inherit;
button {
color: inherit;
}
}
}
.bannerText {
margin-left: 54px;
flex-grow: 1;
text-align: center;
}

View File

@ -1,7 +1,7 @@
import { Meta } from '../../types'
import { SigitCardDisplayInfo, SigitStatus } from '../../utils'
import { SigitCardDisplayInfo, SigitStatus, SignStatus } from '../../utils'
import { Link } from 'react-router-dom'
import { formatTimestamp, hexToNpub, npubToHex, shorten } from '../../utils'
import { formatTimestamp, npubToHex } from '../../utils'
import { appPublicRoutes, appPrivateRoutes } from '../../routes'
import { Button, Divider, Tooltip } from '@mui/material'
import { DisplaySigner } from '../DisplaySigner'
@ -10,104 +10,74 @@ import {
faCalendar,
faCopy,
faEye,
faFile
faFile,
faFileCircleExclamation
} from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { UserAvatar } from '../UserAvatar'
import { UserAvatarGroup } from '../UserAvatarGroup'
import styles from './style.module.scss'
import { TooltipChild } from '../TooltipChild'
import { getExtensionIconLabel } from '../getExtensionIconLabel'
import { useSigitProfiles } from '../../hooks/useSigitProfiles'
import { useSigitMeta } from '../../hooks/useSigitMeta'
import { extractFileExtensions } from '../../utils/file'
type SigitProps = {
sigitCreateId: string
meta: Meta
parsedMeta: SigitCardDisplayInfo
}
export const DisplaySigit = ({ meta, parsedMeta }: SigitProps) => {
const {
title,
createdAt,
submittedBy,
signers,
signedStatus,
fileExtensions
} = parsedMeta
export const DisplaySigit = ({
meta,
parsedMeta,
sigitCreateId: sigitCreateId
}: SigitProps) => {
const { title, createdAt, submittedBy, signers, signedStatus, isValid } =
parsedMeta
const { signersStatus } = useSigitMeta(meta)
const profiles = useSigitProfiles([
...(submittedBy ? [submittedBy] : []),
...signers
])
const { signersStatus, fileHashes } = useSigitMeta(meta)
const { extensions, isSame } = extractFileExtensions(Object.keys(fileHashes))
return (
<div className={styles.itemWrapper}>
<Link
to={
signedStatus === SigitStatus.Complete
? appPublicRoutes.verify
: appPrivateRoutes.sign
}
state={{ meta }}
className={styles.insetLink}
></Link>
{signedStatus === SigitStatus.Complete && (
<Link
to={appPublicRoutes.verify}
state={{ meta }}
className={styles.insetLink}
></Link>
)}
{signedStatus !== SigitStatus.Complete && (
<Link
to={`${appPrivateRoutes.sign}/${sigitCreateId}`}
className={styles.insetLink}
></Link>
)}
<p className={`line-clamp-2 ${styles.title}`}>{title}</p>
<div className={styles.users}>
{submittedBy &&
(function () {
const profile = profiles[submittedBy]
return (
<Tooltip
title={
profile?.display_name ||
profile?.name ||
shorten(hexToNpub(submittedBy))
}
placement="top"
arrow
disableInteractive
>
<TooltipChild>
<UserAvatar pubkey={submittedBy} image={profile?.picture} />
</TooltipChild>
</Tooltip>
)
})()}
{submittedBy && (
<DisplaySigner
status={isValid ? SignStatus.Signed : SignStatus.Invalid}
pubkey={submittedBy}
/>
)}
{submittedBy && signers.length ? (
<Divider orientation="vertical" flexItem />
) : null}
<UserAvatarGroup max={7}>
{signers.map((signer) => {
const pubkey = npubToHex(signer)!
const profile = profiles[pubkey]
return (
<Tooltip
key={signer}
title={
profile?.display_name || profile?.name || shorten(pubkey)
}
placement="top"
arrow
disableInteractive
>
<TooltipChild>
<DisplaySigner
status={signersStatus[signer]}
profile={profile}
pubkey={pubkey}
/>
</TooltipChild>
</Tooltip>
<DisplaySigner
key={pubkey}
status={signersStatus[signer]}
pubkey={pubkey}
/>
)
})}
</UserAvatarGroup>
</div>
<div className={`${styles.details} ${styles.date} ${styles.iconLabel}`}>
<div className={`${styles.details} ${styles.iconLabel}`}>
<FontAwesomeIcon icon={faCalendar} />
{createdAt ? formatTimestamp(createdAt) : null}
</div>
@ -115,17 +85,21 @@ export const DisplaySigit = ({ meta, parsedMeta }: SigitProps) => {
<span className={styles.iconLabel}>
<FontAwesomeIcon icon={faEye} /> {signedStatus}
</span>
{fileExtensions.length > 0 ? (
{extensions.length > 0 ? (
<span className={styles.iconLabel}>
{fileExtensions.length > 1 ? (
{!isSame ? (
<>
<FontAwesomeIcon icon={faFile} /> Multiple File Types
</>
) : (
getExtensionIconLabel(fileExtensions[0])
getExtensionIconLabel(extensions[0])
)}
</span>
) : null}
) : (
<>
<FontAwesomeIcon icon={faFileCircleExclamation} /> &mdash;
</>
)}
</div>
<div className={styles.itemActions}>
<Tooltip title="Duplicate" arrow placement="top" disableInteractive>

View File

@ -1,5 +1,4 @@
import { Badge } from '@mui/material'
import { ProfileMetadata } from '../../types'
import styles from './style.module.scss'
import { UserAvatar } from '../UserAvatar'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
@ -15,38 +14,33 @@ import { SignStatus } from '../../utils'
import { Spinner } from '../Spinner'
type DisplaySignerProps = {
profile: ProfileMetadata
pubkey: string
status: SignStatus
}
export const DisplaySigner = ({
status,
profile,
pubkey
}: DisplaySignerProps) => {
const getStatusIcon = (status: SignStatus) => {
switch (status) {
case SignStatus.Signed:
return <FontAwesomeIcon icon={faCheck} />
case SignStatus.Awaiting:
return (
<Spinner>
<FontAwesomeIcon icon={faHourglass} />
</Spinner>
)
case SignStatus.Pending:
return <FontAwesomeIcon icon={faEllipsis} />
case SignStatus.Invalid:
return <FontAwesomeIcon icon={faExclamation} />
case SignStatus.Viewer:
return <FontAwesomeIcon icon={faEye} />
const getStatusIcon = (status: SignStatus) => {
switch (status) {
case SignStatus.Signed:
return <FontAwesomeIcon icon={faCheck} />
case SignStatus.Awaiting:
return (
<Spinner>
<FontAwesomeIcon icon={faHourglass} />
</Spinner>
)
case SignStatus.Pending:
return <FontAwesomeIcon icon={faEllipsis} />
case SignStatus.Invalid:
return <FontAwesomeIcon icon={faExclamation} />
case SignStatus.Viewer:
return <FontAwesomeIcon icon={faEye} />
default:
return <FontAwesomeIcon icon={faQuestion} />
}
default:
return <FontAwesomeIcon icon={faQuestion} />
}
}
export const DisplaySigner = ({ status, pubkey }: DisplaySignerProps) => {
return (
<Badge
className={styles.signer}
@ -56,7 +50,7 @@ export const DisplaySigner = ({
<div className={styles.statusBadge}>{getStatusIcon(status)}</div>
}
>
<UserAvatar pubkey={pubkey} image={profile?.picture} />
<UserAvatar pubkey={pubkey} />
</Badge>
)
}

View File

@ -1,161 +1,141 @@
import { Close } from '@mui/icons-material'
import {
AccessTime,
CalendarMonth,
ExpandMore,
Gesture,
PictureAsPdf,
Badge,
Work,
Close
} from '@mui/icons-material'
import {
Box,
Typography,
Accordion,
AccordionDetails,
AccordionSummary,
CircularProgress,
FormControl,
InputLabel,
ListItemIcon,
ListItemText,
MenuItem,
Select
} from '@mui/material'
import styles from './style.module.scss'
import { useEffect, useState } from 'react'
import React, { useEffect, useState } from 'react'
import { ProfileMetadata, User, UserRole, KeyboardCode } from '../../types'
import { MouseState, PdfPage, DrawnField, DrawTool } from '../../types/drawing'
import { hexToNpub, npubToHex, getProfileUsername } from '../../utils'
import { SigitFile } from '../../utils/file'
import { getToolboxLabelByMarkType } from '../../utils/mark'
import { FileDivider } from '../FileDivider'
import { ExtensionFileBox } from '../ExtensionFileBox'
import { FONT_SIZE, FONT_TYPE, inPx } from '../../utils/pdf'
import { useScale } from '../../hooks/useScale'
import { AvatarIconButton } from '../UserAvatarIconButton'
import { UserAvatar } from '../UserAvatar'
import _ from 'lodash'
import * as PDFJS from 'pdfjs-dist'
import { ProfileMetadata, User } from '../../types'
import {
PdfFile,
DrawTool,
MouseState,
PdfPage,
DrawnField,
MarkType
} from '../../types/drawing'
import { truncate } from 'lodash'
import { hexToNpub } from '../../utils'
import { toPdfFiles } from '../../utils/pdf.ts'
PDFJS.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url
).toString()
const DEFAULT_START_SIZE = {
width: 140,
height: 40
} as const
interface HideSignersForDrawnField {
[key: number]: boolean
}
interface Props {
selectedFiles: File[]
users: User[]
metadata: { [key: string]: ProfileMetadata }
onDrawFieldsChange: (pdfFiles: PdfFile[]) => void
sigitFiles: SigitFile[]
setSigitFiles: React.Dispatch<React.SetStateAction<SigitFile[]>>
selectedTool?: DrawTool
}
export const DrawPDFFields = (props: Props) => {
const { selectedFiles } = props
const { selectedTool, sigitFiles, setSigitFiles, users } = props
const [pdfFiles, setPdfFiles] = useState<PdfFile[]>([])
const [parsingPdf, setParsingPdf] = useState<boolean>(false)
const [showDrawToolBox, setShowDrawToolBox] = useState<boolean>(false)
const signers = users.filter((u) => u.role === UserRole.signer)
const defaultSignerNpub = signers.length ? hexToNpub(signers[0].pubkey) : ''
const [lastSigner, setLastSigner] = useState(defaultSignerNpub)
const [hideSignersForDrawnField, setHideSignersForDrawnField] =
useState<HideSignersForDrawnField>({})
const [selectedTool, setSelectedTool] = useState<DrawTool | null>()
const [toolbox] = useState<DrawTool[]>([
{
identifier: MarkType.SIGNATURE,
icon: <Gesture />,
label: 'Signature',
active: false
},
{
identifier: MarkType.FULLNAME,
icon: <Badge />,
label: 'Full Name',
active: true
},
{
identifier: MarkType.JOBTITLE,
icon: <Work />,
label: 'Job Title',
active: false
},
{
identifier: MarkType.DATE,
icon: <CalendarMonth />,
label: 'Date',
active: false
},
{
identifier: MarkType.DATETIME,
icon: <AccessTime />,
label: 'Datetime',
active: false
}
])
/**
* Return first pubkey that is present in the signers list
* @param pubkeys
* @returns available pubkey or empty string
*/
const getAvailableSigner = (...pubkeys: string[]) => {
const availableSigner: string | undefined = pubkeys.find((pubkey) =>
signers.some((s) => s.pubkey === npubToHex(pubkey))
)
return availableSigner || ''
}
const { to, from } = useScale()
const [mouseState, setMouseState] = useState<MouseState>({
clicked: false
})
useEffect(() => {
if (selectedFiles) {
setParsingPdf(true)
parsePdfPages().finally(() => {
setParsingPdf(false)
})
}
}, [selectedFiles])
useEffect(() => {
if (pdfFiles) props.onDrawFieldsChange(pdfFiles)
}, [pdfFiles])
const [activeDrawnField, setActiveDrawnField] = useState<{
fileIndex: number
pageIndex: number
drawnFieldIndex: number
}>()
const isActiveDrawnField = (
fileIndex: number,
pageIndex: number,
drawnFieldIndex: number
) =>
activeDrawnField?.fileIndex === fileIndex &&
activeDrawnField?.pageIndex === pageIndex &&
activeDrawnField?.drawnFieldIndex === drawnFieldIndex
/**
* Drawing events
*/
useEffect(() => {
// window.addEventListener('mousedown', onMouseDown);
window.addEventListener('mouseup', onMouseUp)
window.addEventListener('pointerup', handlePointerUp)
window.addEventListener('pointercancel', handlePointerUp)
return () => {
// window.removeEventListener('mousedown', onMouseDown);
window.removeEventListener('mouseup', onMouseUp)
window.removeEventListener('pointerup', handlePointerUp)
window.removeEventListener('pointercancel', handlePointerUp)
}
}, [])
const refreshPdfFiles = () => {
setPdfFiles([...pdfFiles])
setSigitFiles([...sigitFiles])
}
/**
* Fired only when left click and mouse over pdf page
* Fired only on when left (primary pointer interaction) clicking page image
* Creates new drawnElement and pushes in the array
* It is re rendered and visible right away
*
* @param event Mouse event
* @param event Pointer event
* @param page PdfPage where press happened
*/
const onMouseDown = (event: any, page: PdfPage) => {
const handlePointerDown = (
event: React.PointerEvent,
page: PdfPage,
fileIndex: number,
pageIndex: number
) => {
// Proceed only if left click
if (event.button !== 0) return
// Only allow drawing if mouse is not over other drawn element
const isOverPdfImageWrapper = event.target.tagName === 'IMG'
if (!selectedTool || !isOverPdfImageWrapper) {
if (!selectedTool) {
return
}
const { mouseX, mouseY } = getMouseCoordinates(event)
const { x, y } = getPointerCoordinates(event)
const newField: DrawnField = {
left: mouseX,
top: mouseY,
width: 0,
height: 0,
counterpart: '',
left: to(page.width, x),
top: to(page.width, y),
width: event.pointerType === 'mouse' ? 0 : DEFAULT_START_SIZE.width,
height: event.pointerType === 'mouse' ? 0 : DEFAULT_START_SIZE.height,
counterpart: getAvailableSigner(lastSigner, defaultSignerNpub),
type: selectedTool.identifier
}
page.drawnFields.push(newField)
setActiveDrawnField({
fileIndex,
pageIndex,
drawnFieldIndex: page.drawnFields.length - 1
})
setMouseState((prev) => {
return {
...prev,
@ -166,9 +146,9 @@ export const DrawPDFFields = (props: Props) => {
/**
* Drawing is finished, resets all the variables used to draw
* @param event Mouse event
* @param event Pointer event
*/
const onMouseUp = () => {
const handlePointerUp = () => {
setMouseState((prev) => {
return {
...prev,
@ -180,20 +160,26 @@ export const DrawPDFFields = (props: Props) => {
}
/**
* After {@link onMouseDown} create an drawing element, this function gets called on every pixel moved
* which alters the newly created drawing element, resizing it while mouse move
* @param event Mouse event
* After {@link handlePointerDown} create an drawing element, this function gets called on every pixel moved
* which alters the newly created drawing element, resizing it while pointer moves
* @param event Pointer event
* @param page PdfPage where moving is happening
*/
const onMouseMove = (event: any, page: PdfPage) => {
if (mouseState.clicked && selectedTool) {
const handlePointerMove = (event: React.PointerEvent, page: PdfPage) => {
if (mouseState.clicked && selectedTool && event.pointerType === 'mouse') {
const lastElementIndex = page.drawnFields.length - 1
const lastDrawnField = page.drawnFields[lastElementIndex]
const { mouseX, mouseY } = getMouseCoordinates(event)
// Return early if we don't have lastDrawnField
// Issue noticed in the console when dragging out of bounds
// to the page below (without releaseing mouse click)
if (!lastDrawnField) return
const width = mouseX - lastDrawnField.left
const height = mouseY - lastDrawnField.top
const { x, y } = getPointerCoordinates(event)
const width = to(page.width, x) - lastDrawnField.left
const height = to(page.width, y) - lastDrawnField.top
lastDrawnField.width = width
lastDrawnField.height = height
@ -208,51 +194,68 @@ export const DrawPDFFields = (props: Props) => {
/**
* Fired when event happens on the drawn element which will be moved
* mouse coordinates relative to drawn element will be stored
* pointer coordinates relative to drawn element will be stored
* so when we start moving, offset can be calculated
* mouseX - offsetX
* mouseY - offsetY
* x - offsetX
* y - offsetY
*
* @param event Mouse event
* @param drawnField Which we are moving
* @param event Pointer event
* @param drawnFieldIndex Which we are moving
*/
const onDrawnFieldMouseDown = (event: any) => {
const handleDrawnFieldPointerDown = (
event: React.PointerEvent,
fileIndex: number,
pageIndex: number,
drawnFieldIndex: number
) => {
event.stopPropagation()
// Proceed only if left click
if (event.button !== 0) return
const drawingRectangleCoords = getMouseCoordinates(event)
const drawingRectangleCoords = getPointerCoordinates(event)
setActiveDrawnField({ fileIndex, pageIndex, drawnFieldIndex })
setMouseState({
dragging: true,
clicked: false,
coordsInWrapper: {
mouseX: drawingRectangleCoords.mouseX,
mouseY: drawingRectangleCoords.mouseY
x: drawingRectangleCoords.x,
y: drawingRectangleCoords.y
}
})
// make signers dropdown visible
setHideSignersForDrawnField((prev) => ({
...prev,
[drawnFieldIndex]: false
}))
}
/**
* Moves the drawnElement by the mouse position (mouse can grab anywhere on the drawn element)
* @param event Mouse event
* Moves the drawnElement by the pointer position (pointer can grab anywhere on the drawn element)
* @param event Pointer event
* @param drawnField which we are moving
* @param pageWidth pdf value which is used to calculate scaled offset
*/
const onDranwFieldMouseMove = (event: any, drawnField: DrawnField) => {
const handleDrawnFieldPointerMove = (
event: React.PointerEvent,
drawnField: DrawnField,
pageWidth: number
) => {
if (mouseState.dragging) {
const { mouseX, mouseY, rect } = getMouseCoordinates(
const { x, y, rect } = getPointerCoordinates(
event,
event.target.parentNode
event.currentTarget.parentElement
)
const coordsOffset = mouseState.coordsInWrapper
if (coordsOffset) {
let left = mouseX - coordsOffset.mouseX
let top = mouseY - coordsOffset.mouseY
let left = to(pageWidth, x - coordsOffset.x)
let top = to(pageWidth, y - coordsOffset.y)
const rightLimit = rect.width - drawnField.width - 3
const bottomLimit = rect.height - drawnField.height - 3
const rightLimit = to(pageWidth, rect.width) - drawnField.width
const bottomLimit = to(pageWidth, rect.height) - drawnField.height
if (left < 0) left = 0
if (top < 0) top = 0
@ -269,15 +272,20 @@ export const DrawPDFFields = (props: Props) => {
/**
* Fired when clicked on the resize handle, sets the state for a resize action
* @param event Mouse event
* @param drawnField which we are resizing
* @param event Pointer event
* @param drawnFieldIndex which we are resizing
*/
const onResizeHandleMouseDown = (event: any) => {
const handleResizePointerDown = (
event: React.PointerEvent,
fileIndex: number,
pageIndex: number,
drawnFieldIndex: number
) => {
// Proceed only if left click
if (event.button !== 0) return
event.stopPropagation()
setActiveDrawnField({ fileIndex, pageIndex, drawnFieldIndex })
setMouseState({
resizing: true
})
@ -285,18 +293,26 @@ export const DrawPDFFields = (props: Props) => {
/**
* Resizes the drawn element by the mouse position
* @param event Mouse event
* @param event Pointer event
* @param drawnField which we are resizing
* @param pageWidth pdf value which is used to calculate scaled offset
*/
const onResizeHandleMouseMove = (event: any, drawnField: DrawnField) => {
const handleResizePointerMove = (
event: React.PointerEvent,
drawnField: DrawnField,
pageWidth: number
) => {
if (mouseState.resizing) {
const { mouseX, mouseY } = getMouseCoordinates(
const { x, y } = getPointerCoordinates(
event,
event.target.parentNode.parentNode
// currentTarget = span handle
// 1st parent = drawnField
// 2nd parent = img
event.currentTarget.parentElement?.parentElement
)
const width = mouseX - drawnField.left
const height = mouseY - drawnField.top
const width = to(pageWidth, x) - drawnField.left
const height = to(pageWidth, y) - drawnField.top
drawnField.width = width
drawnField.height = height
@ -307,154 +323,194 @@ export const DrawPDFFields = (props: Props) => {
/**
* Removes the drawn element using the indexes in the params
* @param event Mouse event
* @param event Pointer event
* @param pdfFileIndex pdf file index
* @param pdfPageIndex pdf page index
* @param drawnFileIndex drawn file index
*/
const onRemoveHandleMouseDown = (
event: any,
const handleRemovePointerDown = (
event: React.PointerEvent,
pdfFileIndex: number,
pdfPageIndex: number,
drawnFileIndex: number
) => {
event.stopPropagation()
pdfFiles[pdfFileIndex].pages[pdfPageIndex].drawnFields.splice(
drawnFileIndex,
1
)
const pages = sigitFiles[pdfFileIndex]?.pages
if (pages) {
pages[pdfPageIndex]?.drawnFields?.splice(drawnFileIndex, 1)
}
}
/**
* Used to stop mouse click propagating to the parent elements
* Used to stop pointer click propagating to the parent elements
* so select can work properly
* @param event Mouse event
* @param event Pointer event
*/
const onUserSelectHandleMouseDown = (event: any) => {
const handleUserSelectPointerDown = (event: React.PointerEvent) => {
event.stopPropagation()
}
/**
* Gets the mouse coordinates relative to a element in the `event` param
* @param event MouseEvent
* @param customTarget mouse coordinates relative to this element, if not provided
* Handles Escape button-down event and hides all signers dropdowns
* @param event SyntheticEvent event
*/
const handleEscapeButtonDown = (event: React.SyntheticEvent) => {
// get native event
const { nativeEvent } = event
//check if event is a keyboard event
if (nativeEvent instanceof KeyboardEvent) {
// check if event code is Escape
if (nativeEvent.code === KeyboardCode.Escape) {
// hide all signers dropdowns
const newHideSignersForDrawnField: HideSignersForDrawnField = {}
Object.keys(hideSignersForDrawnField).forEach((key) => {
// Object.keys always returns an array of strings,
// that is why unknown type is used below
newHideSignersForDrawnField[key as unknown as number] = true
})
setHideSignersForDrawnField(newHideSignersForDrawnField)
}
}
}
/**
* Gets the pointer coordinates relative to a element in the `event` param
* @param event PointerEvent
* @param customTarget coordinates relative to this element, if not provided
* event.target will be used
*/
const getMouseCoordinates = (event: any, customTarget?: any) => {
const target = customTarget ? customTarget : event.target
const getPointerCoordinates = (
event: React.PointerEvent,
customTarget?: HTMLElement | null
) => {
const target = customTarget ? customTarget : event.currentTarget
const rect = target.getBoundingClientRect()
const mouseX = event.clientX - rect.left //x position within the element.
const mouseY = event.clientY - rect.top //y position within the element.
// Clamp X Y within the target
const x = Math.min(event.clientX, rect.right) - rect.left //x position within the element.
const y = Math.min(event.clientY, rect.bottom) - rect.top //y position within the element.
return {
mouseX,
mouseY,
x,
y,
rect
}
}
/**
* Reads the pdf binary files and converts it's pages to images
* creates the pdfFiles object and sets to a state
*/
const parsePdfPages = async () => {
const pdfFiles: PdfFile[] = await toPdfFiles(selectedFiles)
setPdfFiles(pdfFiles)
}
/**
*
* @returns if expanded pdf accordion is present
*/
const hasExpandedPdf = () => {
return !!pdfFiles.filter((pdfFile) => !!pdfFile.expanded).length
}
const handleAccordionExpandChange = (expanded: boolean, pdfFile: PdfFile) => {
pdfFile.expanded = expanded
refreshPdfFiles()
setShowDrawToolBox(hasExpandedPdf())
}
/**
* Changes the drawing tool
* @param drawTool to draw with
*/
const handleToolSelect = (drawTool: DrawTool) => {
// If clicked on the same tool, unselect
if (drawTool.identifier === selectedTool?.identifier) {
setSelectedTool(null)
return
}
setSelectedTool(drawTool)
}
/**
* Renders the pdf pages and drawing elements
*/
const getPdfPages = (pdfFile: PdfFile, pdfFileIndex: number) => {
const getPdfPages = (file: SigitFile, fileIndex: number) => {
// Early return if this is not a pdf
if (!file.isPdf) return null
return (
<Box
sx={{
width: '100%'
}}
>
{pdfFile.pages.map((page, pdfPageIndex: number) => {
<>
{file.pages?.map((page, pageIndex: number) => {
return (
<div
key={pdfPageIndex}
style={{
border: '1px solid #c4c4c4',
marginBottom: '10px'
}}
className={`${styles.pdfImageWrapper} ${selectedTool ? styles.drawing : ''}`}
onMouseMove={(event) => {
onMouseMove(event, page)
}}
onMouseDown={(event) => {
onMouseDown(event, page)
}}
key={pageIndex}
className={`image-wrapper ${styles.pdfImageWrapper} ${selectedTool ? styles.drawing : ''}`}
tabIndex={-1}
onKeyDown={(event) => handleEscapeButtonDown(event)}
>
<img
onPointerMove={(event) => {
handlePointerMove(event, page)
}}
onPointerDown={(event) => {
handlePointerDown(event, page, fileIndex, pageIndex)
}}
draggable="false"
style={{ width: '100%' }}
src={page.image}
alt={`page ${pageIndex + 1} of ${file.name}`}
/>
{page.drawnFields.map((drawnField, drawnFieldIndex: number) => {
return (
<div
key={drawnFieldIndex}
onMouseDown={onDrawnFieldMouseDown}
onMouseMove={(event) => {
onDranwFieldMouseMove(event, drawnField)
onPointerDown={(event) =>
handleDrawnFieldPointerDown(
event,
fileIndex,
pageIndex,
drawnFieldIndex
)
}
onPointerMove={(event) => {
handleDrawnFieldPointerMove(event, drawnField, page.width)
}}
className={styles.drawingRectangle}
style={{
left: `${drawnField.left}px`,
top: `${drawnField.top}px`,
width: `${drawnField.width}px`,
height: `${drawnField.height}px`,
pointerEvents: mouseState.clicked ? 'none' : 'all'
backgroundColor: drawnField.counterpart
? `#${npubToHex(drawnField.counterpart)?.substring(0, 6)}4b`
: undefined,
outlineColor: drawnField.counterpart
? `#${npubToHex(drawnField.counterpart)?.substring(0, 6)}`
: undefined,
left: inPx(from(page.width, drawnField.left)),
top: inPx(from(page.width, drawnField.top)),
width: inPx(from(page.width, drawnField.width)),
height: inPx(from(page.width, drawnField.height)),
pointerEvents: mouseState.clicked ? 'none' : 'all',
touchAction: 'none',
opacity:
mouseState.dragging &&
isActiveDrawnField(
fileIndex,
pageIndex,
drawnFieldIndex
)
? 0.8
: undefined
}}
>
<div
className={`file-mark ${styles.placeholder}`}
style={{
fontFamily: FONT_TYPE,
fontSize: inPx(from(page.width, FONT_SIZE))
}}
>
{getToolboxLabelByMarkType(drawnField.type) ||
'placeholder'}
</div>
<span
onMouseDown={onResizeHandleMouseDown}
onMouseMove={(event) => {
onResizeHandleMouseMove(event, drawnField)
onPointerDown={(event) =>
handleResizePointerDown(
event,
fileIndex,
pageIndex,
drawnFieldIndex
)
}
onPointerMove={(event) => {
handleResizePointerMove(event, drawnField, page.width)
}}
className={styles.resizeHandle}
style={{
background:
mouseState.resizing &&
isActiveDrawnField(
fileIndex,
pageIndex,
drawnFieldIndex
)
? 'var(--primary-main)'
: undefined
}}
></span>
<span
onMouseDown={(event) => {
onRemoveHandleMouseDown(
onPointerDown={(event) => {
handleRemovePointerDown(
event,
pdfFileIndex,
pdfPageIndex,
fileIndex,
pageIndex,
drawnFieldIndex
)
}}
@ -462,128 +518,156 @@ export const DrawPDFFields = (props: Props) => {
>
<Close fontSize="small" />
</span>
<div
onMouseDown={onUserSelectHandleMouseDown}
className={styles.userSelect}
>
<FormControl fullWidth size="small">
<InputLabel id="counterparts">Counterpart</InputLabel>
<Select
value={drawnField.counterpart}
onChange={(event) => {
drawnField.counterpart = event.target.value
refreshPdfFiles()
}}
labelId="counterparts"
label="Counterparts"
{!isActiveDrawnField(
fileIndex,
pageIndex,
drawnFieldIndex
) &&
!!drawnField.counterpart && (
<div className={styles.counterpartAvatar}>
<UserAvatar
pubkey={npubToHex(drawnField.counterpart)!}
/>
</div>
)}
{isActiveDrawnField(
fileIndex,
pageIndex,
drawnFieldIndex
) &&
(!hideSignersForDrawnField ||
!hideSignersForDrawnField[drawnFieldIndex]) && (
<div
onPointerDown={handleUserSelectPointerDown}
className={styles.userSelect}
>
{props.users.map((user, index) => {
let displayValue = truncate(
hexToNpub(user.pubkey),
{
length: 16
<FormControl fullWidth size="small">
<InputLabel id="counterparts">
Counterpart
</InputLabel>
<Select
value={getAvailableSigner(drawnField.counterpart)}
onChange={(event) => {
drawnField.counterpart = event.target.value
setLastSigner(event.target.value)
refreshPdfFiles()
}}
labelId="counterparts"
label="Counterparts"
sx={{
background: 'white'
}}
renderValue={(value) =>
renderCounterpartValue(value)
}
)
const metadata = props.metadata[user.pubkey]
if (metadata) {
displayValue = truncate(
metadata.name ||
metadata.display_name ||
metadata.username,
{
length: 16
>
{signers.map((signer, index) => {
const npub = hexToNpub(signer.pubkey)
const metadata = props.metadata[signer.pubkey]
const displayValue = getProfileUsername(
npub,
metadata
)
// make current signers dropdown visible
if (
hideSignersForDrawnField[drawnFieldIndex] ===
undefined ||
hideSignersForDrawnField[drawnFieldIndex] ===
true
) {
setHideSignersForDrawnField((prev) => ({
...prev,
[drawnFieldIndex]: false
}))
}
)
}
return (
<MenuItem
key={index}
value={hexToNpub(user.pubkey)}
>
{displayValue}
</MenuItem>
)
})}
</Select>
</FormControl>
</div>
return (
<MenuItem key={index} value={npub}>
<ListItemIcon>
<AvatarIconButton
src={metadata?.picture}
hexKey={signer.pubkey}
aria-label={`account of user ${displayValue}`}
color="inherit"
sx={{
padding: 0,
'> img': {
width: '30px',
height: '30px'
}
}}
/>
</ListItemIcon>
<ListItemText>{displayValue}</ListItemText>
</MenuItem>
)
})}
</Select>
</FormControl>
</div>
)}
</div>
)
})}
</div>
)
})}
</Box>
</>
)
}
if (parsingPdf) {
return (
<Box sx={{ width: '100%', textAlign: 'center' }}>
<CircularProgress />
</Box>
)
}
const renderCounterpartValue = (npub: string) => {
let displayValue = _.truncate(npub, { length: 16 })
if (!pdfFiles.length) {
return ''
const signer = signers.find((u) => u.pubkey === npubToHex(npub))
if (signer) {
const metadata = props.metadata[signer.pubkey]
displayValue = getProfileUsername(npub, metadata)
return (
<div className={styles.counterpartSelectValue}>
<AvatarIconButton
src={props.metadata[signer.pubkey]?.picture}
hexKey={signer.pubkey || undefined}
sx={{
padding: 0,
marginRight: '6px',
'> img': {
width: '21px',
height: '21px'
}
}}
/>
{displayValue}
</div>
)
}
return displayValue
}
return (
<Box>
<Box sx={{ mt: 1 }}>
<Typography sx={{ mb: 1 }}>Draw fields on the PDFs:</Typography>
{pdfFiles.map((pdfFile, pdfFileIndex: number) => {
return (
<Accordion
key={pdfFileIndex}
expanded={pdfFile.expanded}
onChange={(_event, expanded) => {
handleAccordionExpandChange(expanded, pdfFile)
}}
>
<AccordionSummary
expandIcon={<ExpandMore />}
aria-controls={`panel${pdfFileIndex}-content`}
id={`panel${pdfFileIndex}header`}
>
<PictureAsPdf sx={{ mr: 1 }} />
{pdfFile.file.name}
</AccordionSummary>
<AccordionDetails>
{getPdfPages(pdfFile, pdfFileIndex)}
</AccordionDetails>
</Accordion>
)
})}
</Box>
{showDrawToolBox && (
<Box className={styles.drawToolBoxContainer}>
<Box className={styles.drawToolBox}>
{toolbox
.filter((drawTool) => drawTool.active)
.map((drawTool: DrawTool, index: number) => {
return (
<Box
key={index}
onClick={() => {
handleToolSelect(drawTool)
}}
className={`${styles.toolItem} ${selectedTool?.identifier === drawTool.identifier ? styles.selected : ''}`}
>
{drawTool.icon}
{drawTool.label}
</Box>
)
})}
</Box>
</Box>
)}
</Box>
<div className="files-wrapper">
{sigitFiles.map((file, i) => {
return (
<React.Fragment key={file.name}>
<div className="file-wrapper" id={`file-${file.name}`}>
{file.isPdf && getPdfPages(file, i)}
{file.isImage && (
<img
className="file-image"
src={file.objectUrl}
alt={file.name}
/>
)}
{!(file.isPdf || file.isImage) && (
<ExtensionFileBox extension={file.extension} />
)}
</div>
{i < sigitFiles.length - 1 && <FileDivider />}
</React.Fragment>
)
})}
</div>
)
}

View File

@ -1,3 +1,5 @@
@import '../../styles/sizes.scss';
.pdfFieldItem {
background: white;
padding: 10px;
@ -5,70 +7,26 @@
cursor: pointer;
}
.drawToolBoxContainer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: center;
z-index: 50;
.drawToolBox {
display: flex;
gap: 10px;
min-width: 100px;
background-color: white;
padding: 15px;
box-shadow: 0 0 10px 1px #0000003b;
border-radius: 4px;
.toolItem {
display: flex;
flex-direction: column;
align-items: center;
border: 1px solid rgba(0, 0, 0, 0.137);
padding: 5px;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
&.selected {
border-color: #01aaad;
color: #01aaad;
}
&:not(.selected) {
&:hover {
border-color: #01aaad79;
}
}
}
}
}
.pdfImageWrapper {
position: relative;
-webkit-user-select: none;
user-select: none;
margin-bottom: 10px;
> img {
display: block;
max-width: 100%;
max-height: 100%;
object-fit: contain; /* Ensure the image fits within the container */
}
&.drawing {
cursor: crosshair;
}
}
.pdfImageWrapper:focus {
outline: none;
}
.placeholder {
position: absolute;
opacity: 0.5;
inset: 0;
}
.drawingRectangle {
position: absolute;
border: 1px solid #01aaad;
z-index: 50;
outline: 1px solid #01aaad;
z-index: 40;
background-color: #01aaad4b;
cursor: pointer;
display: flex;
@ -81,7 +39,7 @@
}
&.edited {
border: 1px dotted #01aaad
outline: 1px dotted #01aaad;
}
.resizeHandle {
@ -93,7 +51,14 @@
background-color: #fff;
border: 1px solid rgb(160, 160, 160);
border-radius: 50%;
cursor: pointer;
cursor: nwse-resize;
// Increase the area a bit so it's easier to click
&::after {
content: '';
position: absolute;
inset: -14px;
}
}
.removeHandle {
@ -118,9 +83,19 @@
justify-content: center;
align-items: center;
bottom: -60px;
min-width: 170px;
min-width: 193px;
min-height: 30px;
background: #fff;
padding: 5px 0;
}
}
.counterpartSelectValue {
display: flex;
}
.counterpartAvatar {
img {
width: 21px;
height: 21px;
}
}

View File

@ -0,0 +1,6 @@
interface ExtensionFileBoxProps {
extension: string
}
export const ExtensionFileBox = ({ extension }: ExtensionFileBoxProps) => (
<div className="extension-file-box">This is a {extension} file</div>
)

View File

@ -0,0 +1,12 @@
import Divider from '@mui/material/Divider/Divider'
export const FileDivider = () => (
<Divider
sx={{
fontSize: '12px',
color: 'rgba(0,0,0,0.15)'
}}
>
File Separator
</Divider>
)

View File

@ -1,39 +1,49 @@
import { CurrentUserFile } from '../../types/file.ts'
import styles from './style.module.scss'
import { Button } from '@mui/material'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCheck } from '@fortawesome/free-solid-svg-icons'
interface FileListProps {
files: CurrentUserFile[]
currentFile: CurrentUserFile
setCurrentFile: (file: CurrentUserFile) => void
handleDownload: () => void
downloadLabel?: string
}
const FileList = ({
files,
currentFile,
setCurrentFile,
handleDownload
handleDownload,
downloadLabel
}: FileListProps) => {
const isActive = (file: CurrentUserFile) => file.id === currentFile.id
return (
<div className={styles.wrap}>
<div className={styles.container}>
<ul className={styles.files}>
{files.map((file: CurrentUserFile) => (
<li
key={file.id}
className={`${styles.fileItem} ${isActive(file) && styles.active}`}
onClick={() => setCurrentFile(file)}
>
<span className={styles.fileNumber}>{file.id}</span>
<span className={styles.fileName}>{file.filename}</span>
</li>
))}
</ul>
</div>
<ul className={styles.files}>
{files.map((currentUserFile: CurrentUserFile) => (
<li
key={currentUserFile.id}
className={`${styles.fileItem} ${isActive(currentUserFile) && styles.active}`}
onClick={() => setCurrentFile(currentUserFile)}
>
<div className={styles.fileNumber}>{currentUserFile.id}</div>
<div className={styles.fileInfo}>
<div className={styles.fileName}>{currentUserFile.file.name}</div>
</div>
<div className={styles.fileVisual}>
{currentUserFile.isHashValid && (
<FontAwesomeIcon icon={faCheck} />
)}
</div>
</li>
))}
</ul>
<Button variant="contained" fullWidth onClick={handleDownload}>
Download Files
{downloadLabel || 'Download Files'}
</Button>
</div>
)

View File

@ -1,12 +1,3 @@
.container {
border-radius: 4px;
background: white;
padding: 15px;
display: flex;
flex-direction: column;
grid-gap: 0px;
}
.filesPageContainer {
width: 100%;
display: grid;
@ -15,13 +6,6 @@
flex-grow: 1;
}
ul {
list-style-type: none; /* Removes bullet points */
margin: 0; /* Removes default margin */
padding: 0; /* Removes default padding */
}
.wrap {
display: flex;
flex-direction: column;
@ -29,14 +13,16 @@ ul {
}
.files {
border-radius: 4px;
background: white;
padding: 15px;
display: flex;
flex-direction: column;
width: 100%;
grid-gap: 15px;
max-height: 350px;
overflow: auto;
padding: 0 5px 0 0;
margin: 0 -5px 0 0;
overflow-y: auto;
overflow-x: none;
}
.files::-webkit-scrollbar {
@ -44,7 +30,7 @@ ul {
}
.files::-webkit-scrollbar-track {
background-color: rgba(0,0,0,0.15);
background-color: rgba(0, 0, 0, 0.15);
}
.files::-webkit-scrollbar-thumb {
@ -64,12 +50,12 @@ ul {
background: #ffffff;
padding: 5px 10px;
align-items: center;
color: rgba(0,0,0,0.5);
color: rgba(0, 0, 0, 0.5);
cursor: pointer;
flex-grow: 1;
font-size: 16px;
font-weight: 500;
min-height: 45px;
&.active {
background: #4c82a3;
@ -78,16 +64,22 @@ ul {
}
.fileItem:hover {
transition: ease 0.2s;
background: #4c82a3;
color: white;
}
.fileInfo {
flex-grow: 1;
font-size: 16px;
font-weight: 500;
}
.fileName {
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
-webkit-line-clamp: 1;
line-clamp: 1;
}
.fileNumber {
@ -97,4 +89,15 @@ ul {
flex-direction: column;
justify-content: center;
align-items: center;
}
width: 10px;
}
.fileVisual {
display: flex;
flex-shrink: 0;
flex-direction: column;
justify-content: center;
align-items: center;
height: 25px;
width: 25px;
}

View File

@ -4,125 +4,128 @@ import styles from './style.module.scss'
import { Container } from '../Container'
import nostrImage from '../../assets/images/nostr.gif'
import { appPublicRoutes } from '../../routes'
import { createPortal } from 'react-dom'
export const Footer = () => (
<footer className={`${styles.borderTop} ${styles.footer}`}>
<Container
style={{
paddingBlock: '50px'
}}
>
<Box
display={'grid'}
sx={{
gridTemplateColumns: {
xs: '1fr',
md: '0.5fr 2fr 0.5fr'
},
alignItems: {
xs: 'center',
md: 'start'
}
export const Footer = () =>
createPortal(
<footer className={`${styles.borderTop} ${styles.footer}`}>
<Container
style={{
paddingBlock: '50px'
}}
gap={'50px'}
>
<LinkMui
<Box
display={'grid'}
sx={{
justifySelf: {
gridTemplateColumns: {
xs: '1fr',
md: '0.5fr 2fr 0.5fr'
},
alignItems: {
xs: 'center',
md: 'start'
}
}}
component={Link}
to={'/'}
className={styles.logo}
gap={'50px'}
>
<img src="/logo.svg" alt="Logo" />
</LinkMui>
<Box
display={'grid'}
sx={{
gap: '15px',
gridTemplateColumns: {
xs: '1fr',
sm: 'repeat(2, 1fr)',
xl: 'repeat(3, 1fr)'
},
borderBlock: {
xs: 'solid 1px rgba(0, 0, 0, 0.1)',
md: 'unset'
},
paddingY: {
xs: '10px',
md: 'unset'
}
}}
component={'nav'}
className={styles.nav}
>
<Button
<LinkMui
sx={{
justifyContent: 'center'
justifySelf: {
xs: 'center',
md: 'start'
}
}}
component={Link}
to={'/'}
variant={'text'}
className={styles.logo}
>
Home
</Button>
<Button
<img src="/logo.svg" alt="Logo" />
</LinkMui>
<Box
display={'grid'}
sx={{
justifyContent: 'center'
gap: '15px',
gridTemplateColumns: {
xs: '1fr',
sm: 'repeat(2, 1fr)',
xl: 'repeat(3, 1fr)'
},
borderBlock: {
xs: 'solid 1px rgba(0, 0, 0, 0.1)',
md: 'unset'
},
paddingY: {
xs: '10px',
md: 'unset'
}
}}
component={LinkMui}
href={appPublicRoutes.docs}
target="_blank"
variant={'text'}
component={'nav'}
className={styles.nav}
>
Documentation
</Button>
<Button
<Button
sx={{
justifyContent: 'center'
}}
component={Link}
to={'/'}
variant={'text'}
>
Home
</Button>
<Button
sx={{
justifyContent: 'center'
}}
component={LinkMui}
href={appPublicRoutes.docs}
target="_blank"
variant={'text'}
>
Documentation
</Button>
<Button
sx={{
justifyContent: 'center'
}}
component={LinkMui}
href={appPublicRoutes.source}
target="_blank"
variant={'text'}
>
Source
</Button>
</Box>
<Box
className={styles.links}
sx={{
justifyContent: 'center'
justifySelf: {
xs: 'center',
md: 'end'
}
}}
component={LinkMui}
href={appPublicRoutes.source}
target="_blank"
variant={'text'}
>
Source
</Button>
<Button
component={LinkMui}
href="https://snort.social/npub1yay8e9sqk94jfgdlkpgeelj2t5ddsj2eu0xwt4kh4xw5ses2rauqnstrdv"
target="_blank"
sx={{
minWidth: '45px',
padding: '10px'
}}
variant={'contained'}
>
<img src={nostrImage} width="25" alt="nostr logo" height="25" />
</Button>
</Box>
</Box>
<Box
className={styles.links}
sx={{
justifySelf: {
xs: 'center',
md: 'end'
}
}}
>
<Button
component={LinkMui}
href="https://snort.social/npub1yay8e9sqk94jfgdlkpgeelj2t5ddsj2eu0xwt4kh4xw5ses2rauqnstrdv"
target="_blank"
sx={{
minWidth: '45px',
padding: '10px'
}}
variant={'contained'}
>
<img src={nostrImage} width="25" alt="nostr logo" height="25" />
</Button>
</Box>
</Box>
</Container>
<div className={`${styles.borderTop} ${styles.credits}`}>
Built by&nbsp;
<a href="https://nostrdev.com/" target="_blank">
Nostr Dev
</a>{' '}
2024.
</div>
</footer>
)
</Container>
<div className={`${styles.borderTop} ${styles.credits}`}>
Built by&nbsp;
<a rel="noopener" href="https://nostrdev.com/" target="_blank">
Nostr Dev
</a>{' '}
2024.
</div>
</footer>,
document.getElementById('root')!
)

View File

@ -1,18 +1,43 @@
import { createPortal } from 'react-dom'
import styles from './style.module.scss'
import { PropsWithChildren } from 'react'
interface Props {
desc: string
desc?: string
variant?: 'small' | 'default'
}
export const LoadingSpinner = (props: Props) => {
const { desc } = props
export const LoadingSpinner = (props: PropsWithChildren<Props>) => {
const { desc, children, variant = 'default' } = props
return (
<div className={styles.loadingSpinnerOverlay}>
<div className={styles.loadingSpinnerContainer}>
<div className={styles.loadingSpinner}></div>
{desc && <span className={styles.loadingSpinnerDesc}>{desc}</span>}
</div>
</div>
)
switch (variant) {
case 'small':
return (
<div
className={`${styles.loadingSpinnerContainer}`}
data-variant={variant}
>
<div className={styles.loadingSpinner}></div>
</div>
)
default:
return createPortal(
<div className={styles.loadingSpinnerOverlay}>
<div
className={styles.loadingSpinnerContainer}
data-variant={variant}
>
<div className={styles.loadingSpinner}></div>
{desc && (
<div className={styles.loadingSpinnerDesc}>
{desc}
{children}
</div>
)}
</div>
</div>,
document.getElementById('root')!
)
}
}

View File

@ -2,37 +2,56 @@
.loadingSpinnerOverlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.5);
z-index: 9999;
z-index: 50;
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
}
.loadingSpinnerContainer {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
.loadingSpinnerContainer {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
&[data-variant='default'] {
width: 100%;
max-width: 500px;
margin: 25px 20px;
background: $overlay-background-color;
border-radius: 4px;
box-shadow: 0 0 4px 0 rgb(0, 0, 0, 0.1);
}
.loadingSpinner {
background: url('/favicon.png') no-repeat center / cover;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
&[data-variant='small'] {
min-height: 250px;
}
}
.loadingSpinner {
background: url('/favicon.png') no-repeat center / cover;
margin: 40px 25px;
width: 65px;
height: 65px;
animation: spin 1s linear infinite;
}
.loadingSpinnerDesc {
color: white;
margin-top: 13px;
width: 100%;
padding: 15px;
border-top: solid 1px rgba(0, 0, 0, 0.1);
color: rgba(0, 0, 0, 0.5);
font-size: 16px;
font-weight: 400;
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
}
@keyframes spin {

View File

@ -1,21 +1,21 @@
import { CurrentUserMark } from '../../types/mark.ts'
import styles from './style.module.scss'
import { MARK_TYPE_TRANSLATION, NEXT, SIGN } from '../../utils/const.ts'
import {
findNextIncompleteCurrentUserMark,
getToolboxLabelByMarkType,
isCurrentUserMarksComplete,
isCurrentValueLast
} from '../../utils'
import { useState } from 'react'
import React, { useState } from 'react'
import { MARK_TYPE_CONFIG } from '../getMarkComponents.tsx'
interface MarkFormFieldProps {
handleSubmit: (event: any) => void
handleSelectedMarkValueChange: (event: any) => void
selectedMark: CurrentUserMark
selectedMarkValue: string
currentUserMarks: CurrentUserMark[]
handleCurrentUserMarkChange: (mark: CurrentUserMark) => void
handleSelectedMarkValueChange: (value: string) => void
handleSubmit: (event: React.FormEvent<HTMLFormElement>) => void
selectedMark: CurrentUserMark
selectedMarkValue: string
}
/**
@ -30,7 +30,6 @@ const MarkFormField = ({
handleCurrentUserMarkChange
}: MarkFormFieldProps) => {
const [displayActions, setDisplayActions] = useState(true)
const getSubmitButtonText = () => (isReadyToSign() ? SIGN : NEXT)
const isReadyToSign = () =>
isCurrentUserMarksComplete(currentUserMarks) ||
isCurrentValueLast(currentUserMarks, selectedMark, selectedMarkValue)
@ -52,6 +51,9 @@ const MarkFormField = ({
: handleCurrentUserMarkChange(findNext()!)
}
const toggleActions = () => setDisplayActions(!displayActions)
const markLabel = getToolboxLabelByMarkType(selectedMark.mark.type)
const { input: MarkInputComponent } =
MARK_TYPE_CONFIG[selectedMark.mark.type] || {}
return (
<div className={styles.container}>
<div className={styles.trigger}>
@ -59,6 +61,7 @@ const MarkFormField = ({
onClick={toggleActions}
className={styles.triggerBtn}
type="button"
title="Toggle"
>
<svg
xmlns="http://www.w3.org/2000/svg"
@ -76,22 +79,22 @@ const MarkFormField = ({
<div className={styles.actionsWrapper}>
<div className={styles.actionsTop}>
<div className={styles.actionsTopInfo}>
<p className={styles.actionsTopInfoText}>Add your signature</p>
<p className={styles.actionsTopInfoText}>Add {markLabel}</p>
</div>
</div>
<div className={styles.inputWrapper}>
<form onSubmit={(e) => handleFormSubmit(e)}>
<input
className={styles.input}
placeholder={
MARK_TYPE_TRANSLATION[selectedMark.mark.type.valueOf()]
}
onChange={handleSelectedMarkValueChange}
value={selectedMarkValue}
/>
{typeof MarkInputComponent !== 'undefined' && (
<MarkInputComponent
value={selectedMarkValue}
placeholder={markLabel}
handler={handleSelectedMarkValueChange}
userMark={selectedMark}
/>
)}
<div className={styles.actionsBottom}>
<button type="submit" className={styles.submitButton}>
{getSubmitButtonText()}
NEXT
</button>
</div>
</form>

View File

@ -1,25 +1,127 @@
@import '../../styles/sizes.scss';
.container {
width: 100%;
display: flex;
flex-direction: column;
position: fixed;
bottom: 0;
right: 0;
left: 0;
@media only screen and (min-width: 768px) {
bottom: 0;
right: 0;
left: 0;
}
bottom: $tabs-height + 5px;
right: 5px;
left: 5px;
align-items: center;
z-index: 1000;
z-index: 40;
button {
transition: ease 0.2s;
width: auto;
border-radius: 4px;
outline: unset;
border: unset;
background: unset;
color: #ffffff;
background: #4c82a3;
font-weight: 500;
font-size: 14px;
padding: 8px 15px;
white-space: nowrap;
display: flex;
flex-direction: row;
grid-gap: 12px;
justify-content: center;
align-items: center;
text-decoration: unset;
position: relative;
cursor: pointer;
}
button:hover {
background: #5e8eab;
color: white;
}
button:active {
background: #447592;
color: white;
}
.actionButtons {
display: flex;
flex-direction: row;
grid-gap: 5px;
}
.actionsBottom {
display: flex;
flex-direction: row;
grid-gap: 5px;
justify-content: center;
align-items: center;
}
.submitButton {
width: 100%;
max-width: 300px;
margin-top: 10px;
}
.paginationButton {
font-size: 12px;
padding: 5px 10px;
border-radius: 3px;
background: rgba(0, 0, 0, 0.1);
color: rgba(0, 0, 0, 0.5);
}
.paginationButton:hover {
background: #447592;
color: rgba(255, 255, 255, 0.5);
}
.paginationButtonDone {
background: #5e8eab;
color: rgb(255, 255, 255);
}
.paginationButtonCurrent {
height: 2px;
width: 100%;
background: #4c82a3;
}
.trigger {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
position: relative;
}
.triggerBtn {
background: white;
color: #434343;
padding: 5px 30px;
box-shadow: 0px -3px 4px 0 rgb(0, 0, 0, 0.1);
position: absolute;
top: -25px;
}
}
.actions {
background: white;
width: 100%;
border-radius: 4px;
border-radius: 5px;
padding: 10px 20px;
display: none;
flex-direction: column;
align-items: center;
grid-gap: 15px;
box-shadow: 0 -2px 4px 0 rgb(0,0,0,0.1);
box-shadow: 0 -2px 4px 0 rgb(0, 0, 0, 0.1);
max-width: 750px;
&.expanded {
@ -59,12 +161,6 @@
position: relative;
}
.actionButtons {
display: flex;
flex-direction: row;
grid-gap: 5px;
}
.inputWrapper {
display: flex;
flex-direction: column;
@ -73,7 +169,7 @@
.textInput {
height: 100px;
background: rgba(0,0,0,0.1);
background: rgba(0, 0, 0, 0.1);
border-radius: 4px;
border: solid 2px #4c82a3;
display: flex;
@ -84,66 +180,19 @@
.input {
border-radius: 4px;
border: solid 1px rgba(0,0,0,0.15);
border: solid 1px rgba(0, 0, 0, 0.15);
padding: 5px 10px;
font-size: 16px;
width: 100%;
background: linear-gradient(rgba(0,0,0,0.00), rgba(0,0,0,0.00) 100%), linear-gradient(white, white);
background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0) 100%),
linear-gradient(white, white);
}
.input:focus {
border: solid 1px rgba(0,0,0,0.15);
border: solid 1px rgba(0, 0, 0, 0.15);
outline: none;
background: linear-gradient(rgba(0,0,0,0.05), rgba(0,0,0,0.05) 100%), linear-gradient(white, white);
}
.actionsBottom {
display: flex;
flex-direction: row;
grid-gap: 5px;
justify-content: center;
align-items: center;
}
button {
transition: ease 0.2s;
width: auto;
border-radius: 4px;
outline: unset;
border: unset;
background: unset;
color: #ffffff;
background: #4c82a3;
font-weight: 500;
font-size: 14px;
padding: 8px 15px;
white-space: nowrap;
display: flex;
flex-direction: row;
grid-gap: 12px;
justify-content: center;
align-items: center;
text-decoration: unset;
position: relative;
cursor: pointer;
}
button:hover {
transition: ease 0.2s;
background: #5e8eab;
color: white;
}
button:active {
transition: ease 0.2s;
background: #447592;
color: white;
}
.submitButton {
width: 100%;
max-width: 300px;
margin-top: 10px;
background: linear-gradient(rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.05) 100%),
linear-gradient(white, white);
}
.footerContainer {
@ -167,44 +216,3 @@ button:active {
flex-direction: column;
grid-gap: 5px;
}
.paginationButton {
font-size: 12px;
padding: 5px 10px;
border-radius: 3px;
background: rgba(0,0,0,0.1);
color: rgba(0,0,0,0.5);
}
.paginationButton:hover {
background: #447592;
color: rgba(255,255,255,0.5);
}
.paginationButtonDone {
background: #5e8eab;
color: rgb(255,255,255);
}
.paginationButtonCurrent {
height: 2px;
width: 100%;
background: #4c82a3;
}
.trigger {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
position: relative;
}
.triggerBtn {
background: white;
color: #434343;
padding: 5px 30px;
box-shadow: 0px -3px 4px 0 rgb(0,0,0,0.1);
position: absolute;
top: -25px;
}

View File

@ -0,0 +1,44 @@
@import '../../styles/colors.scss';
$padding: 5px;
.wrapper {
display: flex;
justify-content: center;
align-items: center;
padding: $padding;
}
.relative {
position: relative;
}
.canvas {
outline: 1px solid black;
background-color: $body-background-color;
cursor: crosshair;
// Disable panning/zooming when touching canvas element
-ms-touch-action: none;
touch-action: none;
-webkit-user-select: none;
user-select: none;
}
.absolute {
position: absolute;
inset: 0;
pointer-events: none;
}
.reset {
cursor: pointer;
position: absolute;
top: 0;
right: $padding;
color: $primary-main;
&:hover {
color: $primary-dark;
}
}

View File

@ -0,0 +1,101 @@
import { useRef, useState } from 'react'
import { MarkInputProps } from '../../types/mark'
import { getOptimizedPaths, optimizeSVG } from '../../utils'
import { faEraser } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import styles from './Signature.module.scss'
import { MarkRenderSignature } from '../MarkRender/Signature'
export const MarkInputSignature = ({
value,
handler,
userMark
}: MarkInputProps) => {
const location = userMark?.mark.location
const canvasRef = useRef<HTMLCanvasElement>(null)
const [drawing, setDrawing] = useState(false)
const [paths, setPaths] = useState<string[]>(value ? JSON.parse(value) : [])
function update() {
if (location && paths) {
if (paths.length) {
const optimizedSvg = optimizeSVG(location, paths)
const extractedPaths = getOptimizedPaths(optimizedSvg)
handler(JSON.stringify(extractedPaths))
} else {
handler('')
}
}
}
const handlePointerDown = (event: React.PointerEvent) => {
const rect = event.currentTarget.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
const ctx = canvasRef.current?.getContext('2d')
ctx?.beginPath()
ctx?.moveTo(x, y)
setPaths([...paths, `M ${x} ${y}`])
setDrawing(true)
}
const handlePointerUp = () => {
setDrawing(false)
update()
const ctx = canvasRef.current?.getContext('2d')
ctx?.clearRect(0, 0, canvasRef.current!.width, canvasRef.current!.height)
}
const handlePointerMove = (event: React.PointerEvent) => {
if (!drawing) return
const ctx = canvasRef.current?.getContext('2d')
const rect = canvasRef.current?.getBoundingClientRect()
const x = event.clientX - rect!.left
const y = event.clientY - rect!.top
ctx?.lineTo(x, y)
ctx?.stroke()
// Collect the path data
setPaths((prevPaths) => {
const newPaths = [...prevPaths]
newPaths[newPaths.length - 1] += ` L ${x} ${y}`
return newPaths
})
}
const handleReset = () => {
setPaths([])
setDrawing(false)
update()
const ctx = canvasRef.current?.getContext('2d')
ctx?.clearRect(0, 0, canvasRef.current!.width, canvasRef.current!.height)
}
return (
<>
<div className={styles.wrapper}>
<div className={styles.relative}>
<canvas
height={location?.height}
width={location?.width}
ref={canvasRef}
className={styles.canvas}
onPointerDown={handlePointerDown}
onPointerUp={handlePointerUp}
onPointerMove={handlePointerMove}
onPointerOut={handlePointerUp}
></canvas>
{typeof userMark?.mark !== 'undefined' && (
<div className={styles.absolute}>
<MarkRenderSignature value={value} mark={userMark.mark} />
</div>
)}
<div className={styles.reset}>
<FontAwesomeIcon size="sm" icon={faEraser} onClick={handleReset} />
</div>
</div>
</div>
</>
)
}

View File

@ -0,0 +1,19 @@
import { MarkInputProps } from '../../types/mark'
import styles from '../MarkFormField/style.module.scss'
export const MarkInputText = ({
value,
handler,
placeholder
}: MarkInputProps) => {
return (
<input
className={styles.input}
placeholder={placeholder}
onChange={(e) => {
handler(e.currentTarget.value)
}}
value={value}
/>
)
}

View File

@ -0,0 +1,13 @@
import { MarkRenderProps } from '../../types/mark'
export const MarkRenderSignature = ({ value, mark }: MarkRenderProps) => {
const paths = value ? JSON.parse(value) : []
return (
<svg viewBox={`0 0 ${mark.location.width} ${mark.location.height}`}>
{paths.map((path: string) => (
<path d={path} stroke="black" fill="none" />
))}
</svg>
)
}

View File

@ -1,24 +1,27 @@
import { PdfFile } from '../../types/drawing.ts'
import { CurrentUserMark } from '../../types/mark.ts'
import { CurrentUserMark, Mark } from '../../types/mark.ts'
import { SigitFile } from '../../utils/file.ts'
import { ExtensionFileBox } from '../ExtensionFileBox.tsx'
import PdfPageItem from './PdfPageItem.tsx'
interface PdfItemProps {
pdfFile: PdfFile
currentUserMarks: CurrentUserMark[]
handleMarkClick: (id: number) => void
selectedMarkValue: string
otherUserMarks: Mark[]
file: SigitFile
selectedMark: CurrentUserMark | null
selectedMarkValue: string
}
/**
* Responsible for displaying pages of a single Pdf File.
*/
const PdfItem = ({
pdfFile,
file,
currentUserMarks,
handleMarkClick,
selectedMarkValue,
selectedMark
selectedMark,
otherUserMarks
}: PdfItemProps) => {
const filterByPage = (
marks: CurrentUserMark[],
@ -26,18 +29,30 @@ const PdfItem = ({
): CurrentUserMark[] => {
return marks.filter((m) => m.mark.location.page === page)
}
return pdfFile.pages.map((page, i) => {
return (
<PdfPageItem
page={page}
key={i}
currentUserMarks={filterByPage(currentUserMarks, i)}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
selectedMark={selectedMark}
/>
)
})
const filterMarksByPage = (marks: Mark[], page: number): Mark[] => {
return marks.filter((mark) => mark.location.page === page)
}
if (file.isPdf) {
return file.pages?.map((page, i) => {
return (
<PdfPageItem
fileName={file.name}
pageIndex={i}
page={page}
key={i}
currentUserMarks={filterByPage(currentUserMarks, i)}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
selectedMark={selectedMark}
otherUserMarks={filterMarksByPage(otherUserMarks, i)}
/>
)
})
} else if (file.isImage) {
return <img className="file-image" src={file.objectUrl} alt={file.name} />
} else {
return <ExtensionFileBox extension={file.extension} />
}
}
export default PdfItem

View File

@ -1,42 +1,61 @@
import { CurrentUserMark } from '../../types/mark.ts'
import styles from '../DrawPDFFields/style.module.scss'
import { inPx } from '../../utils/pdf.ts'
import { FONT_SIZE, FONT_TYPE, inPx } from '../../utils/pdf.ts'
import { useScale } from '../../hooks/useScale.tsx'
import { forwardRef } from 'react'
import { npubToHex } from '../../utils/nostr.ts'
import { MARK_TYPE_CONFIG } from '../getMarkComponents.tsx'
interface PdfMarkItemProps {
userMark: CurrentUserMark
handleMarkClick: (id: number) => void
selectedMarkValue: string
selectedMark: CurrentUserMark | null
pageWidth: number
}
/**
* Responsible for display an individual Pdf Mark.
*/
const PdfMarkItem = ({
selectedMark,
handleMarkClick,
selectedMarkValue,
userMark
}: PdfMarkItemProps) => {
const { location } = userMark.mark
const handleClick = () => handleMarkClick(userMark.mark.id)
const isEdited = () => selectedMark?.mark.id === userMark.mark.id
const getMarkValue = () =>
isEdited() ? selectedMarkValue : userMark.currentValue
return (
<div
onClick={handleClick}
className={`${styles.drawingRectangle} ${isEdited() && styles.edited}`}
style={{
left: inPx(location.left),
top: inPx(location.top),
width: inPx(location.width),
height: inPx(location.height)
}}
>
{getMarkValue()}
</div>
)
}
const PdfMarkItem = forwardRef<HTMLDivElement, PdfMarkItemProps>(
(
{ selectedMark, handleMarkClick, selectedMarkValue, userMark, pageWidth },
ref
) => {
const { location } = userMark.mark
const handleClick = () => handleMarkClick(userMark.mark.id)
const isEdited = () => selectedMark?.mark.id === userMark.mark.id
const getMarkValue = () =>
isEdited() ? selectedMarkValue : userMark.currentValue
const { from } = useScale()
const { render: MarkRenderComponent } =
MARK_TYPE_CONFIG[userMark.mark.type] || {}
return (
<div
ref={ref}
onClick={handleClick}
className={`file-mark ${styles.drawingRectangle} ${isEdited() && styles.edited}`}
style={{
backgroundColor: selectedMark?.mark.npub
? `#${npubToHex(selectedMark?.mark.npub)?.substring(0, 6)}4b`
: undefined,
outlineColor: selectedMark?.mark.npub
? `#${npubToHex(selectedMark?.mark.npub)?.substring(0, 6)}`
: undefined,
left: inPx(from(pageWidth, location.left)),
top: inPx(from(pageWidth, location.top)),
width: inPx(from(pageWidth, location.width)),
height: inPx(from(pageWidth, location.height)),
fontFamily: FONT_TYPE,
fontSize: inPx(from(pageWidth, FONT_SIZE))
}}
>
{typeof MarkRenderComponent !== 'undefined' && (
<MarkRenderComponent value={getMarkValue()} mark={userMark.mark} />
)}
</div>
)
}
)
export default PdfMarkItem

View File

@ -10,18 +10,26 @@ import {
import { EMPTY } from '../../utils/const.ts'
import { Container } from '../Container'
import signPageStyles from '../../pages/sign/style.module.scss'
import styles from './style.module.scss'
import { CurrentUserFile } from '../../types/file.ts'
import FileList from '../FileList'
import { StickySideColumns } from '../../layouts/StickySideColumns.tsx'
import { UsersDetails } from '../UsersDetails.tsx'
import { Meta } from '../../types'
import {
faCircleInfo,
faFileDownload,
faPen
} from '@fortawesome/free-solid-svg-icons'
interface PdfMarkingProps {
files: CurrentUserFile[]
currentUserMarks: CurrentUserMark[]
setIsReadyToSign: (isReadyToSign: boolean) => void
setCurrentUserMarks: (currentUserMarks: CurrentUserMark[]) => void
setUpdatedMarks: (markToUpdate: Mark) => void
files: CurrentUserFile[]
handleDownload: () => void
meta: Meta | null
otherUserMarks: Mark[]
setCurrentUserMarks: (currentUserMarks: CurrentUserMark[]) => void
setIsMarksCompleted: (isMarksCompleted: boolean) => void
setUpdatedMarks: (markToUpdate: Mark) => void
}
/**
@ -34,10 +42,12 @@ const PdfMarking = (props: PdfMarkingProps) => {
const {
files,
currentUserMarks,
setIsReadyToSign,
setIsMarksCompleted,
setCurrentUserMarks,
setUpdatedMarks,
handleDownload
handleDownload,
meta,
otherUserMarks
} = props
const [selectedMark, setSelectedMark] = useState<CurrentUserMark | null>(null)
const [selectedMarkValue, setSelectedMarkValue] = useState<string>('')
@ -81,8 +91,8 @@ const PdfMarking = (props: PdfMarkingProps) => {
}
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!selectedMarkValue || !selectedMark) return;
event.preventDefault()
if (!selectedMarkValue || !selectedMark) return
const updatedMark: CurrentUserMark = getUpdatedMark(
selectedMark,
@ -96,7 +106,7 @@ const PdfMarking = (props: PdfMarkingProps) => {
)
setCurrentUserMarks(updatedCurrentUserMarks)
setSelectedMark(null)
setIsReadyToSign(true)
setIsMarksCompleted(true)
setUpdatedMarks(updatedMark.mark)
}
@ -107,8 +117,7 @@ const PdfMarking = (props: PdfMarkingProps) => {
// setCurrentUserMarks(updatedCurrentUserMarks)
// }
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) =>
setSelectedMarkValue(event.target.value)
const handleChange = (value: string) => setSelectedMarkValue(value)
return (
<>
@ -126,21 +135,22 @@ const PdfMarking = (props: PdfMarkingProps) => {
)}
</div>
}
right={meta !== null && <UsersDetails meta={meta} />}
leftIcon={faFileDownload}
centerIcon={faPen}
rightIcon={faCircleInfo}
>
<div className={styles.container}>
{currentUserMarks?.length > 0 && (
<div className={styles.pdfView}>
<PdfView
currentFile={currentFile}
files={files}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
selectedMark={selectedMark}
currentUserMarks={currentUserMarks}
/>
</div>
)}
</div>
{currentUserMarks?.length > 0 && (
<PdfView
currentFile={currentFile}
files={files}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
selectedMark={selectedMark}
currentUserMarks={currentUserMarks}
otherUserMarks={otherUserMarks}
/>
)}
</StickySideColumns>
{selectedMark !== null && (
<MarkFormField

View File

@ -1,54 +1,82 @@
import styles from '../DrawPDFFields/style.module.scss'
import { PdfPage } from '../../types/drawing.ts'
import { CurrentUserMark } from '../../types/mark.ts'
import { CurrentUserMark, Mark } from '../../types/mark.ts'
import PdfMarkItem from './PdfMarkItem.tsx'
import { useEffect, useRef } from 'react'
import pdfViewStyles from './style.module.scss'
import { FONT_SIZE, FONT_TYPE, inPx } from '../../utils/pdf.ts'
import { useScale } from '../../hooks/useScale.tsx'
interface PdfPageProps {
page: PdfPage
fileName: string
pageIndex: number
currentUserMarks: CurrentUserMark[]
handleMarkClick: (id: number) => void
selectedMarkValue: string
otherUserMarks: Mark[]
page: PdfPage
selectedMark: CurrentUserMark | null
selectedMarkValue: string
}
/**
* Responsible for rendering a single Pdf Page and its Marks
*/
const PdfPageItem = ({
fileName,
pageIndex,
page,
currentUserMarks,
handleMarkClick,
selectedMarkValue,
selectedMark
selectedMark,
otherUserMarks
}: PdfPageProps) => {
useEffect(() => {
if (selectedMark !== null && !!markRefs.current[selectedMark.id]) {
markRefs.current[selectedMark.id]?.scrollIntoView({
behavior: 'smooth',
block: 'end'
block: 'center'
})
}
}, [selectedMark])
const markRefs = useRef<(HTMLDivElement | null)[]>([])
const { from } = useScale()
return (
<div
className={styles.pdfImageWrapper}
style={{
border: '1px solid #c4c4c4'
}}
>
<img draggable="false" src={page.image} style={{ width: '100%' }} />
<div className={`image-wrapper ${styles.pdfImageWrapper}`}>
<img
draggable="false"
src={page.image}
alt={`page ${pageIndex + 1} of ${fileName}`}
/>
{currentUserMarks.map((m, i) => (
<div key={i} ref={(el) => (markRefs.current[m.id] = el)}>
<PdfMarkItem
key={i}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
userMark={m}
selectedMark={selectedMark}
/>
</div>
<PdfMarkItem
key={i}
ref={(el) => (markRefs.current[m.id] = el)}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
userMark={m}
selectedMark={selectedMark}
pageWidth={page.width}
/>
))}
{otherUserMarks.map((m, i) => {
return (
<div
key={i}
className={pdfViewStyles.otherUserMarksDisplay}
style={{
left: inPx(from(page.width, m.location.left)),
top: inPx(from(page.width, m.location.top)),
width: inPx(from(page.width, m.location.width)),
height: inPx(from(page.width, m.location.height)),
fontFamily: FONT_TYPE,
fontSize: inPx(from(page.width, FONT_SIZE))
}}
>
{m.value}
</div>
)
})}
</div>
)
}

View File

@ -1,16 +1,19 @@
import { Divider } from '@mui/material'
import PdfItem from './PdfItem.tsx'
import { CurrentUserMark } from '../../types/mark.ts'
import { CurrentUserMark, Mark } from '../../types/mark.ts'
import { CurrentUserFile } from '../../types/file.ts'
import { useEffect, useRef } from 'react'
import { FileDivider } from '../FileDivider.tsx'
import React from 'react'
import { LoadingSpinner } from '../LoadingSpinner/index.tsx'
interface PdfViewProps {
files: CurrentUserFile[]
currentUserMarks: CurrentUserMark[]
handleMarkClick: (id: number) => void
selectedMarkValue: string
selectedMark: CurrentUserMark | null
currentFile: CurrentUserFile | null
currentUserMarks: CurrentUserMark[]
files: CurrentUserFile[]
handleMarkClick: (id: number) => void
otherUserMarks: Mark[]
selectedMark: CurrentUserMark | null
selectedMarkValue: string
}
/**
@ -22,50 +25,59 @@ const PdfView = ({
handleMarkClick,
selectedMarkValue,
selectedMark,
currentFile
currentFile,
otherUserMarks
}: PdfViewProps) => {
const pdfRefs = useRef<(HTMLDivElement | null)[]>([])
useEffect(() => {
if (currentFile !== null && !!pdfRefs.current[currentFile.id]) {
pdfRefs.current[currentFile.id]?.scrollIntoView({
behavior: 'smooth',
block: 'end'
})
pdfRefs.current[currentFile.id]?.scrollIntoView({ behavior: 'smooth' })
}
}, [currentFile])
const filterByFile = (
currentUserMarks: CurrentUserMark[],
fileName: string
hash: string
): CurrentUserMark[] => {
return currentUserMarks.filter(
(currentUserMark) => currentUserMark.mark.fileName === fileName
(currentUserMark) => currentUserMark.mark.pdfFileHash === hash
)
}
const filterMarksByFile = (marks: Mark[], hash: string): Mark[] => {
return marks.filter((mark) => mark.pdfFileHash === hash)
}
const isNotLastPdfFile = (index: number, files: CurrentUserFile[]): boolean =>
index !== files.length - 1
return (
<>
{files.map((currentUserFile, index, arr) => {
const { hash, pdfFile, filename, id } = currentUserFile
if (!hash) return
return (
<div
id={pdfFile.file.name}
ref={(el) => (pdfRefs.current[id] = el)}
key={index}
>
<PdfItem
pdfFile={pdfFile}
currentUserMarks={filterByFile(currentUserMarks, filename)}
selectedMark={selectedMark}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
/>
{isNotLastPdfFile(index, arr) && <Divider>File Separator</Divider>}
</div>
)
})}
</>
<div className="files-wrapper">
{files.length > 0 ? (
files.map((currentUserFile, index, arr) => {
const { hash, file, id } = currentUserFile
if (!hash) return
return (
<React.Fragment key={index}>
<div
id={file.name}
className="file-wrapper"
ref={(el) => (pdfRefs.current[id] = el)}
>
<PdfItem
file={file}
currentUserMarks={filterByFile(currentUserMarks, hash)}
selectedMark={selectedMark}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
otherUserMarks={filterMarksByFile(otherUserMarks, hash)}
/>
</div>
{isNotLastPdfFile(index, arr) && <FileDivider />}
</React.Fragment>
)
})
) : (
<LoadingSpinner variant="small" />
)}
</div>
)
}

View File

@ -1,31 +1,13 @@
.imageWrapper {
display: flex;
justify-content: center;
align-items: center;
width: 100%; /* Adjust as needed */
height: 100%; /* Adjust as needed */
overflow: hidden; /* Ensure no overflow */
border: 1px solid #ccc; /* Optional: for visual debugging */
background-color: #e0f7fa; /* Optional: for visual debugging */
}
.image {
max-width: 100%;
max-height: 100%;
object-fit: contain; /* Ensure the image fits within the container */
}
.container {
display: flex;
width: 100%;
flex-direction: column;
}
.pdfView {
.otherUserMarksDisplay {
position: absolute;
z-index: 40;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
gap: 10px;
justify-content: center;
align-items: center;
}

View File

@ -3,34 +3,56 @@ import { getProfileRoute } from '../../routes'
import styles from './styles.module.scss'
import { AvatarIconButton } from '../UserAvatarIconButton'
import { Link } from 'react-router-dom'
import { useProfileMetadata } from '../../hooks/useProfileMetadata'
import { Tooltip } from '@mui/material'
import { getProfileUsername } from '../../utils'
import { TooltipChild } from '../TooltipChild'
interface UserAvatarProps {
name?: string
pubkey: string
image?: string
isNameVisible?: boolean
}
/**
* This component will be used for the displaying username and profile picture.
* Clicking will navigate to the user's profile.
*/
export const UserAvatar = ({ pubkey, name, image }: UserAvatarProps) => {
export const UserAvatar = ({
pubkey,
isNameVisible = false
}: UserAvatarProps) => {
const profile = useProfileMetadata(pubkey)
const name = getProfileUsername(pubkey, profile)
const image = profile?.picture
return (
<Link
to={getProfileRoute(pubkey)}
className={styles.container}
tabIndex={-1}
>
<AvatarIconButton
src={image}
hexKey={pubkey}
aria-label={`account of user ${name || pubkey}`}
color="inherit"
sx={{
padding: 0
}}
/>
{name ? <label className={styles.username}>{name}</label> : null}
<Tooltip
key={pubkey}
title={name}
placement="top"
arrow
disableInteractive
>
<TooltipChild>
<AvatarIconButton
src={image}
hexKey={pubkey}
aria-label={`account of user ${name}`}
color="inherit"
sx={{
padding: 0
}}
/>
</TooltipChild>
</Tooltip>
{isNameVisible && name ? (
<span className={styles.username}>{name}</span>
) : null}
</Link>
)
}

View File

@ -10,4 +10,8 @@
font-weight: 500;
font-size: 14px;
color: var(--text-color);
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}

View File

@ -1,15 +1,12 @@
import { Divider, Tooltip } from '@mui/material'
import { useSigitProfiles } from '../../hooks/useSigitProfiles'
import {
extractFileExtensions,
formatTimestamp,
fromUnixTimestamp,
hexToNpub,
npubToHex,
shorten,
SigitStatus,
SignStatus
} from '../../utils'
import { UserAvatar } from '../UserAvatar'
import { useSigitMeta } from '../../hooks/useSigitMeta'
import { UserAvatarGroup } from '../UserAvatarGroup'
@ -19,16 +16,18 @@ import {
faCalendar,
faCalendarCheck,
faCalendarPlus,
faCheck,
faClock,
faEye,
faFile,
faFileCircleExclamation
} from '@fortawesome/free-solid-svg-icons'
import { getExtensionIconLabel } from '../getExtensionIconLabel'
import { useSelector } from 'react-redux'
import { State } from '../../store/rootReducer'
import { TooltipChild } from '../TooltipChild'
import { useAppSelector } from '../../hooks/store'
import { DisplaySigner } from '../DisplaySigner'
import { Meta } from '../../types'
import { Meta, OpenTimestamp } from '../../types'
import { extractFileExtensions } from '../../utils/file'
import { UserAvatar } from '../UserAvatar'
interface UsersDetailsProps {
meta: Meta
@ -37,6 +36,7 @@ interface UsersDetailsProps {
export const UsersDetails = ({ meta }: UsersDetailsProps) => {
const {
submittedBy,
exportedBy,
signers,
viewers,
fileHashes,
@ -44,45 +44,73 @@ export const UsersDetails = ({ meta }: UsersDetailsProps) => {
createdAt,
completedAt,
parsedSignatureEvents,
signedStatus
signedStatus,
isValid,
id,
timestamps
} = useSigitMeta(meta)
const { usersPubkey } = useSelector((state: State) => state.auth)
const profiles = useSigitProfiles([
...(submittedBy ? [submittedBy] : []),
...signers,
...viewers
])
const { usersPubkey } = useAppSelector((state) => state.auth)
const userCanSign =
typeof usersPubkey !== 'undefined' &&
signers.includes(hexToNpub(usersPubkey))
const ext = extractFileExtensions(Object.keys(fileHashes))
const { extensions, isSame } = extractFileExtensions(Object.keys(fileHashes))
const isTimestampVerified = (
timestamps: OpenTimestamp[],
nostrId: string
): boolean => {
const matched = timestamps.find((t) => t.nostrId === nostrId)
return !!(matched && matched.verification)
}
const getOpenTimestampsInfo = (
timestamps: OpenTimestamp[],
nostrId: string
) => {
if (isTimestampVerified(timestamps, nostrId)) {
return <FontAwesomeIcon className={styles.ticket} icon={faCheck} />
} else {
return <FontAwesomeIcon className={styles.ticket} icon={faClock} />
}
}
const getCompletedOpenTimestampsInfo = (timestamp: OpenTimestamp) => {
if (timestamp.verification) {
return <FontAwesomeIcon className={styles.ticket} icon={faCheck} />
} else {
return <FontAwesomeIcon className={styles.ticket} icon={faClock} />
}
}
const getTimestampTooltipTitle = (label: string, isVerified: boolean) => {
return `${label} / Open Timestamp ${isVerified ? 'Verified' : 'Pending'}`
}
const isUserSignatureTimestampVerified = () => {
if (
userCanSign &&
hexToNpub(usersPubkey) in parsedSignatureEvents &&
timestamps &&
timestamps.length > 0
) {
const nostrId = parsedSignatureEvents[hexToNpub(usersPubkey)].id
return isTimestampVerified(timestamps, nostrId)
}
return false
}
return submittedBy ? (
<div className={styles.container}>
<div className={styles.section}>
<p>Signers</p>
<div className={styles.users}>
{submittedBy &&
(function () {
const profile = profiles[submittedBy]
return (
<Tooltip
title={
profile?.display_name ||
profile?.name ||
shorten(hexToNpub(submittedBy))
}
placement="top"
arrow
disableInteractive
>
<TooltipChild>
<UserAvatar pubkey={submittedBy} image={profile?.picture} />
</TooltipChild>
</Tooltip>
)
})()}
{submittedBy && (
<DisplaySigner
status={isValid ? SignStatus.Signed : SignStatus.Invalid}
pubkey={submittedBy}
/>
)}
{submittedBy && signers.length ? (
<Divider orientation="vertical" flexItem />
@ -91,72 +119,80 @@ export const UsersDetails = ({ meta }: UsersDetailsProps) => {
<UserAvatarGroup max={20}>
{signers.map((signer) => {
const pubkey = npubToHex(signer)!
const profile = profiles[pubkey]
return (
<Tooltip
key={signer}
title={
profile?.display_name || profile?.name || shorten(pubkey)
}
placement="top"
arrow
disableInteractive
>
<TooltipChild>
<DisplaySigner
status={signersStatus[signer]}
profile={profile}
pubkey={pubkey}
/>
</TooltipChild>
</Tooltip>
)
})}
{viewers.map((signer) => {
const pubkey = npubToHex(signer)!
const profile = profiles[pubkey]
return (
<Tooltip
key={signer}
title={
profile?.display_name || profile?.name || shorten(pubkey)
}
placement="top"
arrow
disableInteractive
>
<TooltipChild>
<DisplaySigner
status={SignStatus.Viewer}
profile={profile}
pubkey={pubkey}
/>
</TooltipChild>
</Tooltip>
<DisplaySigner
key={pubkey}
status={signersStatus[signer]}
pubkey={pubkey}
/>
)
})}
</UserAvatarGroup>
</div>
{viewers.length > 0 && (
<>
<p>Viewers</p>
<div className={styles.users}>
<UserAvatarGroup max={20}>
{viewers.map((signer) => {
const pubkey = npubToHex(signer)!
return (
<DisplaySigner
key={pubkey}
status={SignStatus.Viewer}
pubkey={pubkey}
/>
)
})}
</UserAvatarGroup>
</div>
</>
)}
{exportedBy && (
<>
<p>Exported By</p>
<div className={styles.users}>
<UserAvatar pubkey={exportedBy} />
</div>
</>
)}
</div>
<div className={styles.section}>
<p>Details</p>
<Tooltip
title={'Publication date'}
title={getTimestampTooltipTitle(
'Publication date',
!!(timestamps && id && isTimestampVerified(timestamps, id))
)}
placement="top"
arrow
disableInteractive
>
<span className={styles.detailsItem}>
<FontAwesomeIcon icon={faCalendarPlus} />{' '}
{createdAt ? formatTimestamp(createdAt) : <>&mdash;</>}
{createdAt ? formatTimestamp(createdAt) : <>&mdash;</>}{' '}
{timestamps &&
timestamps.length > 0 &&
id &&
getOpenTimestampsInfo(timestamps, id)}
</span>
</Tooltip>
<Tooltip
title={'Completion date'}
title={getTimestampTooltipTitle(
'Completion date',
!!(
signedStatus === SigitStatus.Complete &&
completedAt &&
timestamps &&
timestamps.length > 0 &&
timestamps[timestamps.length - 1].verification
)
)}
placement="top"
arrow
disableInteractive
@ -164,13 +200,26 @@ export const UsersDetails = ({ meta }: UsersDetailsProps) => {
<span className={styles.detailsItem}>
<FontAwesomeIcon icon={faCalendarCheck} />{' '}
{completedAt ? formatTimestamp(completedAt) : <>&mdash;</>}
{signedStatus === SigitStatus.Complete &&
completedAt &&
timestamps &&
timestamps.length > 0 && (
<span className={styles.ticket}>
{getCompletedOpenTimestampsInfo(
timestamps[timestamps.length - 1]
)}
</span>
)}
</span>
</Tooltip>
{/* User signed date */}
{userCanSign ? (
<Tooltip
title={'Your signature date'}
title={getTimestampTooltipTitle(
'Your signature date',
isUserSignatureTimestampVerified()
)}
placement="top"
arrow
disableInteractive
@ -190,20 +239,30 @@ export const UsersDetails = ({ meta }: UsersDetailsProps) => {
) : (
<>&mdash;</>
)}
{hexToNpub(usersPubkey) in parsedSignatureEvents &&
timestamps &&
timestamps.length > 0 && (
<span className={styles.ticket}>
{getOpenTimestampsInfo(
timestamps,
parsedSignatureEvents[hexToNpub(usersPubkey)].id
)}
</span>
)}
</span>
</Tooltip>
) : null}
<span className={styles.detailsItem}>
<FontAwesomeIcon icon={faEye} /> {signedStatus}
</span>
{ext.length > 0 ? (
{extensions.length > 0 ? (
<span className={styles.detailsItem}>
{ext.length > 1 ? (
{!isSame ? (
<>
<FontAwesomeIcon icon={faFile} /> Multiple File Types
</>
) : (
getExtensionIconLabel(ext[0])
getExtensionIconLabel(extensions[0])
)}
</span>
) : (

View File

@ -31,8 +31,6 @@
padding: 5px;
display: flex;
align-items: center;
justify-content: start;
> :first-child {
padding: 5px;
@ -44,3 +42,7 @@
color: white;
}
}
.ticket {
margin-left: auto;
}

View File

@ -0,0 +1,16 @@
import { MarkType } from '../types/drawing'
import { MarkConfigs } from '../types/mark'
import { MarkInputSignature } from './MarkInputs/Signature'
import { MarkInputText } from './MarkInputs/Text'
import { MarkRenderSignature } from './MarkRender/Signature'
export const MARK_TYPE_CONFIG: MarkConfigs = {
[MarkType.TEXT]: {
input: MarkInputText,
render: ({ value }) => <>{value}</>
},
[MarkType.SIGNATURE]: {
input: MarkInputSignature,
render: MarkRenderSignature
}
}

View File

@ -1,6 +1,5 @@
import { Typography } from '@mui/material'
import { useSelector } from 'react-redux'
import { State } from '../store/rootReducer'
import { useAppSelector } from '../hooks/store'
import styles from './username.module.scss'
import { AvatarIconButton } from './UserAvatarIconButton'
@ -16,7 +15,7 @@ type Props = {
* Clicking will open the menu.
*/
const Username = ({ username, avatarContent, handleClick }: Props) => {
const hexKey = useSelector((state: State) => state.auth.usersPubkey)
const hexKey = useAppSelector((state) => state.auth.usersPubkey)
return (
<div className={styles.container}>

View File

@ -1,22 +1,23 @@
import { EventTemplate } from 'nostr-tools'
import { MetadataController, NostrController } from '.'
import { appPrivateRoutes } from '../routes'
import {
setAuthState,
setMetadataEvent,
setRelayMapAction
} from '../store/actions'
import store from '../store/store'
import { SignedEvent } from '../types'
import {
base64DecodeAuthToken,
base64EncodeSignedEvent,
compareObjects,
getAuthToken,
getRelayMap,
getVisitedLink,
saveAuthToken,
compareObjects,
unixNow
} from '../utils'
import { appPrivateRoutes } from '../routes'
import { SignedEvent } from '../types'
export class AuthController {
private nostrController: NostrController
@ -24,13 +25,13 @@ export class AuthController {
constructor() {
this.nostrController = NostrController.getInstance()
this.metadataController = new MetadataController()
this.metadataController = MetadataController.getInstance()
}
/**
* Function will authenticate user by signing an auth event
* which is done by calling the sign() function, where appropriate
* method will be chosen (extension, nsecbunker or keys)
* method will be chosen (extension or keys)
*
* @param pubkey of the user trying to login
* @returns url to redirect if authentication successfull
@ -56,12 +57,15 @@ export class AuthController {
// Nostr uses unix timestamps
const timestamp = unixNow()
const { hostname } = window.location
const { href } = window.location
const authEvent: EventTemplate = {
kind: 27235,
tags: [],
content: `${hostname}-${timestamp}`,
tags: [
['u', href],
['method', 'GET']
],
content: '',
created_at: timestamp
}
@ -75,14 +79,14 @@ export class AuthController {
})
)
const relayMap = await this.nostrController.getRelayMap(pubkey)
const relayMap = await getRelayMap(pubkey)
if (Object.keys(relayMap).length < 1) {
// Navigate user to relays page if relay map is empty
return Promise.resolve(appPrivateRoutes.relays)
}
if (store.getState().auth?.loggedIn) {
if (store.getState().auth.loggedIn) {
if (!compareObjects(store.getState().relays?.map, relayMap.map))
store.dispatch(setRelayMapAction(relayMap.map))
}

View File

@ -1,38 +1,44 @@
import {
Event,
Filter,
SimplePool,
VerifiedEvent,
kinds,
validateEvent,
verifyEvent,
Event,
EventTemplate,
nip19
verifyEvent
} from 'nostr-tools'
import { NostrJoiningBlock, ProfileMetadata, RelaySet } from '../types'
import { NostrController } from '.'
import { toast } from 'react-toastify'
import { queryNip05, unixNow } from '../utils'
import NDK, { NDKEvent, NDKSubscription } from '@nostr-dev-kit/ndk'
import { EventEmitter } from 'tseep'
import { NostrController, relayController } from '.'
import { localCache } from '../services'
import { ProfileMetadata, RelaySet } from '../types'
import {
findRelayListAndUpdateCache,
findRelayListInCache,
getDefaultRelaySet,
getUserRelaySet,
isOlderThanOneWeek
} from '../utils/relays.ts'
isOlderThanOneDay,
unixNow
} from '../utils'
import { DEFAULT_LOOK_UP_RELAY_LIST } from '../utils/const'
export class MetadataController extends EventEmitter {
private static instance: MetadataController
private nostrController: NostrController
private specialMetadataRelay = 'wss://purplepag.es'
private pendingFetches = new Map<string, Promise<Event | null>>() // Track pending fetches
constructor() {
super()
this.nostrController = NostrController.getInstance()
}
public static getInstance(): MetadataController {
if (!MetadataController.instance) {
MetadataController.instance = new MetadataController()
}
return MetadataController.instance
}
/**
* Asynchronously checks for more recent metadata events authored by a specific key.
* If a more recent metadata event is found, it is handled and returned.
@ -45,71 +51,55 @@ export class MetadataController extends EventEmitter {
hexKey: string,
currentEvent: Event | null
): Promise<Event | null> {
// Define the event filter to only include metadata events authored by the given key
const eventFilter: Filter = {
kinds: [kinds.Metadata], // Only metadata events
authors: [hexKey] // Authored by the specified key
// Return the ongoing fetch promise if one exists for the same hexKey
if (this.pendingFetches.has(hexKey)) {
return this.pendingFetches.get(hexKey)!
}
const pool = new SimplePool()
// Define the event filter to only include metadata events authored by the given key
const eventFilter: Filter = {
kinds: [kinds.Metadata],
authors: [hexKey]
}
// Try to get the metadata event from a special relay (wss://purplepag.es)
const metadataEvent = await pool
.get([this.specialMetadataRelay], eventFilter)
const fetchPromise = relayController
.fetchEvent(eventFilter, DEFAULT_LOOK_UP_RELAY_LIST)
.catch((err) => {
console.error(err) // Log any errors
return null // Return null if an error occurs
console.error(err)
return null
})
.finally(() => {
this.pendingFetches.delete(hexKey)
})
// If a valid metadata event is found from the special relay
this.pendingFetches.set(hexKey, fetchPromise)
const metadataEvent = await fetchPromise
if (
metadataEvent &&
validateEvent(metadataEvent) && // Validate the event
verifyEvent(metadataEvent) // Verify the event's authenticity
validateEvent(metadataEvent) &&
verifyEvent(metadataEvent)
) {
// If there's no current event or the new metadata event is more recent
if (
!currentEvent ||
metadataEvent.created_at >= currentEvent.created_at
) {
// Handle the new metadata event
this.handleNewMetadataEvent(metadataEvent)
}
return metadataEvent
}
// If no valid metadata event is found from the special relay, get the most popular relays
const mostPopularRelays = await this.nostrController.getMostPopularRelays()
// todo/implement: if no valid metadata event is found in DEFAULT_LOOK_UP_RELAY_LIST
// try to query user relay list
// Query the most popular relays for metadata events
const events = await pool
.querySync(mostPopularRelays, eventFilter)
.catch((err) => {
console.error(err) // Log any errors
return null // Return null if an error occurs
})
// If events are found from the popular relays
if (events && events.length) {
events.sort((a, b) => b.created_at - a.created_at) // Sort events by creation date (descending)
// Iterate through the events
for (const event of events) {
// If the event is valid, authentic, and more recent than the current event
if (
validateEvent(event) &&
verifyEvent(event) &&
(!currentEvent || event.created_at > currentEvent.created_at)
) {
// Handle the new metadata event
this.handleNewMetadataEvent(event)
return event
}
}
// if current event is null we should cache empty metadata event for provided hexKey
if (!currentEvent) {
const emptyMetadata = this.getEmptyMetadataEvent(hexKey)
this.handleNewMetadataEvent(emptyMetadata as VerifiedEvent)
}
return currentEvent // Return the current event if no newer event is found
return currentEvent
}
/**
@ -134,10 +124,9 @@ export class MetadataController extends EventEmitter {
// If cached metadata is found, check its validity
if (cachedMetadataEvent) {
// Check if the cached metadata is older than one week
if (isOlderThanOneWeek(cachedMetadataEvent.cachedAt)) {
// Check if the cached metadata is older than one day
if (isOlderThanOneDay(cachedMetadataEvent.cachedAt)) {
// If older than one week, find the metadata from relays in background
this.checkForMoreRecentMetadata(hexKey, cachedMetadataEvent.event)
}
@ -165,14 +154,7 @@ export class MetadataController extends EventEmitter {
public findRelayListMetadata = async (hexKey: string): Promise<RelaySet> => {
const relayEvent =
(await findRelayListInCache(hexKey)) ||
(await findRelayListAndUpdateCache(
[this.specialMetadataRelay],
hexKey
)) ||
(await findRelayListAndUpdateCache(
await this.nostrController.getMostPopularRelays(),
hexKey
))
(await findRelayListAndUpdateCache(DEFAULT_LOOK_UP_RELAY_LIST, hexKey))
return relayEvent ? getUserRelaySet(relayEvent.tags) : getDefaultRelaySet()
}
@ -206,152 +188,30 @@ export class MetadataController extends EventEmitter {
await this.nostrController.signEvent(newMetadataEvent)
}
await this.nostrController
.publishEvent(signedMetadataEvent, [this.specialMetadataRelay])
await relayController
.publish(signedMetadataEvent, [this.specialMetadataRelay])
.then((relays) => {
toast.success(`Metadata event published on: ${relays.join('\n')}`)
this.handleNewMetadataEvent(signedMetadataEvent as VerifiedEvent)
if (relays.length) {
toast.success(`Metadata event published on: ${relays.join('\n')}`)
this.handleNewMetadataEvent(signedMetadataEvent as VerifiedEvent)
} else {
toast.error('Could not publish metadata event to any relay!')
}
})
.catch((err) => {
toast.error(err.message)
})
}
public getNostrJoiningBlockNumber = async (
hexKey: string
): Promise<NostrJoiningBlock | null> => {
const relaySet = await this.findRelayListMetadata(hexKey)
const userRelays: string[] = []
// find user's relays
if (relaySet.write.length > 0) {
userRelays.push(...relaySet.write)
} else {
const metadata = await this.findMetadata(hexKey)
if (!metadata) return null
const metadataContent = this.extractProfileMetadataContent(metadata)
if (metadataContent?.nip05) {
const nip05Profile = await queryNip05(metadataContent.nip05)
if (nip05Profile && nip05Profile.pubkey === hexKey) {
userRelays.push(...nip05Profile.relays)
}
}
}
if (userRelays.length === 0) return null
// filter for finding user's first kind 0 event
const eventFilter: Filter = {
kinds: [kinds.Metadata],
authors: [hexKey]
}
const pool = new SimplePool()
// find user's kind 0 events published on user's relays
const events = await pool.querySync(userRelays, eventFilter)
if (events && events.length) {
// sort events by created_at time in ascending order
events.sort((a, b) => a.created_at - b.created_at)
// get first ever event published on user's relays
const event = events[0]
const { created_at } = event
// initialize job request
const jobEventTemplate: EventTemplate = {
content: '',
created_at: unixNow(),
kind: 68001,
tags: [
['i', `${created_at * 1000}`],
['j', 'blockChain-block-number']
]
}
// sign job request event
const jobSignedEvent =
await this.nostrController.signEvent(jobEventTemplate)
const relays = [
'wss://relay.damus.io',
'wss://relay.primal.net',
'wss://relayable.org'
]
// publish job request
await this.nostrController.publishEvent(jobSignedEvent, relays)
console.log('jobSignedEvent :>> ', jobSignedEvent)
const subscribeWithTimeout = (
subscription: NDKSubscription,
timeoutMs: number
): Promise<string> => {
return new Promise((resolve, reject) => {
const eventHandler = (event: NDKEvent) => {
subscription.stop()
resolve(event.content)
}
subscription.on('event', eventHandler)
// Set up a timeout to stop the subscription after a specified time
const timeout = setTimeout(() => {
subscription.stop() // Stop the subscription
reject(new Error('Subscription timed out')) // Reject the promise with a timeout error
}, timeoutMs)
// Handle subscription close event
subscription.on('close', () => clearTimeout(timeout))
})
}
const dvmNDK = new NDK({
explicitRelayUrls: relays
})
await dvmNDK.connect(2000)
// filter for getting DVM job's result
const sub = dvmNDK.subscribe({
kinds: [68002 as number],
'#e': [jobSignedEvent.id],
'#p': [jobSignedEvent.pubkey]
})
// asynchronously get block number from dvm job with 20 seconds timeout
const dvmJobResult = await subscribeWithTimeout(sub, 20000)
const encodedEventPointer = nip19.neventEncode({
id: event.id,
relays: userRelays,
author: event.pubkey,
kind: event.kind
})
return {
block: parseInt(dvmJobResult),
encodedEventPointer
}
}
return null
}
public validate = (event: Event) => validateEvent(event) && verifyEvent(event)
public getEmptyMetadataEvent = (): Event => {
public getEmptyMetadataEvent = (pubkey?: string): Event => {
return {
content: '',
created_at: new Date().valueOf(),
id: '',
kind: 0,
pubkey: '',
pubkey: pubkey || '',
sig: '',
tags: []
}

View File

@ -1,221 +1,24 @@
import NDK, {
NDKEvent,
NDKNip46Signer,
NDKPrivateKeySigner,
NDKSubscription,
NDKUser,
NostrEvent
} from '@nostr-dev-kit/ndk'
import axios from 'axios'
import {
Event,
EventTemplate,
Filter,
Relay,
SimplePool,
UnsignedEvent,
finalizeEvent,
kinds,
nip04,
nip19,
nip44
} from 'nostr-tools'
import { toast } from 'react-toastify'
import { EventTemplate, UnsignedEvent } from 'nostr-tools'
import { WindowNostr } from 'nostr-tools/nip07'
import { EventEmitter } from 'tseep'
import {
setMostPopularRelaysAction,
setRelayConnectionStatusAction,
setRelayInfoAction,
updateNsecbunkerPubkey
} from '../store/actions'
import { AuthState, LoginMethods } from '../store/auth/types'
import store from '../store/store'
import {
RelayConnectionState,
RelayConnectionStatus,
RelayInfoObject,
RelayMap,
RelayReadStats,
RelayStats,
SignedEvent
} from '../types'
import {
compareObjects,
getNsecBunkerDelegatedKey,
unixNow,
verifySignedEvent
} from '../utils'
import { getDefaultRelayMap } from '../utils/relays.ts'
import { SignedEvent } from '../types'
import { LoginMethodContext } from '../services/LoginMethodStrategy/loginMethodContext'
export class NostrController extends EventEmitter {
private static instance: NostrController
private bunkerNDK: NDK | undefined
private remoteSigner: NDKNip46Signer | undefined
private connectedRelays: Relay[] | undefined
private constructor() {
super()
}
private getNostrObject = () => {
// fix: this is not picking up type declaration from src/system/index.d.ts
if (window.nostr) return window.nostr as any
if (window.nostr) return window.nostr as WindowNostr
throw new Error(
`window.nostr object not present. Make sure you have an nostr extension installed/working properly.`
)
}
public nsecBunkerInit = async (relays: string[]) => {
// Don't reinstantiate bunker NDK if exists with same relays
if (
this.bunkerNDK &&
this.bunkerNDK.explicitRelayUrls?.length === relays.length &&
this.bunkerNDK.explicitRelayUrls?.every((relay) => relays.includes(relay))
)
return
this.bunkerNDK = new NDK({
explicitRelayUrls: relays
})
try {
await this.bunkerNDK
.connect(2000)
.then(() => {
console.log(
`Successfully connected to the nsecBunker relays: ${relays.join(
','
)}`
)
})
.catch((err) => {
console.error(
`Error connecting to the nsecBunker relays: ${relays.join(
','
)} ${err}`
)
})
} catch (err) {
console.error(err)
}
}
/**
* Creates nSecBunker signer instance for the given npub
* Or if npub omitted it will return existing signer
* If neither, error will be thrown
* @param npub nPub / public key in hex format
* @returns nsecBunker Signer instance
*/
public createNsecBunkerSigner = async (
npub: string | undefined
): Promise<NDKNip46Signer> => {
const nsecBunkerDelegatedKey = getNsecBunkerDelegatedKey()
return new Promise((resolve, reject) => {
if (!nsecBunkerDelegatedKey) {
reject('nsecBunker delegated key is not found in the browser.')
return
}
const localSigner = new NDKPrivateKeySigner(nsecBunkerDelegatedKey)
if (!npub) {
if (this.remoteSigner) resolve(this.remoteSigner)
const npubFromStorage = (store.getState().auth as AuthState)
.nsecBunkerPubkey
if (npubFromStorage) {
npub = npubFromStorage
} else {
reject(
'No signer instance present, no npub provided by user or found in the browser.'
)
return
}
} else {
store.dispatch(updateNsecbunkerPubkey(npub))
}
// Pubkey of a key pair stored in nsecbunker that will be used to sign event with
const appPubkeyOrToken = npub.includes('npub')
? npub
: nip19.npubEncode(npub)
/**
* When creating and NDK instance we create new connection to the relay
* To prevent too much connections and hitting rate limits, if npub against which we sign
* we will reuse existing instance. Otherwise we will create new NDK and signer instance.
*/
if (!this.remoteSigner || this.remoteSigner?.remotePubkey !== npub) {
this.remoteSigner = new NDKNip46Signer(
this.bunkerNDK!,
appPubkeyOrToken,
localSigner
)
}
/**
* when nsecbunker-delegated-key is regenerated we have to reinitialize the remote signer
*/
if (this.remoteSigner.localSigner !== localSigner) {
this.remoteSigner = new NDKNip46Signer(
this.bunkerNDK!,
appPubkeyOrToken,
localSigner
)
}
resolve(this.remoteSigner)
})
}
/**
* Signs the nostr event and returns the sig and id or full raw nostr event
* @param npub stored in nsecBunker to sign with
* @param event to be signed
* @param returnFullEvent whether to return full raw nostr event or just SIG and ID values
*/
public signWithNsecBunker = async (
npub: string | undefined,
event: NostrEvent,
returnFullEvent = true
): Promise<{ id: string; sig: string } | NostrEvent> => {
return new Promise((resolve, reject) => {
this.createNsecBunkerSigner(npub)
.then(async (signer) => {
const ndkEvent = new NDKEvent(undefined, event)
const timeout = setTimeout(() => {
reject('Timeout occurred while waiting for event signing')
}, 60000) // 60000 ms (1 min) = 1000 * 60
await ndkEvent.sign(signer).catch((err) => {
clearTimeout(timeout)
reject(err)
return
})
clearTimeout(timeout)
if (returnFullEvent) {
resolve(ndkEvent.rawEvent())
} else {
resolve({
id: ndkEvent.id,
sig: ndkEvent.sig!
})
}
})
.catch((err) => {
reject(err)
})
})
}
public static getInstance(): NostrController {
if (!NostrController.instance) {
NostrController.instance = new NostrController()
@ -223,98 +26,6 @@ export class NostrController extends EventEmitter {
return NostrController.instance
}
/**
* Function will publish provided event to the provided relays
*
* @param event - The event to publish.
* @param relays - An array of relay URLs to publish the event to.
* @returns A promise that resolves to an array of relays where the event was successfully published.
*/
publishEvent = async (event: Event, relays: string[]) => {
const simplePool = new SimplePool()
// Publish the event to all relays
const promises = simplePool.publish(relays, event)
// Use Promise.race to wait for the first successful publish
const firstSuccessfulPublish = await Promise.race(
promises.map((promise, index) =>
promise.then(() => relays[index]).catch(() => null)
)
)
if (!firstSuccessfulPublish) {
// If no publish was successful, collect the reasons for failures
const failedPublishes: unknown[] = []
const fallbackRejectionReason =
'Attempt to publish an event has been rejected with unknown reason.'
const results = await Promise.allSettled(promises)
results.forEach((res, index) => {
if (res.status === 'rejected') {
failedPublishes.push({
relay: relays[index],
error: res.reason
? res.reason.message || fallbackRejectionReason
: fallbackRejectionReason
})
}
})
throw failedPublishes
}
// Continue publishing to other relays in the background
promises.forEach((promise, index) => {
promise.catch((err) => {
console.log(`Failed to publish to ${relays[index]}`, err)
})
})
return [firstSuccessfulPublish]
}
/**
* Asynchronously retrieves an event from a set of relays based on a provided filter.
* If no relays are specified, it defaults to using connected relays.
*
* @param {Filter} filter - The filter criteria to find the event.
* @param {string[]} [relays] - An optional array of relay URLs to search for the event.
* @returns {Promise<Event | null>} - Returns a promise that resolves to the found event or null if not found.
*/
getEvent = async (
filter: Filter,
relays?: string[]
): Promise<Event | null> => {
// If no relays are provided or the provided array is empty, use connected relays if available.
if (!relays || relays.length === 0) {
relays = this.connectedRelays
? this.connectedRelays.map((relay) => relay.url)
: []
}
// If still no relays are available, reject the promise with an error message.
if (relays.length === 0) {
return Promise.reject('Provide some relays to find the event')
}
// Create a new instance of SimplePool to handle the relay connections and event retrieval.
const pool = new SimplePool()
// Attempt to retrieve the event from the specified relays using the filter criteria.
const event = await pool.get(relays, filter).catch((err) => {
// Log any errors that occur during the event retrieval process.
console.log('An error occurred in finding the event', err)
// Show an error toast notification to the user.
toast.error('An error occurred in finding the event')
// Return null if an error occurs, indicating that no event was found.
return null
})
// Return the found event, or null if an error occurred.
return event
}
/**
* Encrypts the given content for the specified receiver using NIP-44 encryption.
*
@ -325,60 +36,11 @@ export class NostrController extends EventEmitter {
*/
nip44Encrypt = async (receiver: string, content: string) => {
// Retrieve the current login method from the application's redux state.
const loginMethod = (store.getState().auth as AuthState).loginMethod
const loginMethod = store.getState().auth.loginMethod
const context = new LoginMethodContext(loginMethod)
// Handle encryption when the login method is via an extension.
if (loginMethod === LoginMethods.extension) {
const nostr = this.getNostrObject()
// Check if the nostr object supports NIP-44 encryption.
if (!nostr.nip44) {
throw new Error(
`Your nostr extension does not support nip44 encryption & decryption`
)
}
// Encrypt the content using NIP-44 provided by the nostr extension.
const encrypted = await nostr.nip44.encrypt(receiver, content)
return encrypted as string
}
// Handle encryption when the login method is via a private key.
if (loginMethod === LoginMethods.privateKey) {
const keys = (store.getState().auth as AuthState).keyPair
// Check if the private and public key pair is available.
if (!keys) {
throw new Error(
`Login method is ${LoginMethods.privateKey} but private & public key pair is not found.`
)
}
// Decode the private key.
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
// Generate the conversation key using NIP-44 utilities.
const nip44ConversationKey = nip44.v2.utils.getConversationKey(
privateKey,
receiver
)
// Encrypt the content using the generated conversation key.
const encrypted = nip44.v2.encrypt(content, nip44ConversationKey)
return encrypted
}
// Throw an error if the login method is nsecBunker (not supported).
if (loginMethod === LoginMethods.nsecBunker) {
throw new Error(
`nip44 encryption is not yet supported for login method '${LoginMethods.nsecBunker}'`
)
}
// Throw an error if the login method is undefined or unsupported.
throw new Error('Login method is undefined')
return await context.nip44Encrypt(receiver, content)
}
/**
@ -391,180 +53,33 @@ export class NostrController extends EventEmitter {
*/
nip44Decrypt = async (sender: string, content: string) => {
// Retrieve the current login method from the application's redux state.
const loginMethod = (store.getState().auth as AuthState).loginMethod
const loginMethod = store.getState().auth.loginMethod
const context = new LoginMethodContext(loginMethod)
// Handle decryption when the login method is via an extension.
if (loginMethod === LoginMethods.extension) {
const nostr = this.getNostrObject()
// Check if the nostr object supports NIP-44 decryption.
if (!nostr.nip44) {
throw new Error(
`Your nostr extension does not support nip44 encryption & decryption`
)
}
// Decrypt the content using NIP-44 provided by the nostr extension.
const decrypted = await nostr.nip44.decrypt(sender, content)
return decrypted as string
}
// Handle decryption when the login method is via a private key.
if (loginMethod === LoginMethods.privateKey) {
const keys = (store.getState().auth as AuthState).keyPair
// Check if the private and public key pair is available.
if (!keys) {
throw new Error(
`Login method is ${LoginMethods.privateKey} but private & public key pair is not found.`
)
}
// Decode the private key.
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
// Generate the conversation key using NIP-44 utilities.
const nip44ConversationKey = nip44.v2.utils.getConversationKey(
privateKey,
sender
)
// Decrypt the content using the generated conversation key.
const decrypted = nip44.v2.decrypt(content, nip44ConversationKey)
return decrypted
}
// Throw an error if the login method is nsecBunker (not supported).
if (loginMethod === LoginMethods.nsecBunker) {
throw new Error(
`nip44 decryption is not yet supported for login method '${LoginMethods.nsecBunker}'`
)
}
// Throw an error if the login method is undefined or unsupported.
throw new Error('Login method is undefined')
// Handle decryption
return await context.nip44Decrypt(sender, content)
}
/**
* Signs an event with private key (if it is present in local storage) or
* with browser extension (if it is present) or
* with nSecBunker instance.
* with browser extension (if it is present)
* @param event - unsigned nostr event.
* @returns - a promised that is resolved with signed nostr event.
*/
signEvent = async (
event: UnsignedEvent | EventTemplate
): Promise<SignedEvent> => {
const loginMethod = (store.getState().auth as AuthState).loginMethod
const loginMethod = store.getState().auth.loginMethod
const context = new LoginMethodContext(loginMethod)
if (!loginMethod) {
return Promise.reject('No login method found in the browser storage')
}
if (loginMethod === LoginMethods.nsecBunker) {
// Check if nsecBunker is available
if (!this.bunkerNDK) {
return Promise.reject(
`Login method is ${loginMethod} but bunkerNDK is not created`
)
}
if (!this.remoteSigner) {
return Promise.reject(
`Login method is ${loginMethod} but bunkerNDK is not created`
)
}
const signedEvent = await this.signWithNsecBunker(
'',
event as NostrEvent
).catch((err) => {
throw err
})
return Promise.resolve(signedEvent as SignedEvent)
} else if (loginMethod === LoginMethods.privateKey) {
const keys = (store.getState().auth as AuthState).keyPair
if (!keys) {
return Promise.reject(
`Login method is ${loginMethod}, but keys are not found`
)
}
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
const signedEvent = finalizeEvent(event, privateKey)
verifySignedEvent(signedEvent)
return Promise.resolve(signedEvent)
} else if (loginMethod === LoginMethods.extension) {
const nostr = this.getNostrObject()
return (await nostr
.signEvent(event as NostrEvent)
.catch((err: unknown) => {
console.log('Error while signing event: ', err)
throw err
})) as Event
} else {
return Promise.reject(
`We could not sign the event, none of the signing methods are available`
)
}
return await context.signEvent(event)
}
nip04Encrypt = async (receiver: string, content: string): Promise<string> => {
const loginMethod = (store.getState().auth as AuthState).loginMethod
const loginMethod = store.getState().auth.loginMethod
const context = new LoginMethodContext(loginMethod)
if (loginMethod === LoginMethods.extension) {
const nostr = this.getNostrObject()
if (!nostr.nip04) {
throw new Error(
`Your nostr extension does not support nip04 encryption & decryption`
)
}
const encrypted = await nostr.nip04.encrypt(receiver, content)
return encrypted
}
if (loginMethod === LoginMethods.privateKey) {
const keys = (store.getState().auth as AuthState).keyPair
if (!keys) {
throw new Error(
`Login method is ${LoginMethods.privateKey} but private & public key pair is not found.`
)
}
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
const encrypted = await nip04.encrypt(privateKey, receiver, content)
return encrypted
}
if (loginMethod === LoginMethods.nsecBunker) {
const user = new NDKUser({ pubkey: receiver })
this.remoteSigner?.on('authUrl', (authUrl) => {
this.emit('nsecbunker-auth', authUrl)
})
if (!this.remoteSigner) throw new Error('Remote signer is undefined.')
const encrypted = await this.remoteSigner.encrypt(user, content)
return encrypted
}
throw new Error('Login method is undefined')
return await context.nip04Encrypt(receiver, content)
}
/**
@ -575,51 +90,10 @@ export class NostrController extends EventEmitter {
* @returns A promise that resolves to the decrypted content.
*/
nip04Decrypt = async (sender: string, content: string): Promise<string> => {
const loginMethod = (store.getState().auth as AuthState).loginMethod
const loginMethod = store.getState().auth.loginMethod
const context = new LoginMethodContext(loginMethod)
if (loginMethod === LoginMethods.extension) {
const nostr = this.getNostrObject()
if (!nostr.nip04) {
throw new Error(
`Your nostr extension does not support nip04 encryption & decryption`
)
}
const decrypted = await nostr.nip04.decrypt(sender, content)
return decrypted
}
if (loginMethod === LoginMethods.privateKey) {
const keys = (store.getState().auth as AuthState).keyPair
if (!keys) {
throw new Error(
`Login method is ${LoginMethods.privateKey} but private & public key pair is not found.`
)
}
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
const decrypted = await nip04.decrypt(privateKey, sender, content)
return decrypted
}
if (loginMethod === LoginMethods.nsecBunker) {
const user = new NDKUser({ pubkey: sender })
this.remoteSigner?.on('authUrl', (authUrl) => {
this.emit('nsecbunker-auth', authUrl)
})
if (!this.remoteSigner) throw new Error('Remote signer is undefined.')
const decrypted = await this.remoteSigner.decrypt(user, content)
return decrypted
}
throw new Error('Login method is undefined')
return await context.nip04Decrypt(sender, content)
}
/**
@ -642,367 +116,4 @@ export class NostrController extends EventEmitter {
return Promise.resolve(pubKey)
}
/**
* Generates NDK Private Signer
* @returns nSecBunker delegated key
*/
generateDelegatedKey = (): string => {
return NDKPrivateKeySigner.generate().privateKey!
}
/**
* Provides relay map.
* @param npub - user's npub
* @returns - promise that resolves into relay map and a timestamp when it has been updated.
*/
getRelayMap = async (
npub: string
): Promise<{ map: RelayMap; mapUpdated?: number }> => {
const mostPopularRelays = await this.getMostPopularRelays()
const pool = new SimplePool()
// More info about this kind of event available https://github.com/nostr-protocol/nips/blob/master/65.md
const eventFilter: Filter = {
kinds: [kinds.RelayList],
authors: [npub]
}
const event = await pool
.get(mostPopularRelays, eventFilter)
.catch((err) => {
return Promise.reject(err)
})
if (event) {
// Handle founded 10002 event
const relaysMap: RelayMap = {}
// 'r' stands for 'relay'
const relayTags = event.tags.filter((tag) => tag[0] === 'r')
relayTags.forEach((tag) => {
const uri = tag[1]
const relayType = tag[2]
// if 3rd element of relay tag is undefined, relay is WRITE and READ
relaysMap[uri] = {
write: relayType ? relayType === 'write' : true,
read: relayType ? relayType === 'read' : true
}
})
this.getRelayInfo(Object.keys(relaysMap))
this.connectToRelays(Object.keys(relaysMap))
return Promise.resolve({ map: relaysMap, mapUpdated: event.created_at })
} else {
return Promise.resolve({ map: getDefaultRelayMap() })
}
}
/**
* Publishes relay map.
* @param relayMap - relay map.
* @param npub - user's npub.
* @param extraRelaysToPublish - optional relays to publish relay map.
* @returns - promise that resolves into a string representing publishing result.
*/
publishRelayMap = async (
relayMap: RelayMap,
npub: string,
extraRelaysToPublish?: string[]
): Promise<string> => {
const timestamp = unixNow()
const relayURIs = Object.keys(relayMap)
// More info about this kind of event available https://github.com/nostr-protocol/nips/blob/master/65.md
const tags: string[][] = relayURIs.map((relayURI) =>
[
'r',
relayURI,
relayMap[relayURI].read && relayMap[relayURI].write
? ''
: relayMap[relayURI].write
? 'write'
: 'read'
].filter((value) => value !== '')
)
const newRelayMapEvent: UnsignedEvent = {
kind: kinds.RelayList,
tags,
content: '',
pubkey: npub,
created_at: timestamp
}
const signedEvent = await this.signEvent(newRelayMapEvent)
let relaysToPublish = relayURIs
// Add extra relays if provided
if (extraRelaysToPublish) {
relaysToPublish = [...relaysToPublish, ...extraRelaysToPublish]
}
// If relay map is empty, use most popular relay URIs
if (!relaysToPublish.length) {
relaysToPublish = await this.getMostPopularRelays()
}
const publishResult = await this.publishEvent(signedEvent, relaysToPublish)
if (publishResult && publishResult.length) {
return Promise.resolve(
`Relay Map published on: ${publishResult.join('\n')}`
)
}
return Promise.reject('Publishing updated relay map was unsuccessful.')
}
/**
* Provides most popular relays.
* @param numberOfTopRelays - number representing how many most popular relays to provide
* @returns - promise that resolves into an array of most popular relays
*/
getMostPopularRelays = async (
numberOfTopRelays: number = 30
): Promise<string[]> => {
const mostPopularRelaysState = store.getState().relays?.mostPopular
// return most popular relays from app state if present
if (mostPopularRelaysState) return mostPopularRelaysState
// relays in env
const { VITE_MOST_POPULAR_RELAYS } = import.meta.env
const hardcodedPopularRelays = (VITE_MOST_POPULAR_RELAYS || '').split(' ')
const url = `https://stats.nostr.band/stats_api?method=stats`
const response = await axios.get<RelayStats>(url).catch(() => undefined)
if (!response) {
return hardcodedPopularRelays //return hardcoded relay list
}
const data = response.data
if (!data) {
return hardcodedPopularRelays //return hardcoded relay list
}
const apiTopRelays = data.relay_stats.user_picks.read_relays
.slice(0, numberOfTopRelays)
.map((relay: RelayReadStats) => relay.d)
if (!apiTopRelays.length) {
return Promise.reject(`Couldn't fetch popular relays.`)
}
if (store.getState().auth?.loggedIn) {
store.dispatch(setMostPopularRelaysAction(apiTopRelays))
}
return apiTopRelays
}
/**
* Sets information about relays into relays.info app state.
* @param relayURIs - relay URIs to get information about
*/
getRelayInfo = async (relayURIs: string[]) => {
// initialize job request
const jobEventTemplate: EventTemplate = {
content: '',
created_at: unixNow(),
kind: 68001,
tags: [
['i', `${JSON.stringify(relayURIs)}`],
['j', 'relay-info']
]
}
// sign job request event
const jobSignedEvent = await this.signEvent(jobEventTemplate)
const relays = [
'wss://relay.damus.io',
'wss://relay.primal.net',
'wss://relayable.org'
]
// publish job request
await this.publishEvent(jobSignedEvent, relays)
console.log('jobSignedEvent :>> ', jobSignedEvent)
const subscribeWithTimeout = (
subscription: NDKSubscription,
timeoutMs: number
): Promise<string> => {
return new Promise((resolve, reject) => {
const eventHandler = (event: NDKEvent) => {
subscription.stop()
resolve(event.content)
}
subscription.on('event', eventHandler)
// Set up a timeout to stop the subscription after a specified time
const timeout = setTimeout(() => {
subscription.stop() // Stop the subscription
reject(new Error('Subscription timed out')) // Reject the promise with a timeout error
}, timeoutMs)
// Handle subscription close event
subscription.on('close', () => clearTimeout(timeout))
})
}
const dvmNDK = new NDK({
explicitRelayUrls: relays
})
await dvmNDK.connect(2000)
// filter for getting DVM job's result
const sub = dvmNDK.subscribe({
kinds: [68002 as number],
'#e': [jobSignedEvent.id],
'#p': [jobSignedEvent.pubkey]
})
// asynchronously get block number from dvm job with 20 seconds timeout
const dvmJobResult = await subscribeWithTimeout(sub, 20000)
if (!dvmJobResult) {
return Promise.reject(`Relay(s) information wasn't received`)
}
let relaysInfo: RelayInfoObject
try {
relaysInfo = JSON.parse(dvmJobResult)
} catch (error) {
return Promise.reject(`Invalid relay(s) information.`)
}
if (
relaysInfo &&
!compareObjects(store.getState().relays?.info, relaysInfo)
) {
store.dispatch(setRelayInfoAction(relaysInfo))
}
}
/**
* Establishes connection to relays.
* @param relayURIs - an array of relay URIs
* @returns - promise that resolves into an array of connections
*/
connectToRelays = async (relayURIs: string[]) => {
// Copy of relay connection status
const relayConnectionsStatus: RelayConnectionStatus = JSON.parse(
JSON.stringify(store.getState().relays?.connectionStatus || {})
)
const connectedRelayURLs = this.connectedRelays
? this.connectedRelays.map((relay) => relay.url)
: []
// Check if connections already established
if (compareObjects(connectedRelayURLs, relayURIs)) {
return
}
const connections = relayURIs
.filter((relayURI) => !connectedRelayURLs.includes(relayURI))
.map((relayURI) =>
Relay.connect(relayURI)
.then((relay) => {
// put connection status into relayConnectionsStatus object
relayConnectionsStatus[relayURI] = relay.connected
? RelayConnectionState.Connected
: RelayConnectionState.NotConnected
return relay
})
.catch(() => {
relayConnectionsStatus[relayURI] = RelayConnectionState.NotConnected
})
)
const connected = await Promise.all(connections)
// put connected relays into connectedRelays private property, so it can be closed later
this.connectedRelays = connected.filter(
(relay) => relay instanceof Relay && relay.connected
) as Relay[]
if (Object.keys(relayConnectionsStatus)) {
if (
!compareObjects(
store.getState().relays?.connectionStatus,
relayConnectionsStatus
)
) {
store.dispatch(setRelayConnectionStatusAction(relayConnectionsStatus))
}
}
return Promise.resolve(relayConnectionsStatus)
}
/**
* Disconnects from relays.
* @param relayURIs - array of relay URIs to disconnect from
*/
disconnectFromRelays = async (relayURIs: string[]) => {
const connectedRelayURLs = this.connectedRelays
? this.connectedRelays.map((relay) => relay.url)
: []
relayURIs
.filter((relayURI) => connectedRelayURLs.includes(relayURI))
.forEach((relayURI) => {
if (this.connectedRelays) {
const relay = this.connectedRelays.find(
(relay) => relay.url === relayURI
)
if (relay) {
// close relay connection
relay.close()
// remove relay from connectedRelays property
this.connectedRelays = this.connectedRelays.filter(
(relay) => relay.url !== relayURI
)
}
}
})
if (store.getState().relays?.connectionStatus) {
const connectionStatus = JSON.parse(
JSON.stringify(store.getState().relays?.connectionStatus)
)
relayURIs.forEach((relay) => {
delete connectionStatus[relay]
})
if (
!compareObjects(
store.getState().relays?.connectionStatus,
connectionStatus
)
) {
// Update app state
store.dispatch(setRelayConnectionStatusAction(connectionStatus))
}
}
}
}

View File

@ -0,0 +1,306 @@
import { Event, Filter, Relay } from 'nostr-tools'
import {
settleAllFullfilfedPromises,
normalizeWebSocketURL,
timeout
} from '../utils'
import { SIGIT_RELAY } from '../utils/const'
/**
* Singleton class to manage relay operations.
*/
export class RelayController {
private static instance: RelayController
private pendingConnections = new Map<string, Promise<Relay | null>>() // Track pending connections
public connectedRelays = new Map<string, Relay>()
private constructor() {}
/**
* Provides the singleton instance of RelayController.
*
* @returns The singleton instance of RelayController.
*/
public static getInstance(): RelayController {
if (!RelayController.instance) {
RelayController.instance = new RelayController()
}
return RelayController.instance
}
/**
* Connects to a relay server if not already connected.
*
* This method checks if a relay with the given URL is already in the list of connected relays.
* If it is not connected, it attempts to establish a new connection.
* On successful connection, the relay is added to the list of connected relays and returned.
* If the connection fails, an error is logged and `null` is returned.
*
* @param relayUrl - The URL of the relay server to connect to.
* @returns A promise that resolves to the connected relay object if successful, or `null` if the connection fails.
*/
public connectRelay = async (relayUrl: string): Promise<Relay | null> => {
const normalizedWebSocketURL = normalizeWebSocketURL(relayUrl)
const relay = this.connectedRelays.get(normalizedWebSocketURL)
if (relay) {
if (relay.connected) return relay
// If relay is found in connectedRelay map but not connected,
// remove it from map and call connectRelay method again
this.connectedRelays.delete(relayUrl)
return this.connectRelay(relayUrl)
}
// Check if there's already a pending connection for this relay URL
if (this.pendingConnections.has(relayUrl)) {
// Return the existing promise to avoid making another connection
return this.pendingConnections.get(relayUrl)!
}
// Create a new connection promise and store it in pendingConnections
const connectionPromise = Relay.connect(relayUrl)
.then((relay) => {
if (relay.connected) {
// Add the newly connected relay to the connected relays map
this.connectedRelays.set(relayUrl, relay)
// Return the newly connected relay
return relay
}
return null
})
.catch((err) => {
// Log an error message if the connection fails
console.error(`Relay connection failed: ${relayUrl}`, err)
// Return null to indicate connection failure
return null
})
.finally(() => {
// Remove the connection from pendingConnections once it settles
this.pendingConnections.delete(relayUrl)
})
this.pendingConnections.set(relayUrl, connectionPromise)
return connectionPromise
}
/**
* Asynchronously retrieves multiple event from a set of relays based on a provided filter.
* If no relays are specified, it defaults to using connected relays.
*
* @param filter - The filter criteria to find the event.
* @param relays - An optional array of relay URLs to search for the event.
* @returns Returns a promise that resolves with an array of events.
*/
fetchEvents = async (
filter: Filter,
relayUrls: string[] = []
): Promise<Event[]> => {
if (!relayUrls.includes(SIGIT_RELAY)) {
/**
* NOTE: To avoid side-effects on external relayUrls array passed as argument
* re-assigned relayUrls with added sigit relay instead of just appending to same array
*/
relayUrls = [...relayUrls, SIGIT_RELAY] // Add app relay to relays array if not exists already
}
// connect to all specified relays
const relays = await settleAllFullfilfedPromises(
relayUrls,
this.connectRelay
)
// Check if any relays are connected
if (relays.length === 0) {
throw new Error('No relay is connected to fetch events!')
}
const events: Event[] = []
const eventIds = new Set<string>() // To keep track of event IDs and avoid duplicates
// Create a promise for each relay subscription
const subPromises = relays.map((relay) => {
return new Promise<void>((resolve) => {
if (!relay.connected) {
console.log(`${relay.url} : Not connected!`, 'Skipping subscription')
return resolve()
}
// Subscribe to the relay with the specified filter
const sub = relay.subscribe([filter], {
// Handle incoming events
onevent: (e) => {
// Add the event to the array if it's not a duplicate
if (!eventIds.has(e.id)) {
eventIds.add(e.id) // Record the event ID
events.push(e) // Add the event to the array
}
},
// Handle the End-Of-Stream (EOSE) message
oneose: () => {
sub.close() // Close the subscription
resolve() // Resolve the promise when EOSE is received
}
})
// add a 30 sec of timeout to subscription
setTimeout(() => {
if (!sub.closed) {
sub.close()
resolve()
}
}, 30 * 1000)
})
})
// Wait for all subscriptions to complete
await Promise.allSettled(subPromises)
// It is possible that different relays will send different events and events array may contain more events then specified limit in filter
// To fix this issue we'll first sort these events and then return only limited events
if (filter.limit) {
// Sort events by creation date in descending order
events.sort((a, b) => b.created_at - a.created_at)
return events.slice(0, filter.limit)
}
return events
}
/**
* Asynchronously retrieves an event from a set of relays based on a provided filter.
* If no relays are specified, it defaults to using connected relays.
*
* @param filter - The filter criteria to find the event.
* @param relays - An optional array of relay URLs to search for the event.
* @returns Returns a promise that resolves to the found event or null if not found.
*/
fetchEvent = async (
filter: Filter,
relays: string[] = []
): Promise<Event | null> => {
const events = await this.fetchEvents(filter, relays)
// Sort events by creation date in descending order
events.sort((a, b) => b.created_at - a.created_at)
// Return the most recent event, or null if no events were received
return events[0] || null
}
/**
* Subscribes to events from multiple relays.
*
* This method connects to the specified relay URLs and subscribes to events
* using the provided filter. It handles incoming events through the given
* `eventHandler` callback and manages the subscription lifecycle.
*
* @param filter - The filter criteria to apply when subscribing to events.
* @param relayUrls - An optional array of relay URLs to connect to. The default relay URL (`SIGIT_RELAY`) is added automatically.
* @param eventHandler - A callback function to handle incoming events. It receives an `Event` object.
*
*/
subscribeForEvents = async (
filter: Filter,
relayUrls: string[] = [],
eventHandler: (event: Event) => void
) => {
if (!relayUrls.includes(SIGIT_RELAY)) {
/**
* NOTE: To avoid side-effects on external relayUrls array passed as argument
* re-assigned relayUrls with added sigit relay instead of just appending to same array
*/
relayUrls = [...relayUrls, SIGIT_RELAY] // Add app relay to relays array if not exists already
}
// connect to all specified relays
const relays = await settleAllFullfilfedPromises(
relayUrls,
this.connectRelay
)
// Check if any relays are connected
if (relays.length === 0) {
throw new Error('No relay is connected to fetch events!')
}
const processedEvents: string[] = [] // To keep track of processed events
// Create a promise for each relay subscription
const subPromises = relays.map((relay) => {
return new Promise<void>((resolve) => {
// Subscribe to the relay with the specified filter
const sub = relay.subscribe([filter], {
// Handle incoming events
onevent: (e) => {
// Process event only if it hasn't been processed before
if (!processedEvents.includes(e.id)) {
processedEvents.push(e.id)
eventHandler(e) // Call the event handler with the event
}
},
// Handle the End-Of-Stream (EOSE) message
oneose: () => {
sub.close() // Close the subscription
resolve() // Resolve the promise when EOSE is received
}
})
})
})
// Wait for all subscriptions to complete
await Promise.allSettled(subPromises)
}
publish = async (
event: Event,
relayUrls: string[] = []
): Promise<string[]> => {
if (!relayUrls.includes(SIGIT_RELAY)) {
/**
* NOTE: To avoid side-effects on external relayUrls array passed as argument
* re-assigned relayUrls with added sigit relay instead of just appending to same array
*/
relayUrls = [...relayUrls, SIGIT_RELAY] // Add app relay to relays array if not exists already
}
// connect to all specified relays
const relays = await settleAllFullfilfedPromises(
relayUrls,
this.connectRelay
)
// Check if any relays are connected
if (relays.length === 0) {
throw new Error('No relay is connected to publish event!')
}
const publishedOnRelays: string[] = [] // List to track which relays successfully published the event
// Create a promise for publishing the event to each connected relay
const publishPromises = relays.map(async (relay) => {
try {
await Promise.race([
relay.publish(event), // Publish the event to the relay
timeout(20 * 1000) // Set a timeout to handle cases where publishing takes too long
])
publishedOnRelays.push(relay.url) // Add the relay URL to the list of successfully published relays
} catch (err) {
console.error(`Failed to publish event on relay: ${relay.url}`, err)
}
})
// Wait for all publish operations to complete (either fulfilled or rejected)
await Promise.allSettled(publishPromises)
// Return the list of relay URLs where the event was published
return publishedOnRelays
}
}
export const relayController = RelayController.getInstance()

View File

@ -1,3 +1,4 @@
export * from './AuthController'
export * from './MetadataController'
export * from './NostrController'
export * from './RelayController'

View File

@ -1 +1,2 @@
export * from './store'
export * from './useDidMount'

12
src/hooks/useDidMount.ts Normal file
View File

@ -0,0 +1,12 @@
import { useRef, useEffect } from 'react'
export const useDidMount = (callback: () => void) => {
const didMount = useRef<boolean>(false)
useEffect(() => {
if (callback && !didMount.current) {
didMount.current = true
callback()
}
})
}

26
src/hooks/useLogout.tsx Normal file
View File

@ -0,0 +1,26 @@
import { logout as nostrLogout } from 'nostr-login'
import { clear } from '../utils/localStorage'
import { userLogOutAction } from '../store/actions'
import { LoginMethod } from '../store/auth/types'
import { useAppDispatch, useAppSelector } from './store'
import { useCallback } from 'react'
export const useLogout = () => {
const loginMethod = useAppSelector((state) => state.auth?.loginMethod)
const dispatch = useAppDispatch()
const logout = useCallback(() => {
// Log out of the nostr-login
if (loginMethod === LoginMethod.nostrLogin) {
nostrLogout()
}
// Reset redux state with the logout
dispatch(userLogOutAction())
// Clear the local storage states
clear()
}, [dispatch, loginMethod])
return logout
}

View File

@ -0,0 +1,46 @@
import { useEffect, useState } from 'react'
import { ProfileMetadata } from '../types/profile'
import { MetadataController } from '../controllers/MetadataController'
import { Event, kinds } from 'nostr-tools'
export const useProfileMetadata = (pubkey: string) => {
const [profileMetadata, setProfileMetadata] = useState<ProfileMetadata>()
useEffect(() => {
const metadataController = MetadataController.getInstance()
const handleMetadataEvent = (event: Event) => {
const metadataContent =
metadataController.extractProfileMetadataContent(event)
if (metadataContent) {
setProfileMetadata(metadataContent)
}
}
if (pubkey) {
metadataController.on(pubkey, (kind: number, event: Event) => {
if (kind === kinds.Metadata) {
handleMetadataEvent(event)
}
})
metadataController
.findMetadata(pubkey)
.then((metadataEvent) => {
if (metadataEvent) handleMetadataEvent(metadataEvent)
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${pubkey}`,
err
)
})
}
return () => {
metadataController.off(pubkey, handleMetadataEvent)
}
}, [pubkey])
return profileMetadata
}

46
src/hooks/useScale.tsx Normal file
View File

@ -0,0 +1,46 @@
import { useEffect, useState } from 'react'
import { singletonHook } from 'react-singleton-hook'
import { getInnerContentWidth } from '../utils/pdf'
const noScaleInit = {
to: (_: number, v: number) => v,
from: (_: number, v: number) => v
}
const useScaleImpl = () => {
const [width, setWidth] = useState(getInnerContentWidth())
// Get the scale based on the original width
const scale = (originalWidth: number) => {
return width / originalWidth
}
// Get the original pixel value
const to = (originalWidth: number, value: number) => {
return value / scale(originalWidth)
}
// Get the scaled pixel value
const from = (originalWidth: number, value: number) => {
return value * scale(originalWidth)
}
const resize = () => {
setWidth(getInnerContentWidth())
}
useEffect(() => {
resize()
window.addEventListener('resize', resize)
return () => {
window.removeEventListener('resize', resize)
}
}, [])
return { to, from }
}
export const useScale = singletonHook(noScaleInit, useScaleImpl, {
unmountIfNoConsumers: true
})

View File

@ -1,12 +1,17 @@
import { useEffect, useState } from 'react'
import { CreateSignatureEventContent, Meta, SignedEventContent } from '../types'
import {
CreateSignatureEventContent,
DocSignatureEvent,
Meta,
SignedEventContent,
OpenTimestamp
} from '../types'
import { Mark } from '../types/mark'
import {
fromUnixTimestamp,
hexToNpub,
parseNostrEvent,
parseCreateSignatureEventContent,
SigitMetaParseError,
SigitStatus,
SignStatus
} from '../utils'
@ -14,8 +19,8 @@ import { toast } from 'react-toastify'
import { verifyEvent } from 'nostr-tools'
import { Event } from 'nostr-tools'
import store from '../store/store'
import { AuthState } from '../store/auth/types'
import { NostrController } from '../controllers'
import { MetaParseError } from '../types/errors/MetaParseError'
/**
* Flattened interface that combines properties `Meta`, `CreateSignatureEventContent`,
@ -28,6 +33,10 @@ export interface FlatMeta
// Remove pubkey and use submittedBy as `npub1${string}`
submittedBy?: `npub1${string}`
// Optional field only present on exported sigits
// Exporting adds user's pubkey
exportedBy?: `npub1${string}`
// Remove created_at and replace with createdAt
createdAt?: number
@ -38,7 +47,9 @@ export interface FlatMeta
encryptionKey: string | null
// Parsed Document Signatures
parsedSignatureEvents: { [signer: `npub1${string}`]: Event }
parsedSignatureEvents: {
[signer: `npub1${string}`]: DocSignatureEvent
}
// Calculated completion time
completedAt?: number
@ -48,6 +59,8 @@ export interface FlatMeta
signersStatus: {
[signer: `npub1${string}`]: SignStatus
}
timestamps?: OpenTimestamp[]
}
/**
@ -61,6 +74,7 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
const [tags, setTags] = useState<string[][]>()
const [createdAt, setCreatedAt] = useState<number>()
const [submittedBy, setSubmittedBy] = useState<`npub1${string}`>() // submittedBy, pubkey from nostr event
const [exportedBy, setExportedBy] = useState<`npub1${string}`>() // pubkey from export signature nostr event
const [id, setId] = useState<string>()
const [sig, setSig] = useState<string>()
@ -74,7 +88,7 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
const [zipUrl, setZipUrl] = useState<string>('')
const [parsedSignatureEvents, setParsedSignatureEvents] = useState<{
[signer: `npub1${string}`]: Event
[signer: `npub1${string}`]: DocSignatureEvent
}>({})
const [completedAt, setCompletedAt] = useState<number>()
@ -92,6 +106,18 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
if (!meta) return
;(async function () {
try {
if (meta.exportSignature) {
const exportSignatureEvent = await parseNostrEvent(
meta.exportSignature
)
if (
verifyEvent(exportSignatureEvent) &&
exportSignatureEvent.pubkey
) {
setExportedBy(exportSignatureEvent.pubkey as `npub1${string}`)
}
}
const createSignatureEvent = await parseNostrEvent(meta.createSignature)
const { kind, tags, created_at, pubkey, id, sig, content } =
@ -119,7 +145,7 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
if (meta.keys) {
const { sender, keys } = meta.keys
// Retrieve the user's public key from the state
const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
const usersPubkey = store.getState().auth.usersPubkey!
const usersNpub = hexToNpub(usersPubkey)
// Check if the user's public key is in the keys object
@ -139,9 +165,11 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
setEncryptionKey(decrypted)
}
}
// Temp. map to hold events and signers
const parsedSignatureEventsMap = new Map<`npub1${string}`, Event>()
const parsedSignatureEventsMap = new Map<
`npub1${string}`,
DocSignatureEvent
>()
const signerStatusMap = new Map<`npub1${string}`, SignStatus>()
const getPrevSignerSig = (npub: `npub1${string}`) => {
@ -183,9 +211,12 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
if (isValidSignature) {
// get the signature of prev signer from the content of current signers signedEvent
const prevSignersSig = getPrevSignerSig(npub)
try {
const obj: SignedEventContent = JSON.parse(event.content)
parsedSignatureEventsMap.set(npub, {
...event,
parsedContent: obj
})
if (
obj.prevSig &&
prevSignersSig &&
@ -234,7 +265,7 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
)
}
} catch (error) {
if (error instanceof SigitMetaParseError) {
if (error instanceof MetaParseError) {
toast.error(error.message)
}
console.error(error)
@ -247,11 +278,13 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
createSignature: meta?.createSignature,
docSignatures: meta?.docSignatures,
keys: meta?.keys,
timestamps: meta?.timestamps,
isValid,
kind,
tags,
createdAt,
submittedBy,
exportedBy,
id,
sig,
signers,

View File

@ -1,70 +0,0 @@
import { useEffect, useState } from 'react'
import { ProfileMetadata } from '../types'
import { MetadataController } from '../controllers'
import { npubToHex } from '../utils'
import { Event, kinds } from 'nostr-tools'
/**
* Extracts profiles from metadata events
* @param pubkeys Array of npubs to check
* @returns ProfileMetadata
*/
export const useSigitProfiles = (
pubkeys: `npub1${string}`[]
): { [key: string]: ProfileMetadata } => {
const [profileMetadata, setProfileMetadata] = useState<{
[key: string]: ProfileMetadata
}>({})
useEffect(() => {
if (pubkeys.length) {
const metadataController = new MetadataController()
// Remove duplicate keys
const users = new Set<string>([...pubkeys])
const handleMetadataEvent = (key: string) => (event: Event) => {
const metadataContent =
metadataController.extractProfileMetadataContent(event)
if (metadataContent) {
setProfileMetadata((prev) => ({
...prev,
[key]: metadataContent
}))
}
}
users.forEach((user) => {
const hexKey = npubToHex(user)
if (hexKey && !(hexKey in profileMetadata)) {
metadataController.on(hexKey, (kind: number, event: Event) => {
if (kind === kinds.Metadata) {
handleMetadataEvent(hexKey)(event)
}
})
metadataController
.findMetadata(hexKey)
.then((metadataEvent) => {
if (metadataEvent) handleMetadataEvent(hexKey)(metadataEvent)
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${user}`,
err
)
})
}
})
return () => {
users.forEach((key) => {
metadataController.off(key, handleMetadataEvent(key))
})
}
}
}, [pubkeys, profileMetadata])
return profileMetadata
}

View File

@ -27,7 +27,7 @@ body {
position: fixed;
top: 80px;
right: 20px;
z-index: 100;
z-index: 40;
}
#root {

View File

@ -1,86 +1,160 @@
import { Event, kinds } from 'nostr-tools'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Outlet } from 'react-router-dom'
import { Event, getPublicKey, kinds, nip19 } from 'nostr-tools'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Outlet, useNavigate, useSearchParams } from 'react-router-dom'
import { AppBar } from '../components/AppBar/AppBar'
import { LoadingSpinner } from '../components/LoadingSpinner'
import { MetadataController, NostrController } from '../controllers'
import {
AuthController,
MetadataController,
NostrController
} from '../controllers'
import {
restoreState,
setAuthState,
setMetadataEvent,
updateKeyPair,
updateLoginMethod,
updateNostrLoginAuthMethod,
updateUserAppData
} from '../store/actions'
import { LoginMethods } from '../store/auth/types'
import { State } from '../store/rootReducer'
import { Dispatch } from '../store/store'
import { setUserRobotImage } from '../store/userRobotImage/action'
import {
clearAuthToken,
clearState,
getRoboHashPicture,
getUsersAppData,
loadState,
saveNsecBunkerDelegatedKey,
subscribeForSigits
} from '../utils'
import { useAppSelector } from '../hooks'
import { SubCloser } from 'nostr-tools/abstract-pool'
import { useAppDispatch, useAppSelector } from '../hooks'
import styles from './style.module.scss'
import { Footer } from '../components/Footer/Footer'
import { useLogout } from '../hooks/useLogout'
import { LoginMethod } from '../store/auth/types'
import { NostrLoginAuthOptions } from 'nostr-login/dist/types'
import { init as initNostrLogin } from 'nostr-login'
export const MainLayout = () => {
const dispatch: Dispatch = useDispatch()
const [searchParams, setSearchParams] = useSearchParams()
const navigate = useNavigate()
const dispatch = useAppDispatch()
const logout = useLogout()
const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState(`Loading App`)
const authState = useSelector((state: State) => state.auth)
const isLoggedIn = useAppSelector((state) => state.auth?.loggedIn)
const authState = useAppSelector((state) => state.auth)
const usersAppData = useAppSelector((state) => state.userAppData)
useEffect(() => {
const metadataController = new MetadataController()
// Ref to track if `subscribeForSigits` has been called
const hasSubscribed = useRef(false)
const logout = () => {
dispatch(
setAuthState({
keyPair: undefined,
loggedIn: false,
usersPubkey: undefined,
loginMethod: undefined,
nsecBunkerPubkey: undefined
})
)
const navigateAfterLogin = (path: string) => {
const callbackPath = searchParams.get('callbackPath')
dispatch(setMetadataEvent(metadataController.getEmptyMetadataEvent()))
// clear authToken saved in local storage
clearAuthToken()
clearState()
// update nsecBunker delegated key
const newDelegatedKey =
NostrController.getInstance().generateDelegatedKey()
saveNsecBunkerDelegatedKey(newDelegatedKey)
if (callbackPath) {
// base64 decoded path
const path = atob(callbackPath)
navigate(path)
return
}
navigate(path)
}
const login = useCallback(async () => {
const nostrController = NostrController.getInstance()
const authController = new AuthController()
const pubkey = await nostrController.capturePublicKey()
dispatch(updateLoginMethod(LoginMethod.nostrLogin))
const redirectPath =
await authController.authAndGetMetadataAndRelaysMap(pubkey)
if (redirectPath) {
navigateAfterLogin(redirectPath)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch])
useEffect(() => {
// Developer login with ?nsec= (not recommended)
const nsec = searchParams.get('nsec')
if (!nsec) return
// Clear nsec from the url immediately
searchParams.delete('nsec')
setSearchParams(searchParams)
if (!authState?.loggedIn) {
if (!nsec.startsWith('nsec')) {
console.error('Invalid format, use private key (nsec)')
return
}
try {
const privateKey = nip19.decode(nsec).data as Uint8Array
if (!privateKey) {
console.error('Failed to convert the private key.')
return
}
const publickey = getPublicKey(privateKey)
dispatch(
updateKeyPair({
private: nsec,
public: publickey
})
)
dispatch(updateLoginMethod(LoginMethod.privateKey))
const authController = new AuthController()
authController
.authAndGetMetadataAndRelaysMap(publickey)
.catch((err) => {
console.error('Error occurred in authentication: ' + err)
return null
})
} catch (err) {
console.error(`Error decoding the nsec. ${err}`)
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch, searchParams])
useEffect(() => {
const handleNostrAuth = (_: string, opts: NostrLoginAuthOptions) => {
if (opts.type === 'login' || opts.type === 'signup') {
dispatch(updateNostrLoginAuthMethod(opts.method))
login()
} else if (opts.type === 'logout') {
// Clear `subscribeForSigits` as called after the logout
hasSubscribed.current = false
}
}
// Initialize the nostr-login
initNostrLogin({
methods: ['connect', 'extension', 'local'],
noBanner: true,
onAuth: handleNostrAuth
}).catch((error) => {
console.error('Failed to initialize Nostr-Login', error)
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch])
useEffect(() => {
const metadataController = MetadataController.getInstance()
const restoredState = loadState()
if (restoredState) {
dispatch(restoreState(restoredState))
const { loggedIn, loginMethod, usersPubkey, nsecBunkerRelays } =
restoredState.auth
const { loggedIn, loginMethod, usersPubkey } = restoredState.auth
if (loggedIn) {
if (!loginMethod || !usersPubkey) return logout()
if (loginMethod === LoginMethods.nsecBunker) {
if (!nsecBunkerRelays) return logout()
const nostrController = NostrController.getInstance()
nostrController.nsecBunkerInit(nsecBunkerRelays).then(() => {
nostrController.createNsecBunkerSigner(usersPubkey)
})
}
// Update user profile metadata, old state might be outdated
const handleMetadataEvent = (event: Event) => {
dispatch(setMetadataEvent(event))
}
@ -100,27 +174,26 @@ export const MainLayout = () => {
} else {
setIsLoading(false)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch])
/**
* Subscribe for the sigits
*/
useEffect(() => {
let subCloser: SubCloser | null = null
if (authState.loggedIn && usersAppData) {
if (authState && isLoggedIn && usersAppData) {
const pubkey = authState.usersPubkey || authState.keyPair?.public
if (pubkey) {
subscribeForSigits(pubkey).then((res) => {
subCloser = res || null
})
}
}
if (pubkey && !hasSubscribed.current) {
// Call `subscribeForSigits` only if it hasn't been called before
// #193 disabled websocket subscribtion, until #194 is done
subscribeForSigits(pubkey)
return () => {
if (subCloser) {
subCloser.close()
// Mark `subscribeForSigits` as called
hasSubscribed.current = true
}
}
}, [authState, usersAppData])
}, [authState, isLoggedIn, usersAppData])
/**
* When authState change user logged in / or app reloaded
@ -128,7 +201,7 @@ export const MainLayout = () => {
* so that avatar will be consistent across the app when kind 0 is empty
*/
useEffect(() => {
if (authState && authState.loggedIn) {
if (authState && isLoggedIn) {
const pubkey = authState.usersPubkey || authState.keyPair?.public
if (pubkey) {
@ -145,17 +218,26 @@ export const MainLayout = () => {
})
.finally(() => setIsLoading(false))
}
}, [authState, dispatch])
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch, isLoggedIn])
if (isLoading) return <LoadingSpinner desc={loadingSpinnerDesc} />
const isDev = import.meta.env.MODE === 'development'
return (
<>
<AppBar />
<main className={styles.main}>
<main
className={styles.main}
// Add dev debug flag to show special dev css
// (visible marks border on verify)
{...(isDev && {
'data-dev': true
})}
>
<Outlet />
</main>
<Footer />
</>
)
}

View File

@ -3,27 +3,102 @@
.container {
display: grid;
grid-template-columns: 0.75fr 1.5fr 0.75fr;
grid-gap: 30px;
flex-grow: 1;
@media only screen and (max-width: 767px) {
gap: 20px;
grid-auto-flow: column;
grid-auto-columns: 100%;
// Hide Scrollbar and let's use tabs to navigate
-ms-overflow-style: none; /* Internet Explorer 10+ */
scrollbar-width: none; /* Firefox */
&::-webkit-scrollbar {
display: none; /* Safari and Chrome */
}
overflow-x: auto;
overscroll-behavior-inline: contain;
scroll-snap-type: inline mandatory;
> * {
scroll-margin-top: $header-height + $body-vertical-padding;
scroll-snap-align: start;
scroll-snap-stop: always; // Touch devices will always stop on each element
}
}
@media only screen and (min-width: 768px) {
grid-template-columns: 0.75fr 1.5fr 0.75fr;
gap: 30px;
}
}
.sidesWrap {
position: relative;
// HACK: Stop grid column from growing
min-width: 0;
}
.sides {
position: sticky;
top: $header-height + $body-vertical-padding;
@media only screen and (min-width: 768px) {
position: sticky;
top: $body-vertical-padding;
}
> :first-child {
// We want to keep header on smaller devices at all times
max-height: calc(
100dvh - $header-height - $body-vertical-padding * 2 - $tabs-height
);
@media only screen and (min-width: 768px) {
max-height: calc(100dvh - $body-vertical-padding * 2);
}
}
}
.files {
display: flex;
flex-direction: column;
grid-gap: 15px;
// Adjust the content scroll on smaller screens
// Make sure only the inner tab is scrolling
.scrollAdjust {
@media only screen and (max-width: 767px) {
max-height: calc(
100svh - $header-height - $body-vertical-padding * 2 - $tabs-height
);
overflow-y: auto;
}
}
.content {
max-width: 550px;
width: 550px;
margin: 0 auto;
@media only screen and (min-width: 768px) {
padding: 10px;
border: 10px solid $overlay-background-color;
border-radius: 4px;
}
}
.navTabs {
display: none;
position: fixed;
left: 0;
bottom: 0;
right: 0;
height: $tabs-height;
z-index: 2;
background: $overlay-background-color;
box-shadow: 0 0 4px 0 rgb(0, 0, 0, 0.1);
padding: 5px;
gap: 5px;
@media only screen and (max-width: 767px) {
display: flex;
}
> li {
flex-grow: 1;
}
}
.active {
background-color: $primary-main !important;
color: white !important;
}

View File

@ -1,26 +1,147 @@
import { PropsWithChildren, ReactNode } from 'react'
import {
PropsWithChildren,
ReactNode,
useEffect,
useRef,
useState
} from 'react'
import styles from './StickySideColumns.module.scss'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { IconDefinition } from '@fortawesome/free-solid-svg-icons'
import { Button } from '@mui/material'
interface StickySideColumnsProps {
left?: ReactNode
right?: ReactNode
left: ReactNode
right: ReactNode
leftIcon: IconDefinition
centerIcon: IconDefinition
rightIcon: IconDefinition
}
const DEFAULT_TAB = 'nav-content'
export const StickySideColumns = ({
left,
right,
leftIcon,
centerIcon,
rightIcon,
children
}: PropsWithChildren<StickySideColumnsProps>) => {
const [tab, setTab] = useState(DEFAULT_TAB)
const ref = useRef<HTMLDivElement>(null)
const tabsRefs = useRef<{ [id: string]: HTMLDivElement | null }>({})
const handleNavClick = (id: string) => {
if (ref.current && tabsRefs.current) {
const x = tabsRefs.current[id]?.offsetLeft
ref.current.scrollTo({
left: x,
behavior: 'smooth'
})
}
}
const isActive = (id: string) => id === tab
useEffect(() => {
setTab(DEFAULT_TAB)
handleNavClick(DEFAULT_TAB)
}, [])
useEffect(() => {
const tabs = tabsRefs.current
// Set up the observer
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setTab(entry.target.id)
}
})
},
{
root: ref.current,
threshold: 0.5,
rootMargin: '-20px'
}
)
if (tabs) {
Object.values(tabs).forEach((tab) => {
if (tab) observer.observe(tab)
})
}
return () => {
if (tabs) {
Object.values(tabs).forEach((tab) => {
if (tab) observer.unobserve(tab)
})
}
}
}, [])
return (
<div className={styles.container}>
<div className={`${styles.sidesWrap} ${styles.files}`}>
<div className={styles.sides}>{left}</div>
<>
<div className={styles.container} ref={ref}>
<div
id="nav-left"
className={styles.sidesWrap}
ref={(tab) => (tabsRefs.current['nav-left'] = tab)}
>
<div className={styles.sides}>{left}</div>
</div>
<div
id="nav-content"
className={styles.scrollAdjust}
ref={(tab) => (tabsRefs.current['nav-content'] = tab)}
>
<div id="content-preview" className={styles.content}>
{children}
</div>
</div>
<div
id="nav-right"
className={styles.sidesWrap}
ref={(tab) => (tabsRefs.current['nav-right'] = tab)}
>
<div className={styles.sides}>{right}</div>
</div>
</div>
<div className={styles.content}>{children}</div>
<div className={styles.sidesWrap}>
<div className={styles.sides}>{right}</div>
</div>
</div>
<ul className={styles.navTabs}>
<li>
<Button
fullWidth
variant="text"
onClick={() => handleNavClick('nav-left')}
className={`${isActive('nav-left') && styles.active}`}
aria-label="nav left"
>
<FontAwesomeIcon icon={leftIcon} />
</Button>
</li>
<li>
<Button
fullWidth
variant="text"
onClick={() => handleNavClick('nav-content')}
className={`${isActive('nav-content') && styles.active}`}
aria-label="nav middle"
>
<FontAwesomeIcon icon={centerIcon} />
</Button>
</li>
<li>
<Button
fullWidth
variant="text"
onClick={() => handleNavClick('nav-right')}
className={`${isActive('nav-right') && styles.active}`}
aria-label="nav right"
>
<FontAwesomeIcon icon={rightIcon} />
</Button>
</li>
</ul>
</>
)
}

View File

@ -33,7 +33,7 @@ export const Modal = () => {
{ to: appPublicRoutes.register, title: 'Register', label: 'Register' },
{
to: appPublicRoutes.nostr,
title: 'Login',
title: 'Nostr Login',
sx: { padding: '10px' },
label: <img src={nostrImage} width="25" alt="nostr logo" height="25" />
}

View File

@ -3,6 +3,5 @@
.main {
flex-grow: 1;
padding: $header-height + $body-vertical-padding 0 $body-vertical-padding 0;
background-color: $body-background-color;
padding: $body-vertical-padding 0 $body-vertical-padding 0;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,41 +1,242 @@
@import '../../styles/colors.scss';
.container {
.flexWrap {
display: flex;
flex-direction: column;
color: $text-color;
margin-top: 10px;
gap: 10px;
width: 550px;
max-width: 550px;
gap: 15px;
.inputBlock {
display: flex;
flex-direction: column;
gap: 25px;
}
container-type: inline-size;
}
.subHeader {
border-bottom: 0.5px solid;
}
.orderedFilesList {
counter-reset: item;
list-style-type: none;
margin: 0;
.tableHeaderCell {
border-right: 1px solid rgba(224, 224, 224, 1);
}
.tableCell {
border-right: 1px solid rgba(224, 224, 224, 1);
height: 56px;
.user {
li {
display: flex;
align-items: center;
transition: ease 0.4s;
border-radius: 4px;
background: #ffffff;
padding: 7px 10px;
color: rgba(0, 0, 0, 0.5);
min-height: 45px;
cursor: pointer;
gap: 10px;
.name {
text-align: center;
cursor: pointer;
&::before {
content: counter(item) ' ';
counter-increment: item;
font-size: 14px;
}
:nth-child(1) {
flex-grow: 1;
font-size: 16px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
button {
min-width: 44px;
color: $primary-main;
}
&:hover,
&.active,
&:focus-within {
background: $primary-main;
color: white;
button {
color: white;
}
}
}
}
}
.uploadFileText {
margin-left: 12px;
}
.paperGroup {
border-radius: 4px;
background: white;
padding: 15px;
display: flex;
flex-direction: column;
gap: 15px;
overflow-x: hidden;
overflow-y: auto;
}
.inputWrapper {
display: flex;
align-items: center;
flex-shrink: 0;
height: 36px;
overflow: hidden;
border-radius: 4px;
outline: solid 1px #dddddd;
background: white;
width: 100%;
&:focus-within {
outline-color: $primary-main;
}
// Override default MUI input styles only inside inputWrapepr
:global {
.MuiInputBase-input {
padding: 7px 14px;
}
.MuiOutlinedInput-notchedOutline {
display: none;
}
}
}
.addCounterpart {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: start;
gap: 10px;
> .inputWrapper {
flex-shrink: 1;
}
button {
min-width: 44px;
padding: 11px 12px;
}
}
.users {
flex-shrink: 0;
max-height: 33vh;
.counterpartToggleButton {
min-width: 44px;
padding: 11px 12px;
}
}
.user {
display: flex;
gap: 10px;
font-size: 14px;
text-align: start;
justify-content: center;
align-items: center;
a:hover {
text-decoration: none;
}
// Higher specificify to override default button styles
.counterpartRowToggleButton {
min-width: 34px;
height: 34px;
padding: 0;
}
}
.counterpartRowToggleButton {
&[data-variant='primary'] {
color: $primary-main;
}
&[data-variant='secondary'] {
color: rgba(0, 0, 0, 0.35);
}
}
.avatar {
flex-grow: 1;
min-width: 0;
&:first-child {
margin-left: 24px;
}
img {
// Override the default avatar size
width: 30px;
height: 30px;
}
}
.fileName {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
flex-grow: 1;
}
.toolbox {
display: grid;
grid-template-columns: 1fr;
@container (min-width: 204px) {
grid-template-columns: repeat(2, 1fr);
}
@container (min-width: 309px) {
grid-template-columns: repeat(3, 1fr);
}
gap: 15px;
overflow-x: hidden;
overflow-y: auto;
container-type: inline-size;
}
.toolItem {
transition: ease 0.2s;
display: flex;
flex-direction: column;
gap: 5px;
border-radius: 4px;
padding: 10px 5px 5px 5px;
background: rgba(0, 0, 0, 0.05);
color: rgba(0, 0, 0, 0.5);
text-align: center;
align-items: center;
justify-content: center;
font-size: 14px;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
&.selected {
background: $primary-main;
color: white;
}
&:not(.selected, .comingSoon) {
&:hover {
background: $primary-light;
color: white;
}
}
&.comingSoon {
opacity: 0.5;
cursor: not-allowed;
}
}
.comingSoonPlaceholder {
font-size: 10px;
}

View File

@ -18,6 +18,7 @@ import {
SigitCardDisplayInfo,
SigitStatus
} from '../../utils'
import { Footer } from '../../components/Footer/Footer'
// Unsupported Filter options are commented
const FILTERS = [
@ -225,11 +226,11 @@ export const HomePage = () => {
type="button"
aria-label="upload files"
>
<input {...getInputProps()} />
<input id="file-upload" {...getInputProps()} />
{isDragActive ? (
<p>Drop the files here ...</p>
<label htmlFor="file-upload">Drop the files here ...</label>
) : (
<p>Click or drag files to upload!</p>
<label htmlFor="file-upload">Click or drag files to upload!</label>
)}
</button>
<div className={styles.submissions}>
@ -256,12 +257,14 @@ export const HomePage = () => {
.map((key) => (
<DisplaySigit
key={`sigit-${key}`}
sigitCreateId={key}
parsedMeta={parsedSigits[key]}
meta={sigits[key]}
/>
))}
</div>
</Container>
<Footer />
</div>
)
}

View File

@ -1,7 +1,6 @@
import { Box, Button } from '@mui/material'
import { useEffect } from 'react'
import { Outlet, useLocation, useNavigate } from 'react-router-dom'
import { appPublicRoutes } from '../../routes'
import { Outlet, useLocation } from 'react-router-dom'
import { saveVisitedLink } from '../../utils'
import { CardComponent } from '../../components/Landing/CardComponent/CardComponent'
import { Container } from '../../components/Container'
@ -19,13 +18,14 @@ import {
faWifi
} from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIconStack } from '../../components/FontAwesomeIconStack'
import { Footer } from '../../components/Footer/Footer'
import { launch as launchNostrLoginDialog } from 'nostr-login'
export const LandingPage = () => {
const navigate = useNavigate()
const location = useLocation()
const onSignInClick = async () => {
navigate(appPublicRoutes.nostr)
launchNostrLoginDialog()
}
const cards = [
@ -34,7 +34,7 @@ export const LandingPage = () => {
title: <>Open Source</>,
description: (
<>
Code is MIT licenced and available at{' '}
Code is AGPL licenced and available at{' '}
<a href="https://git.nostrdev.com/sigit/sigit.io">
https://git.nostrdev.com/sigit/sigit.io
</a>
@ -69,8 +69,8 @@ export const LandingPage = () => {
title: <>Verifiable</>,
description: (
<>
Thanks to Schnorr Signatures and Web of Trust, SIGit is far more
auditable than traditional server-based offerings.
SIGit Agreements can be directly verified - unlike traditional,
server-based offerings.
</>
)
},
@ -84,8 +84,8 @@ export const LandingPage = () => {
title: <>Works Offline</>,
description: (
<>
Presuming you have a hardware signing device, it is possible to
complete a SIGit round without an internet connection.
It is possible to complete a SIGit round without an internet
connection.
</>
)
},
@ -94,8 +94,8 @@ export const LandingPage = () => {
title: <>Multi-Party Signing</>,
description: (
<>
Choose any number of Signers and Viewers, track the signature status,
send reminders, get notifications on completion.
Choose any number of Signers and Viewers, track status, get
notifications on completion.
</>
)
}
@ -119,9 +119,7 @@ export const LandingPage = () => {
<Container className={styles.container}>
<img className={styles.logo} src="/logo.svg" alt="Logo" width={300} />
<div className={styles.titleSection}>
<h1 className={styles.title}>
Secure &amp; Private Document Signing
</h1>
<h1 className={styles.title}>Secure &amp; Private Agreements</h1>
<p className={styles.subTitle}>
An open-source and self-hostable solution for secure document
signing and verification.
@ -162,6 +160,7 @@ export const LandingPage = () => {
<Outlet />
</Container>
<Footer />
</div>
)
}

View File

@ -12,6 +12,11 @@ export const Login = () => {
margin="dense"
autoComplete="username"
disabled
sx={{
input: {
cursor: 'not-allowed'
}
}}
/>
<TextField
label="Password"
@ -20,6 +25,11 @@ export const Login = () => {
margin="dense"
autoComplete="current-password"
disabled
sx={{
input: {
cursor: 'not-allowed'
}
}}
/>
<Button variant="contained" fullWidth disabled>

View File

@ -1,62 +1,31 @@
import { launch as launchNostrLoginDialog } from 'nostr-login'
import { Button, Divider, TextField } from '@mui/material'
import { getPublicKey, nip19 } from 'nostr-tools'
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useAppDispatch } from '../../hooks/store'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import {
AuthController,
MetadataController,
NostrController
} from '../../controllers'
import {
updateKeyPair,
updateLoginMethod,
updateNsecbunkerPubkey,
updateNsecbunkerRelays
} from '../../store/actions'
import { LoginMethods } from '../../store/auth/types'
import { Dispatch } from '../../store/store'
import { npubToHex, queryNip05 } from '../../utils'
import { AuthController } from '../../controllers'
import { updateKeyPair, updateLoginMethod } from '../../store/actions'
import { KeyboardCode } from '../../types'
import { LoginMethod } from '../../store/auth/types'
import { hexToBytes } from '@noble/hashes/utils'
import { NIP05_REGEX } from '../../constants'
import styles from './styles.module.scss'
export const Nostr = () => {
const [searchParams] = useSearchParams()
const dispatch: Dispatch = useDispatch()
const dispatch = useAppDispatch()
const navigate = useNavigate()
const authController = new AuthController()
const metadataController = new MetadataController()
const nostrController = NostrController.getInstance()
const [isLoading, setIsLoading] = useState(false)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
const [inputValue, setInputValue] = useState('')
const [authUrl, setAuthUrl] = useState<string>()
const [isNostrExtensionAvailable, setIsNostrExtensionAvailable] =
useState(false)
useEffect(() => {
setTimeout(() => {
setIsNostrExtensionAvailable(!!window.nostr)
}, 500)
}, [])
/**
* Call login function when enter is pressed
*/
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.code === 'Enter' || event.code === 'NumpadEnter') {
event.preventDefault()
login()
}
}
const navigateAfterLogin = (path: string) => {
const callbackPath = searchParams.get('callbackPath')
@ -71,28 +40,26 @@ export const Nostr = () => {
navigate(path)
}
const loginWithExtension = async () => {
setIsLoading(true)
setLoadingSpinnerDesc('Capturing pubkey from nostr extension')
const [isNostrExtensionAvailable, setIsNostrExtensionAvailable] =
useState(false)
nostrController
.capturePublicKey()
.then(async (pubkey) => {
dispatch(updateLoginMethod(LoginMethods.extension))
useEffect(() => {
setTimeout(() => {
setIsNostrExtensionAvailable(!!window.nostr)
}, 500)
}, [])
setLoadingSpinnerDesc('Authenticating and finding metadata')
const redirectPath =
await authController.authAndGetMetadataAndRelaysMap(pubkey)
if (redirectPath) navigateAfterLogin(redirectPath)
})
.catch((err) => {
toast.error('Error capturing public key from nostr extension: ' + err)
})
.finally(() => {
setIsLoading(false)
setLoadingSpinnerDesc('')
})
/**
* Call login function when enter is pressed
*/
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
if (
event.code === KeyboardCode.Enter ||
event.code === KeyboardCode.NumpadEnter
) {
event.preventDefault()
login()
}
}
/**
@ -130,7 +97,7 @@ export const Nostr = () => {
public: publickey
})
)
dispatch(updateLoginMethod(LoginMethods.privateKey))
dispatch(updateLoginMethod(LoginMethod.privateKey))
setIsLoading(true)
setLoadingSpinnerDesc('Authenticating and finding metadata')
@ -148,182 +115,10 @@ export const Nostr = () => {
setLoadingSpinnerDesc('')
}
const loginWithNsecBunker = async () => {
let relays: string[] | undefined
let pubkey: string | undefined
setIsLoading(true)
const displayError = (message: string) => {
toast.error(message)
setIsLoading(false)
setLoadingSpinnerDesc('')
}
if (inputValue.match(NIP05_REGEX)) {
const nip05Profile = await queryNip05(inputValue).catch((err) => {
toast.error('An error occurred while querying nip05 profile: ' + err)
return null
})
if (nip05Profile) {
pubkey = nip05Profile.pubkey
relays = nip05Profile.relays
}
} else if (inputValue.startsWith('npub')) {
pubkey = nip19.decode(inputValue).data as string
const metadataEvent = await metadataController
.findMetadata(pubkey)
.catch(() => {
return null
})
if (!metadataEvent) {
return displayError('metadata not found!')
}
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (!metadataContent?.nip05) {
return displayError('nip05 not present in metadata')
}
const nip05Profile = await queryNip05(inputValue).catch((err) => {
toast.error('An error occurred while querying nip05 profile: ' + err)
return null
})
if (nip05Profile) {
if (nip05Profile.pubkey !== pubkey) {
return displayError(
'pubkey in nip05 does not match with provided npub'
)
}
relays = nip05Profile.relays
}
}
if (!relays || relays.length === 0) {
return displayError('No relay found for nsecbunker')
}
if (!pubkey) {
return displayError('pubkey not found')
}
setLoadingSpinnerDesc('Initializing nsecBunker')
await nostrController.nsecBunkerInit(relays)
setLoadingSpinnerDesc('Creating nsecbunker singer')
await nostrController
.createNsecBunkerSigner(pubkey)
.then(async (signer) => {
signer.on('authUrl', (url: string) => {
setAuthUrl(url)
})
dispatch(updateLoginMethod(LoginMethods.nsecBunker))
dispatch(updateNsecbunkerPubkey(pubkey))
dispatch(updateNsecbunkerRelays(relays))
setLoadingSpinnerDesc('Authenticating and finding metadata')
const redirectPath = await authController
.authAndGetMetadataAndRelaysMap(pubkey!)
.catch((err) => {
toast.error('Error occurred in authentication: ' + err)
return null
})
if (redirectPath) navigateAfterLogin(redirectPath)
})
.catch((err) => {
toast.error(
'An error occurred while creating nsecbunker signer: ' + err
)
})
.finally(() => {
setIsLoading(false)
setLoadingSpinnerDesc('')
})
}
const loginWithBunkerConnectionString = async () => {
// Extract the key
const keyStartIndex = inputValue.indexOf('bunker://') + 'bunker://'.length
const keyEndIndex = inputValue.indexOf('?relay=')
const key = inputValue.substring(keyStartIndex, keyEndIndex)
const pubkey = npubToHex(key)
if (!pubkey) {
toast.error('Invalid pubkey in bunker connection string.')
setIsLoading(false)
return
}
// Extract the relay value
const relayIndex = inputValue.indexOf('relay=')
const relay = inputValue.substring(
relayIndex + 'relay='.length,
inputValue.length
)
setIsLoading(true)
setLoadingSpinnerDesc('Initializing bunker NDK')
await nostrController.nsecBunkerInit([relay])
setLoadingSpinnerDesc('Creating remote signer')
await nostrController
.createNsecBunkerSigner(pubkey)
.then(async (signer) => {
signer.on('authUrl', (url: string) => {
setAuthUrl(url)
})
dispatch(updateLoginMethod(LoginMethods.nsecBunker))
dispatch(updateNsecbunkerPubkey(pubkey))
dispatch(updateNsecbunkerRelays([relay]))
setLoadingSpinnerDesc('Authenticating and finding metadata')
const redirectPath = await authController
.authAndGetMetadataAndRelaysMap(pubkey!)
.catch((err) => {
toast.error('Error occurred in authentication: ' + err)
return null
})
if (redirectPath) navigateAfterLogin(redirectPath)
})
.catch((err) => {
toast.error(
'An error occurred while creating nsecbunker signer: ' + err
)
})
.finally(() => {
setIsLoading(false)
setLoadingSpinnerDesc('')
})
}
const login = () => {
if (inputValue.startsWith('bunker://')) {
return loginWithBunkerConnectionString()
}
if (inputValue.startsWith('nsec')) {
return loginWithNsec()
}
if (inputValue.startsWith('npub')) {
return loginWithNsecBunker()
}
if (inputValue.match(NIP05_REGEX)) {
return loginWithNsecBunker()
}
// Check if maybe hex nsec
try {
@ -335,38 +130,33 @@ export const Nostr = () => {
console.warn('err', err)
}
toast.error(
'Invalid format, please use: private key (hex), nsec..., bunker:// or nip05 format.'
)
toast.error('Invalid format, please use: private key (hex or nsec)')
return
}
if (authUrl) {
return (
<iframe
title="Nsecbunker auth"
src={authUrl}
width="100%"
height="500px"
/>
)
}
return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
{isNostrExtensionAvailable && (
<>
<label className={styles.label} htmlFor="extension-login">
Login by using a browser extension
Login by using a{' '}
<a
rel="noopener"
href="https://github.com/nostrband/nostr-login"
target="_blank"
>
nostr-login
</a>
</label>
<Button
id="extension-login"
onClick={loginWithExtension}
id="nostr-login"
variant="contained"
onClick={() => {
launchNostrLoginDialog()
}}
>
Extension Login
Nostr Login
</Button>
<Divider
sx={{
@ -377,16 +167,18 @@ export const Nostr = () => {
</Divider>
</>
)}
<TextField
onKeyDown={handleInputKeyDown}
label="nip05 login / nip46 bunker string"
helperText="Private key (Not recommended)"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
fullWidth
margin="dense"
/>
<form autoComplete="off">
<TextField
onKeyDown={handleInputKeyDown}
label="Private key (Not recommended)"
type="password"
autoComplete="off"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
fullWidth
margin="dense"
/>
</form>
<Button
disabled={!inputValue}
onClick={login}

View File

@ -1,41 +1,48 @@
import ContentCopyIcon from '@mui/icons-material/ContentCopy'
import EditIcon from '@mui/icons-material/Edit'
import { Box, IconButton, SxProps, Theme, Typography } from '@mui/material'
import { truncate } from 'lodash'
import { Event, VerifiedEvent, kinds, nip19 } from 'nostr-tools'
import { useEffect, useMemo, useState } from 'react'
import { useSelector } from 'react-redux'
import { useAppSelector } from '../../hooks/store'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { MetadataController } from '../../controllers'
import { getProfileSettingsRoute } from '../../routes'
import { State } from '../../store/rootReducer'
import { NostrJoiningBlock, ProfileMetadata } from '../../types'
import { getRoboHashPicture, hexToNpub, shorten } from '../../utils'
import {
getNostrJoiningBlockNumber,
getProfileUsername,
getRoboHashPicture,
hexToNpub,
shorten
} from '../../utils'
import styles from './style.module.scss'
import { Container } from '../../components/Container'
import { Footer } from '../../components/Footer/Footer'
export const ProfilePage = () => {
const navigate = useNavigate()
const { npub } = useParams()
const metadataController = useMemo(() => new MetadataController(), [])
const metadataController = useMemo(() => MetadataController.getInstance(), [])
const [pubkey, setPubkey] = useState<string>()
const [nostrJoiningBlock, setNostrJoiningBlock] =
useState<NostrJoiningBlock | null>(null)
const [profileMetadata, setProfileMetadata] = useState<ProfileMetadata>()
const metadataState = useSelector((state: State) => state.metadata)
const { usersPubkey } = useSelector((state: State) => state.auth)
const userRobotImage = useSelector((state: State) => state.userRobotImage)
const metadataState = useAppSelector((state) => state.metadata)
const { usersPubkey } = useAppSelector((state) => state.auth)
const userRobotImage = useAppSelector((state) => state.userRobotImage)
const [isUsersOwnProfile, setIsUsersOwnProfile] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc] = useState('Fetching metadata')
const profileName = pubkey && getProfileUsername(pubkey, profileMetadata)
useEffect(() => {
if (npub) {
try {
@ -51,8 +58,7 @@ export const ProfilePage = () => {
useEffect(() => {
if (pubkey) {
metadataController
.getNostrJoiningBlockNumber(pubkey)
getNostrJoiningBlockNumber(pubkey)
.then((res) => {
setNostrJoiningBlock(res)
})
@ -161,7 +167,10 @@ export const ProfilePage = () => {
className={`${styles.banner} ${!profileMetadata || !profileMetadata.banner ? styles.noImage : ''}`}
>
{profileMetadata && profileMetadata.banner ? (
<img src={profileMetadata.banner} />
<img
src={profileMetadata.banner}
alt={`banner image for ${profileName}`}
/>
) : (
''
)}
@ -181,6 +190,7 @@ export const ProfilePage = () => {
<img
className={styles['image-placeholder']}
src={getProfileImage(profileMetadata!)}
alt={profileName}
/>
</div>
</Box>
@ -220,14 +230,7 @@ export const ProfilePage = () => {
variant="h6"
className={styles.bold}
>
{truncate(
profileMetadata.display_name ||
profileMetadata.name ||
hexToNpub(pubkey),
{
length: 16
}
)}
{profileName}
</Typography>
)}
</Box>
@ -281,6 +284,7 @@ export const ProfilePage = () => {
</Box>
</Container>
)}
<Footer />
</>
)
}

View File

@ -24,7 +24,7 @@
}
.container {
color: black
color: black;
}
.left {
@ -51,7 +51,8 @@
}
.image-placeholder {
width: 150px;
width: 100%;
height: auto;
}
.link {
@ -99,4 +100,4 @@
margin-left: 5px;
margin-top: 2px;
}
}
}

View File

@ -12,6 +12,11 @@ export const Register = () => {
margin="dense"
autoComplete="username"
disabled
sx={{
input: {
cursor: 'not-allowed'
}
}}
/>
<TextField
label="Password"
@ -21,6 +26,11 @@ export const Register = () => {
type="password"
autoComplete="new-password"
disabled
sx={{
input: {
cursor: 'not-allowed'
}
}}
/>
<TextField
label="Confirm password"
@ -30,6 +40,11 @@ export const Register = () => {
type="password"
autoComplete="new-password"
disabled
sx={{
input: {
cursor: 'not-allowed'
}
}}
/>
<Button variant="contained" fullWidth disabled>

View File

@ -2,24 +2,22 @@ import AccountCircleIcon from '@mui/icons-material/AccountCircle'
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos'
import CachedIcon from '@mui/icons-material/Cached'
import RouterIcon from '@mui/icons-material/Router'
import { useTheme } from '@mui/material'
import { ListItem, useTheme } from '@mui/material'
import List from '@mui/material/List'
import ListItemButton from '@mui/material/ListItemButton'
import ListItemIcon from '@mui/material/ListItemIcon'
import ListItemText from '@mui/material/ListItemText'
import ListSubheader from '@mui/material/ListSubheader'
import { useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { useAppSelector } from '../../hooks/store'
import { Link } from 'react-router-dom'
import { appPrivateRoutes, getProfileSettingsRoute } from '../../routes'
import { State } from '../../store/rootReducer'
import { Container } from '../../components/Container'
import { Footer } from '../../components/Footer/Footer'
import ExtensionIcon from '@mui/icons-material/Extension'
import { LoginMethod } from '../../store/auth/types'
export const SettingsPage = () => {
const theme = useTheme()
const navigate = useNavigate()
const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)
const { usersPubkey, loginMethod } = useAppSelector((state) => state.auth)
const listItem = (label: string, disabled = false) => {
return (
<>
@ -43,56 +41,56 @@ export const SettingsPage = () => {
}
return (
<Container>
<List
sx={{
width: '100%',
bgcolor: 'background.paper'
}}
subheader={
<ListSubheader
sx={{
fontSize: '1.5rem',
borderBottom: '0.5px solid',
paddingBottom: 2,
paddingTop: 2
}}
>
Settings
</ListSubheader>
}
>
<ListItemButton
onClick={() => {
navigate(getProfileSettingsRoute(usersPubkey!))
<>
<Container>
<List
sx={{
width: '100%',
bgcolor: 'background.paper'
}}
subheader={
<ListSubheader
sx={{
fontSize: '1.5rem',
borderBottom: '0.5px solid',
paddingBottom: 2,
paddingTop: 2,
zIndex: 2
}}
>
Settings
</ListSubheader>
}
>
<ListItemIcon>
<AccountCircleIcon />
</ListItemIcon>
{listItem('Profile')}
</ListItemButton>
<ListItemButton
onClick={() => {
navigate(appPrivateRoutes.relays)
}}
>
<ListItemIcon>
<RouterIcon />
</ListItemIcon>
{listItem('Relays')}
</ListItemButton>
<ListItemButton
onClick={() => {
navigate(appPrivateRoutes.cacheSettings)
}}
>
<ListItemIcon>
<CachedIcon />
</ListItemIcon>
{listItem('Local Cache')}
</ListItemButton>
</List>
</Container>
<ListItem component={Link} to={getProfileSettingsRoute(usersPubkey!)}>
<ListItemIcon>
<AccountCircleIcon />
</ListItemIcon>
{listItem('Profile')}
</ListItem>
<ListItem component={Link} to={appPrivateRoutes.relays}>
<ListItemIcon>
<RouterIcon />
</ListItemIcon>
{listItem('Relays')}
</ListItem>
<ListItem component={Link} to={appPrivateRoutes.cacheSettings}>
<ListItemIcon>
<CachedIcon />
</ListItemIcon>
{listItem('Local Cache')}
</ListItem>
{loginMethod === LoginMethod.nostrLogin && (
<ListItem component={Link} to={appPrivateRoutes.nostrLogin}>
<ListItemIcon>
<ExtensionIcon />
</ListItemIcon>
{listItem('Nostr Login')}
</ListItem>
)}
</List>
</Container>
<Footer />
</>
)
}

View File

@ -14,6 +14,7 @@ import { toast } from 'react-toastify'
import { localCache } from '../../../services'
import { LoadingSpinner } from '../../../components/LoadingSpinner'
import { Container } from '../../../components/Container'
import { Footer } from '../../../components/Footer/Footer'
export const CacheSettingsPage = () => {
const theme = useTheme()
@ -50,48 +51,52 @@ export const CacheSettingsPage = () => {
}
return (
<Container>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<List
sx={{
width: '100%',
bgcolor: 'background.paper',
marginTop: 2
}}
subheader={
<ListSubheader
sx={{
fontSize: '1.5rem',
borderBottom: '0.5px solid',
paddingBottom: 2,
paddingTop: 2
}}
>
Cache Setting
</ListSubheader>
}
>
<ListItemButton disabled>
<ListItemIcon>
<IosShareIcon />
</ListItemIcon>
{listItem('Export (coming soon)')}
</ListItemButton>
<>
<Container>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<List
sx={{
width: '100%',
bgcolor: 'background.paper',
marginTop: 2
}}
subheader={
<ListSubheader
sx={{
fontSize: '1.5rem',
borderBottom: '0.5px solid',
paddingBottom: 2,
paddingTop: 2,
zIndex: 2
}}
>
Cache Setting
</ListSubheader>
}
>
<ListItemButton disabled>
<ListItemIcon>
<IosShareIcon />
</ListItemIcon>
{listItem('Export (coming soon)')}
</ListItemButton>
<ListItemButton disabled>
<ListItemIcon>
<InputIcon />
</ListItemIcon>
{listItem('Import (coming soon)')}
</ListItemButton>
<ListItemButton disabled>
<ListItemIcon>
<InputIcon />
</ListItemIcon>
{listItem('Import (coming soon)')}
</ListItemButton>
<ListItemButton onClick={handleClearData}>
<ListItemIcon>
<ClearIcon sx={{ color: theme.palette.error.main }} />
</ListItemIcon>
{listItem('Clear Cache')}
</ListItemButton>
</List>
</Container>
<ListItemButton onClick={handleClearData}>
<ListItemIcon>
<ClearIcon sx={{ color: theme.palette.error.main }} />
</ListItemIcon>
{listItem('Clear Cache')}
</ListItemButton>
</List>
</Container>
<Footer />
</>
)
}

View File

@ -0,0 +1,78 @@
import {
List,
ListItemButton,
ListItemIcon,
ListItemText,
ListSubheader,
useTheme
} from '@mui/material'
import { launch as launchNostrLoginDialog } from 'nostr-login'
import { Container } from '../../../components/Container'
import PeopleIcon from '@mui/icons-material/People'
import ImportExportIcon from '@mui/icons-material/ImportExport'
import { useAppSelector } from '../../../hooks/store'
import { NostrLoginAuthMethod } from '../../../store/auth/types'
export const NostrLoginPage = () => {
const theme = useTheme()
const nostrLoginAuthMethod = useAppSelector(
(state) => state.auth?.nostrLoginAuthMethod
)
return (
<Container>
<List
sx={{
width: '100%',
bgcolor: 'background.paper'
}}
subheader={
<ListSubheader
sx={{
fontSize: '1.5rem',
borderBottom: '0.5px solid',
paddingBottom: 2,
paddingTop: 2,
zIndex: 2
}}
>
Nostr Settings
</ListSubheader>
}
>
<ListItemButton
onClick={() => {
launchNostrLoginDialog('switch-account')
}}
>
<ListItemIcon>
<PeopleIcon />
</ListItemIcon>
<ListItemText
primary={'Nostr Login Accounts'}
sx={{
color: theme.palette.text.primary
}}
/>
</ListItemButton>
{nostrLoginAuthMethod === NostrLoginAuthMethod.Local && (
<ListItemButton
onClick={() => {
launchNostrLoginDialog('import')
}}
>
<ListItemIcon>
<ImportExportIcon />
</ListItemIcon>
<ListItemText
primary={'Import / Export Keys'}
sx={{
color: theme.palette.text.primary
}}
/>
</ListItemButton>
)}
</List>
</Container>
)
}

View File

@ -12,31 +12,38 @@ import {
useTheme
} from '@mui/material'
import { UnsignedEvent, nip19, kinds, VerifiedEvent, Event } from 'nostr-tools'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import React, { useEffect, useRef, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { toast } from 'react-toastify'
import { MetadataController, NostrController } from '../../../controllers'
import { NostrJoiningBlock, ProfileMetadata } from '../../../types'
import styles from './style.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { State } from '../../../store/rootReducer'
import { useAppDispatch, useAppSelector } from '../../../hooks/store'
import { LoadingButton } from '@mui/lab'
import { Dispatch } from '../../../store/store'
import { setMetadataEvent } from '../../../store/actions'
import { LoadingSpinner } from '../../../components/LoadingSpinner'
import { LoginMethods } from '../../../store/auth/types'
import { LoginMethod, NostrLoginAuthMethod } from '../../../store/auth/types'
import { SmartToy } from '@mui/icons-material'
import { getRoboHashPicture, unixNow } from '../../../utils'
import {
getNostrJoiningBlockNumber,
getRoboHashPicture,
unixNow
} from '../../../utils'
import { Container } from '../../../components/Container'
import { Footer } from '../../../components/Footer/Footer'
import LaunchIcon from '@mui/icons-material/Launch'
import { launch as launchNostrLoginDialog } from 'nostr-login'
export const ProfileSettingsPage = () => {
const theme = useTheme()
const { npub } = useParams()
const dispatch: Dispatch = useDispatch()
const dispatch: Dispatch = useAppDispatch()
const metadataController = useMemo(() => new MetadataController(), [])
const metadataController = MetadataController.getInstance()
const nostrController = NostrController.getInstance()
const [pubkey, setPubkey] = useState<string>()
@ -44,10 +51,12 @@ export const ProfileSettingsPage = () => {
useState<NostrJoiningBlock | null>(null)
const [profileMetadata, setProfileMetadata] = useState<ProfileMetadata>()
const [savingProfileMetadata, setSavingProfileMetadata] = useState(false)
const metadataState = useSelector((state: State) => state.metadata)
const keys = useSelector((state: State) => state.auth?.keyPair)
const { usersPubkey, loginMethod } = useSelector((state: State) => state.auth)
const userRobotImage = useSelector((state: State) => state.userRobotImage)
const metadataState = useAppSelector((state) => state.metadata)
const keys = useAppSelector((state) => state.auth?.keyPair)
const { usersPubkey, loginMethod, nostrLoginAuthMethod } = useAppSelector(
(state) => state.auth
)
const userRobotImage = useAppSelector((state) => state.userRobotImage)
const [isUsersOwnProfile, setIsUsersOwnProfile] = useState(false)
@ -71,8 +80,7 @@ export const ProfileSettingsPage = () => {
useEffect(() => {
if (pubkey) {
metadataController
.getNostrJoiningBlockNumber(pubkey)
getNostrJoiningBlockNumber(pubkey)
.then((res) => {
setNostrJoiningBlock(res)
})
@ -283,7 +291,8 @@ export const ProfileSettingsPage = () => {
sx={{
paddingBottom: 1,
paddingTop: 1,
fontSize: '1.5rem'
fontSize: '1.5rem',
zIndex: 2
}}
className={styles.subHeader}
>
@ -359,7 +368,7 @@ export const ProfileSettingsPage = () => {
<>
{usersPubkey &&
copyItem(nip19.npubEncode(usersPubkey), 'Public Key')}
{loginMethod === LoginMethods.privateKey &&
{loginMethod === LoginMethod.privateKey &&
keys &&
keys.private &&
copyItem(
@ -369,6 +378,33 @@ export const ProfileSettingsPage = () => {
)}
</>
)}
{isUsersOwnProfile && (
<>
{loginMethod === LoginMethod.nostrLogin &&
nostrLoginAuthMethod === NostrLoginAuthMethod.Local && (
<ListItem
sx={{ marginTop: 1 }}
onClick={() => {
launchNostrLoginDialog('import')
}}
>
<TextField
label="Private Key (nostr-login)"
defaultValue="••••••••••••••••••••••••••••••••••••••••••••••••••"
size="small"
className={styles.textField}
disabled
type={'password'}
InputProps={{
endAdornment: (
<LaunchIcon className={styles.copyItem} />
)
}}
/>
</ListItem>
)}
</>
)}
</div>
)}
</List>
@ -382,6 +418,7 @@ export const ProfileSettingsPage = () => {
</LoadingButton>
)}
</Container>
<Footer />
</>
)
}

View File

@ -12,138 +12,45 @@ import ListItemText from '@mui/material/ListItemText'
import Switch from '@mui/material/Switch'
import { useEffect, useState } from 'react'
import { toast } from 'react-toastify'
import { NostrController } from '../../../controllers'
import { useAppDispatch, useAppSelector } from '../../../hooks'
import {
setRelayMapAction,
setRelayMapUpdatedAction
} from '../../../store/actions'
import {
RelayConnectionState,
RelayFee,
RelayInfoObject,
RelayMap
} from '../../../types'
import { Container } from '../../../components/Container'
import { relayController } from '../../../controllers'
import { useAppDispatch, useAppSelector, useDidMount } from '../../../hooks'
import { setRelayMapAction } from '../../../store/actions'
import { RelayConnectionState, RelayFee, RelayInfo } from '../../../types'
import {
capitalizeFirstLetter,
compareObjects,
getRelayInfo,
getRelayMap,
hexToNpub,
publishRelayMap,
shorten
} from '../../../utils'
import styles from './style.module.scss'
import { Container } from '../../../components/Container'
import { Footer } from '../../../components/Footer/Footer'
export const RelaysPage = () => {
const nostrController = NostrController.getInstance()
const relaysState = useAppSelector((state) => state.relays)
const usersPubkey = useAppSelector((state) => state.auth?.usersPubkey)
const dispatch = useAppDispatch()
const [newRelayURI, setNewRelayURI] = useState<string>()
const [newRelayURIerror, setNewRelayURIerror] = useState<string>()
const [relayMap, setRelayMap] = useState<RelayMap | undefined>(
relaysState?.map
)
const [relaysInfo, setRelaysInfo] = useState<RelayInfoObject | undefined>(
relaysState?.info
)
const [displayRelaysInfo, setDisplayRelaysInfo] = useState<string[]>([])
const [relaysConnectionStatus, setRelaysConnectionStatus] = useState(
relaysState?.connectionStatus
)
const relayMap = useAppSelector((state) => state.relays?.map)
const relaysInfo = useAppSelector((state) => state.relays?.info)
const webSocketPrefix = 'wss://'
// Update relay connection status
useEffect(() => {
if (
!compareObjects(relaysConnectionStatus, relaysState?.connectionStatus)
) {
setRelaysConnectionStatus(relaysState?.connectionStatus)
}
}, [relaysConnectionStatus, relaysState?.connectionStatus])
useEffect(() => {
if (!compareObjects(relaysInfo, relaysState?.info)) {
setRelaysInfo(relaysState?.info)
}
}, [relaysInfo, relaysState?.info])
useEffect(() => {
if (!compareObjects(relayMap, relaysState?.map)) {
setRelayMap(relaysState?.map)
}
}, [relayMap, relaysState?.map])
useEffect(() => {
let isMounted = false
const fetchData = async () => {
if (usersPubkey) {
isMounted = true
// call async func to fetch relay map
const newRelayMap = await nostrController.getRelayMap(usersPubkey)
// handle fetched relay map
if (isMounted) {
if (
!relaysState?.mapUpdated ||
(newRelayMap?.mapUpdated !== undefined &&
newRelayMap?.mapUpdated > relaysState?.mapUpdated)
) {
if (
!relaysState?.map ||
!compareObjects(relaysState.map, newRelayMap)
) {
setRelayMap(newRelayMap.map)
dispatch(setRelayMapAction(newRelayMap.map))
} else {
// Update relay map updated timestamp
dispatch(setRelayMapUpdatedAction())
}
}
useDidMount(() => {
if (usersPubkey) {
getRelayMap(usersPubkey).then((newRelayMap) => {
if (!compareObjects(relayMap, newRelayMap.map)) {
dispatch(setRelayMapAction(newRelayMap.map))
}
}
})
}
// Publishing relay map can take some time.
// This is why data fetch should happen only if relay map was received more than 5 minutes ago.
if (
usersPubkey &&
(!relaysState?.mapUpdated ||
Date.now() - relaysState?.mapUpdated > 5 * 60 * 1000) // 5 minutes
) {
fetchData()
// Update relay connection status
if (relaysConnectionStatus) {
const notConnectedRelays = Object.keys(relaysConnectionStatus).filter(
(key) =>
relaysConnectionStatus[key] === RelayConnectionState.NotConnected
)
if (notConnectedRelays.length) {
nostrController.connectToRelays(notConnectedRelays)
}
}
}
// cleanup func
return () => {
isMounted = false
}
}, [
dispatch,
usersPubkey,
relaysState?.map,
relaysState?.mapUpdated,
nostrController,
relaysConnectionStatus
])
})
useEffect(() => {
// Display notification if an empty relay map has been received
@ -175,24 +82,23 @@ export const RelaysPage = () => {
if (usersPubkey) {
// Publish updated relay map.
const relayMapPublishingRes = await nostrController
.publishRelayMap(relayMapCopy, usersPubkey, [relay])
.catch((err) => handlePublishRelayMapError(err))
const relayMapPublishingRes = await publishRelayMap(
relayMapCopy,
usersPubkey,
[relay]
).catch((err) => handlePublishRelayMapError(err))
if (relayMapPublishingRes) {
toast.success(relayMapPublishingRes)
setRelayMap(relayMapCopy)
dispatch(setRelayMapAction(relayMapCopy))
}
}
nostrController.disconnectFromRelays([relay])
}
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handlePublishRelayMapError = (err: any) => {
const errorPrefix = 'Error while publishing Relay Map'
@ -224,15 +130,14 @@ export const RelaysPage = () => {
if (usersPubkey) {
// Publish updated relay map
const relayMapPublishingRes = await nostrController
.publishRelayMap(relayMapCopy, usersPubkey)
.catch((err) => handlePublishRelayMapError(err))
const relayMapPublishingRes = await publishRelayMap(
relayMapCopy,
usersPubkey
).catch((err) => handlePublishRelayMapError(err))
if (relayMapPublishingRes) {
toast.success(relayMapPublishingRes)
setRelayMap(relayMapCopy)
dispatch(setRelayMapAction(relayMapCopy))
}
}
@ -256,29 +161,25 @@ export const RelaysPage = () => {
)
}
} else if (relayURI && usersPubkey) {
const connectionStatus = await nostrController.connectToRelays([relayURI])
const relay = await relayController.connectRelay(relayURI)
if (
connectionStatus &&
connectionStatus[relayURI] &&
connectionStatus[relayURI] === RelayConnectionState.Connected
) {
if (relay && relay.connected) {
const relayMapCopy = JSON.parse(JSON.stringify(relayMap))
relayMapCopy[relayURI] = { write: true, read: true }
// Publish updated relay map
const relayMapPublishingRes = await nostrController
.publishRelayMap(relayMapCopy, usersPubkey)
.catch((err) => handlePublishRelayMapError(err))
const relayMapPublishingRes = await publishRelayMap(
relayMapCopy,
usersPubkey
).catch((err) => handlePublishRelayMapError(err))
if (relayMapPublishingRes) {
setRelayMap(relayMapCopy)
setNewRelayURI('')
dispatch(setRelayMapAction(relayMapCopy))
nostrController.getRelayInfo([relayURI])
getRelayInfo([relayURI])
toast.success(relayMapPublishingRes)
}
@ -292,29 +193,6 @@ export const RelaysPage = () => {
}
}
// Handle relay open and close state
const handleRelayInfo = (relay: string) => {
if (relaysInfo) {
const info = relaysInfo[relay]
if (info) {
let displayRelaysInfoCopy: string[] = JSON.parse(
JSON.stringify(displayRelaysInfo)
)
if (displayRelaysInfoCopy.includes(relay)) {
displayRelaysInfoCopy = displayRelaysInfoCopy.filter(
(rel) => rel !== relay
)
} else {
displayRelaysInfoCopy.push(relay)
}
setDisplayRelaysInfo(displayRelaysInfoCopy)
}
}
}
return (
<Container className={styles.container}>
<Box className={styles.relayAddContainer}>
@ -343,177 +221,214 @@ export const RelaysPage = () => {
</Box>
{relayMap && (
<Box className={styles.relaysContainer}>
{Object.keys(relayMap).map((relay, i) => (
<Box className={styles.relay} key={`relay_${i}`}>
<List>
<ListItem>
<span
className={[
styles.connectionStatus,
relaysConnectionStatus
? relaysConnectionStatus[relay] ===
RelayConnectionState.Connected
? styles.connectionStatusConnected
: styles.connectionStatusNotConnected
: styles.connectionStatusUnknown
].join(' ')}
/>
{relaysInfo &&
relaysInfo[relay] &&
relaysInfo[relay].limitation &&
relaysInfo[relay].limitation?.payment_required && (
<Tooltip title="Paid Relay" arrow placement="top">
<ElectricBoltIcon
className={styles.lightningIcon}
color="warning"
onClick={() => handleRelayInfo(relay)}
/>
</Tooltip>
)}
<ListItemText primary={relay} />
<Box
className={styles.leaveRelayContainer}
onClick={() => handleLeaveRelay(relay)}
>
<LogoutIcon />
<span>Leave</span>
</Box>
</ListItem>
<Divider className={styles.relayDivider} />
<ListItem>
<ListItemText
primary="Publish to this relay?"
secondary={
relaysInfo && relaysInfo[relay] ? (
<span
onClick={() => handleRelayInfo(relay)}
className={styles.showInfo}
>
Show info{' '}
{displayRelaysInfo.includes(relay) ? (
<KeyboardArrowUpIcon
className={styles.showInfoIcon}
/>
) : (
<KeyboardArrowDownIcon
className={styles.showInfoIcon}
/>
)}
</span>
) : (
''
)
}
/>
<Switch
checked={relayMap[relay].write}
onChange={(event) => handleRelayWriteChange(relay, event)}
/>
</ListItem>
{displayRelaysInfo.includes(relay) && (
<>
<Divider className={styles.relayDivider} />
<ListItem>
<Box className={styles.relayInfoContainer}>
{relaysInfo &&
relaysInfo[relay] &&
Object.keys(relaysInfo[relay]).map((key: string) => {
const infoTitle = capitalizeFirstLetter(
key.replace('_', ' ')
)
let infoValue = (relaysInfo[relay] as any)[key]
switch (key) {
case 'pubkey':
infoValue = shorten(hexToNpub(infoValue), 15)
break
case 'limitation':
infoValue = (
<ul key={`${i}_${key}`}>
{Object.keys(infoValue).map((valueKey) => (
<li key={`${i}_${key}_${valueKey}`}>
<span
className={styles.relayInfoSubTitle}
>
{capitalizeFirstLetter(
valueKey.split('_').join(' ')
)}
:
</span>{' '}
{`${infoValue[valueKey]}`}
</li>
))}
</ul>
)
break
case 'fees':
infoValue = (
<ul>
{Object.keys(infoValue).map((valueKey) => (
<li key={`${i}_${key}_${valueKey}`}>
<span
className={styles.relayInfoSubTitle}
>
{capitalizeFirstLetter(
valueKey.split('_').join(' ')
)}
:
</span>{' '}
{`${infoValue[valueKey].map((fee: RelayFee) => `${fee.amount} ${fee.unit}`)}`}
</li>
))}
</ul>
)
break
default:
break
}
if (Array.isArray(infoValue)) {
infoValue = infoValue.join(', ')
}
return (
<span key={`${i}_${key}_container`}>
<span className={styles.relayInfoTitle}>
{infoTitle}:
</span>{' '}
{infoValue}
{key === 'pubkey' ? (
<ContentCopyIcon
className={styles.copyItem}
onClick={() => {
navigator.clipboard.writeText(
hexToNpub(
(relaysInfo[relay] as any)[key]
)
)
toast.success('Copied to clipboard', {
autoClose: 1000,
hideProgressBar: true
})
}}
/>
) : null}
</span>
)
})}
</Box>
</ListItem>
</>
)}
</List>
</Box>
{Object.keys(relayMap).map((relay) => (
<RelayItem
key={relay}
relayURI={relay}
isWriteRelay={relayMap[relay].write}
relayInfo={relaysInfo ? relaysInfo[relay] : undefined}
handleLeaveRelay={handleLeaveRelay}
handleRelayWriteChange={handleRelayWriteChange}
/>
))}
</Box>
)}
<Footer />
</Container>
)
}
type RelayItemProp = {
relayURI: string
isWriteRelay: boolean
relayInfo?: RelayInfo
handleLeaveRelay: (relay: string) => void
handleRelayWriteChange: (
relay: string,
event: React.ChangeEvent<HTMLInputElement>
) => Promise<void>
}
const RelayItem = ({
relayURI,
isWriteRelay,
relayInfo,
handleLeaveRelay,
handleRelayWriteChange
}: RelayItemProp) => {
const [relayConnectionStatus, setRelayConnectionStatus] =
useState<RelayConnectionState>()
const [displayRelayInfo, setDisplayRelayInfo] = useState(false)
useDidMount(() => {
relayController.connectRelay(relayURI).then((relay) => {
if (relay && relay.connected) {
setRelayConnectionStatus(RelayConnectionState.Connected)
} else {
setRelayConnectionStatus(RelayConnectionState.NotConnected)
}
})
})
return (
<>
<Box className={styles.relay}>
<List>
<ListItem>
<span
className={[
styles.connectionStatus,
relayConnectionStatus
? relayConnectionStatus === RelayConnectionState.Connected
? styles.connectionStatusConnected
: styles.connectionStatusNotConnected
: styles.connectionStatusUnknown
].join(' ')}
/>
{relayInfo &&
relayInfo.limitation &&
relayInfo.limitation?.payment_required && (
<Tooltip title="Paid Relay" arrow placement="top">
<ElectricBoltIcon
className={styles.lightningIcon}
color="warning"
onClick={() => setDisplayRelayInfo((prev) => !prev)}
/>
</Tooltip>
)}
<ListItemText primary={relayURI} />
<Box
className={styles.leaveRelayContainer}
onClick={() => handleLeaveRelay(relayURI)}
>
<LogoutIcon />
<span>Leave</span>
</Box>
</ListItem>
<Divider className={styles.relayDivider} />
<ListItem>
<ListItemText
primary="Publish to this relay?"
secondary={
relayInfo ? (
<span
onClick={() => setDisplayRelayInfo((prev) => !prev)}
className={styles.showInfo}
>
Show info{' '}
{displayRelayInfo ? (
<KeyboardArrowUpIcon className={styles.showInfoIcon} />
) : (
<KeyboardArrowDownIcon className={styles.showInfoIcon} />
)}
</span>
) : (
''
)
}
/>
<Switch
checked={isWriteRelay}
onChange={(event) => handleRelayWriteChange(relayURI, event)}
/>
</ListItem>
{displayRelayInfo && (
<>
<Divider className={styles.relayDivider} />
<ListItem>
<Box className={styles.relayInfoContainer}>
{relayInfo &&
Object.keys(relayInfo).map((key: string) => {
const infoTitle = capitalizeFirstLetter(
key.replace('_', ' ')
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let infoValue = (relayInfo as any)[key]
switch (key) {
case 'pubkey':
infoValue = shorten(hexToNpub(infoValue), 15)
break
case 'limitation':
infoValue = (
<ul>
{Object.keys(infoValue).map((valueKey) => (
<li key={`${relayURI}_${key}_${valueKey}`}>
<span className={styles.relayInfoSubTitle}>
{capitalizeFirstLetter(
valueKey.split('_').join(' ')
)}
:
</span>{' '}
{`${infoValue[valueKey]}`}
</li>
))}
</ul>
)
break
case 'fees':
infoValue = (
<ul>
{Object.keys(infoValue).map((valueKey) => (
<li key={`${relayURI}_${key}_${valueKey}`}>
<span className={styles.relayInfoSubTitle}>
{capitalizeFirstLetter(
valueKey.split('_').join(' ')
)}
:
</span>{' '}
{`${infoValue[valueKey].map((fee: RelayFee) => `${fee.amount} ${fee.unit}`)}`}
</li>
))}
</ul>
)
break
default:
break
}
if (Array.isArray(infoValue)) {
infoValue = infoValue.join(', ')
}
return (
<span key={`${relayURI}_${key}_container`}>
<span className={styles.relayInfoTitle}>
{infoTitle}:
</span>{' '}
{infoValue}
{key === 'pubkey' ? (
<ContentCopyIcon
className={styles.copyItem}
onClick={() => {
navigator.clipboard.writeText(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
hexToNpub((relayInfo as any)[key])
)
toast.success('Copied to clipboard', {
autoClose: 1000,
hideProgressBar: true
})
}}
/>
) : null}
</span>
)
})}
</Box>
</ListItem>
</>
)}
</List>
</Box>
</>
)
}

View File

@ -6,13 +6,12 @@ import _ from 'lodash'
import { MuiFileInput } from 'mui-file-input'
import { Event, verifyEvent } from 'nostr-tools'
import { useCallback, useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import { useLocation, useNavigate } from 'react-router-dom'
import { useAppSelector } from '../../hooks/store'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { NostrController } from '../../controllers'
import { appPublicRoutes } from '../../routes'
import { State } from '../../store/rootReducer'
import { CreateSignatureEventContent, Meta, SignedEvent } from '../../types'
import {
decryptArrayBuffer,
@ -32,15 +31,15 @@ import {
readContentOfZipEntry,
sendNotification,
signEventForMetaFile,
updateUsersAppData
updateUsersAppData,
findOtherUserMarks,
timeout
} from '../../utils'
import { Container } from '../../components/Container'
import { DisplayMeta } from './internal/displayMeta'
import styles from './style.module.scss'
import { PdfFile } from '../../types/drawing.ts'
import { convertToPdfFile } from '../../utils/pdf.ts'
import { CurrentUserMark, Mark } from '../../types/mark.ts'
import { getLastSignersSig } from '../../utils/sign.ts'
import { getLastSignersSig, isFullySigned } from '../../utils/sign.ts'
import {
filterMarksByPubkey,
getCurrentUserMarks,
@ -48,8 +47,14 @@ import {
updateMarks
} from '../../utils'
import PdfMarking from '../../components/PDFView/PdfMarking.tsx'
import { getZipWithFiles } from '../../utils/file.ts'
import {
convertToSigitFile,
getZipWithFiles,
SigitFile
} from '../../utils/file.ts'
import { ARRAY_BUFFER, DEFLATE } from '../../utils/const.ts'
import { generateTimestamp } from '../../utils/opentimestamps.ts'
enum SignedStatus {
Fully_Signed,
User_Is_Next_Signer,
@ -59,23 +64,45 @@ enum SignedStatus {
export const SignPage = () => {
const navigate = useNavigate()
const location = useLocation()
const params = useParams()
const usersAppData = useAppSelector((state) => state.userAppData)
/**
* Received from `location.state`
*
* uploadedZip will be received from home page when a user uploads a sigit zip wrapper that contains keys.json
* arrayBuffer will be received in navigation from create page in offline mode
* meta will be received in navigation from create & home page in online mode
* arrayBuffer (decryptedArrayBuffer) will be received in navigation from create page in offline mode
* meta (metaInNavState) will be received in navigation from create & home page in online mode
*/
const {
meta: metaInNavState,
arrayBuffer: decryptedArrayBuffer,
uploadedZip
} = location.state || {}
let metaInNavState = location?.state?.meta || undefined
const { arrayBuffer: decryptedArrayBuffer, uploadedZip } = location.state || {
decryptedArrayBuffer: undefined,
uploadedZip: undefined
}
/**
* If userAppData (redux) is available, and we have the route param (sigit id)
* which is actually a `createEventId`, we will fetch a `sigit`
* based on the provided route ID and set fetched `sigit` to the `metaInNavState`
*/
if (usersAppData) {
const sigitCreateId = params.id
if (sigitCreateId) {
const sigit = usersAppData.sigits[sigitCreateId]
if (sigit) {
metaInNavState = sigit
}
}
}
const [displayInput, setDisplayInput] = useState(false)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [files, setFiles] = useState<{ [filename: string]: PdfFile }>({})
const [files, setFiles] = useState<{ [filename: string]: SigitFile }>({})
const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
@ -102,19 +129,19 @@ export const SignPage = () => {
// This state variable indicates whether the logged-in user is a signer, a creator, or neither.
const [isSignerOrCreator, setIsSignerOrCreator] = useState(false)
const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)
const usersPubkey = useAppSelector((state) => state.auth.usersPubkey)
const [authUrl, setAuthUrl] = useState<string>()
const nostrController = NostrController.getInstance()
const [currentUserMarks, setCurrentUserMarks] = useState<CurrentUserMark[]>(
[]
)
const [isReadyToSign, setIsReadyToSign] = useState(false)
const [isMarksCompleted, setIsMarksCompleted] = useState(false)
const [otherUserMarks, setOtherUserMarks] = useState<Mark[]>([])
useEffect(() => {
if (signers.length > 0) {
// check if all signers have signed then its fully signed
if (signers.every((signer) => signedBy.includes(signer))) {
if (isFullySigned(signers, signedBy)) {
setSignedStatus(SignedStatus.Fully_Signed)
} else {
for (const signer of signers) {
@ -209,8 +236,10 @@ export const SignPage = () => {
)
const signedMarks = extractMarksFromSignedMeta(meta)
const currentUserMarks = getCurrentUserMarks(metaMarks, signedMarks)
const otherUserMarks = findOtherUserMarks(signedMarks, usersPubkey!)
setOtherUserMarks(otherUserMarks)
setCurrentUserMarks(currentUserMarks)
setIsReadyToSign(isCurrentUserMarksComplete(currentUserMarks))
setIsMarksCompleted(isCurrentUserMarksComplete(currentUserMarks))
}
setSignedBy(Object.keys(meta.docSignatures) as `npub1${string}`[])
@ -236,9 +265,11 @@ export const SignPage = () => {
if (!arrayBuffer) return
const blob = new Blob([arrayBuffer])
saveAs(blob, `exported-${unixNow()}.sigit.zip`)
} catch (error: any) {
} catch (error) {
console.log('error in zip:>> ', error)
toast.error(error.message || 'Error occurred in generating zip file')
if (error instanceof Error) {
toast.error(error.message || 'Error occurred in generating zip file')
}
}
}
@ -263,22 +294,10 @@ export const SignPage = () => {
const { keys, sender } = parsedKeysJson
for (const key of keys) {
// Set up event listener for authentication event
nostrController.on('nsecbunker-auth', (url) => {
setAuthUrl(url)
})
// Set up timeout promise to handle encryption timeout
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => {
reject(new Error('Timeout occurred'))
}, 60000) // Timeout duration = 60 seconds
})
// decrypt the encryptionKey, with timeout
// decrypt the encryptionKey, with timeout (duration = 60 seconds)
const encryptionKey = await Promise.race([
nostrController.nip04Decrypt(sender, key),
timeoutPromise
timeout(60000)
])
.then((res) => {
return res
@ -287,9 +306,6 @@ export const SignPage = () => {
console.log('err :>> ', err)
return null
})
.finally(() => {
setAuthUrl(undefined) // Clear authentication URL
})
// Return if encryption failed
if (!encryptionKey) continue
@ -396,7 +412,7 @@ export const SignPage = () => {
return
}
const files: { [filename: string]: PdfFile } = {}
const files: { [filename: string]: SigitFile } = {}
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files).map((entry) => entry.name)
@ -410,8 +426,7 @@ export const SignPage = () => {
)
if (arrayBuffer) {
files[fileName] = await convertToPdfFile(arrayBuffer, fileName)
files[fileName] = await convertToSigitFile(arrayBuffer, fileName)
const hash = await getHash(arrayBuffer)
if (hash) {
fileHashes[fileName] = hash
@ -456,25 +471,25 @@ export const SignPage = () => {
const zip = await loadZip(decryptedZipFile)
if (!zip) return
const files: { [filename: string]: PdfFile } = {}
const files: { [filename: string]: SigitFile } = {}
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files)
.filter((entry) => entry.name.startsWith('files/') && !entry.dir)
.map((entry) => entry.name)
.map((entry) => entry.replace(/^files\//, ''))
// generate hashes for all entries in files folder of zipArchive
// these hashes can be used to verify the originality of files
for (const fileName of fileNames) {
for (const zipFilePath of fileNames) {
const arrayBuffer = await readContentOfZipEntry(
zip,
fileName,
zipFilePath,
'arraybuffer'
)
const fileName = zipFilePath.replace(/^files\//, '')
if (arrayBuffer) {
files[fileName] = await convertToPdfFile(arrayBuffer, fileName)
files[fileName] = await convertToSigitFile(arrayBuffer, fileName)
// generate hashes for all entries in files folder of zipArchive
// these hashes can be used to verify the originality of files
const hash = await getHash(arrayBuffer)
if (hash) {
fileHashes[fileName] = hash
@ -522,7 +537,11 @@ export const SignPage = () => {
setIsLoading(true)
const arrayBuffer = await decrypt(selectedFile)
if (!arrayBuffer) return
if (!arrayBuffer) {
setIsLoading(false)
toast.error('Error decrypting file')
return
}
handleDecryptedArrayBuffer(arrayBuffer)
}
@ -535,16 +554,27 @@ export const SignPage = () => {
setLoadingSpinnerDesc('Signing nostr event')
const prevSig = getPrevSignersSig(hexToNpub(usersPubkey!))
if (!prevSig) return
if (!prevSig) {
setIsLoading(false)
toast.error('Previous signature is invalid')
return
}
const marks = getSignerMarksForMeta()
if (!marks) return
const marks = getSignerMarksForMeta() || []
const signedEvent = await signEventForMeta({ prevSig, marks })
if (!signedEvent) return
const updatedMeta = updateMetaSignatures(meta, signedEvent)
setLoadingSpinnerDesc('Generating an open timestamp.')
const timestamp = await generateTimestamp(signedEvent.id)
if (timestamp) {
updatedMeta.timestamps = [...(updatedMeta.timestamps || []), timestamp]
updatedMeta.modifiedAt = unixNow()
}
if (await isOnline()) {
await handleOnlineFlow(updatedMeta)
} else {
@ -754,14 +784,9 @@ export const SignPage = () => {
2
)
const zip = new JSZip()
const zip = await getZipWithFiles(meta, files)
zip.file('meta.json', stringifiedMeta)
for (const [fileName, pdf] of Object.entries(files)) {
zip.file(`files/${fileName}`, await pdf.file.arrayBuffer())
}
const arrayBuffer = await zip
.generateAsync({
type: 'arraybuffer',
@ -787,19 +812,14 @@ export const SignPage = () => {
navigate(appPublicRoutes.verify)
}
const handleExportSigit = async () => {
const handleEncryptedExport = async () => {
if (Object.entries(files).length === 0 || !meta) return
const zip = new JSZip()
const stringifiedMeta = JSON.stringify(meta, null, 2)
const zip = await getZipWithFiles(meta, files)
zip.file('meta.json', stringifiedMeta)
for (const [fileName, pdf] of Object.entries(files)) {
zip.file(`files/${fileName}`, await pdf.file.arrayBuffer())
}
const arrayBuffer = await zip
.generateAsync({
type: 'arraybuffer',
@ -861,103 +881,94 @@ export const SignPage = () => {
}
}
if (authUrl) {
return (
<iframe
title="Nsecbunker auth"
src={authUrl}
width="100%"
height="500px"
/>
)
}
if (isLoading) {
return <LoadingSpinner desc={loadingSpinnerDesc} />
}
if (isReadyToSign) {
if (!isMarksCompleted && signedStatus === SignedStatus.User_Is_Next_Signer) {
return (
<>
<Container className={styles.container}>
{displayInput && (
<>
<Typography component="label" variant="h6">
Select sigit file
</Typography>
<Box className={styles.inputBlock}>
<MuiFileInput
placeholder="Select file"
inputProps={{ accept: '.sigit.zip' }}
value={selectedFile}
onChange={(value) => setSelectedFile(value)}
/>
</Box>
{selectedFile && (
<Box sx={{ mt: 2, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleDecrypt} variant="contained">
Decrypt
</Button>
</Box>
)}
</>
)}
{submittedBy && Object.entries(files).length > 0 && meta && (
<>
<DisplayMeta
meta={meta}
files={files}
submittedBy={submittedBy}
signers={signers}
viewers={viewers}
creatorFileHashes={creatorFileHashes}
currentFileHashes={currentFileHashes}
signedBy={signedBy}
nextSigner={nextSinger}
getPrevSignersSig={getPrevSignersSig}
/>
{signedStatus === SignedStatus.Fully_Signed && (
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExport} variant="contained">
Export
</Button>
</Box>
)}
{signedStatus === SignedStatus.User_Is_Next_Signer && (
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleSign} variant="contained">
Sign
</Button>
</Box>
)}
{isSignerOrCreator && (
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExportSigit} variant="contained">
Export Sigit
</Button>
</Box>
)}
</>
)}
</Container>
</>
<PdfMarking
files={getCurrentUserFiles(files, currentFileHashes, creatorFileHashes)}
currentUserMarks={currentUserMarks}
setIsMarksCompleted={setIsMarksCompleted}
setCurrentUserMarks={setCurrentUserMarks}
setUpdatedMarks={setUpdatedMarks}
handleDownload={handleDownload}
otherUserMarks={otherUserMarks}
meta={meta}
/>
)
}
return (
<PdfMarking
files={getCurrentUserFiles(files, currentFileHashes)}
currentUserMarks={currentUserMarks}
setIsReadyToSign={setIsReadyToSign}
setCurrentUserMarks={setCurrentUserMarks}
setUpdatedMarks={setUpdatedMarks}
handleDownload={handleDownload}
/>
<>
<Container className={styles.container}>
{displayInput && (
<>
<Typography component="label" variant="h6">
Select sigit file
</Typography>
<Box className={styles.inputBlock}>
<MuiFileInput
placeholder="Select file"
inputProps={{ accept: '.sigit.zip' }}
value={selectedFile}
onChange={(value) => setSelectedFile(value)}
/>
</Box>
{selectedFile && (
<Box sx={{ mt: 2, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleDecrypt} variant="contained">
Decrypt
</Button>
</Box>
)}
</>
)}
{submittedBy && Object.entries(files).length > 0 && meta && (
<>
<DisplayMeta
meta={meta}
files={files}
submittedBy={submittedBy}
signers={signers}
viewers={viewers}
creatorFileHashes={creatorFileHashes}
currentFileHashes={currentFileHashes}
signedBy={signedBy}
nextSigner={nextSinger}
getPrevSignersSig={getPrevSignersSig}
/>
{signedStatus === SignedStatus.Fully_Signed && (
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExport} variant="contained">
Export Sigit
</Button>
</Box>
)}
{signedStatus === SignedStatus.User_Is_Next_Signer && (
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleSign} variant="contained">
Sign
</Button>
</Box>
)}
{isSignerOrCreator && (
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleEncryptedExport} variant="contained">
Export Encrypted Sigit
</Button>
</Box>
)}
</>
)}
</Container>
</>
)
}

View File

@ -32,13 +32,13 @@ import { useState, useEffect } from 'react'
import { toast } from 'react-toastify'
import { UserAvatar } from '../../../components/UserAvatar'
import { MetadataController } from '../../../controllers'
import { npubToHex, shorten, hexToNpub, parseJson } from '../../../utils'
import { npubToHex, hexToNpub, parseJson } from '../../../utils'
import styles from '../style.module.scss'
import { PdfFile } from '../../../types/drawing.ts'
import { SigitFile } from '../../../utils/file'
type DisplayMetaProps = {
meta: Meta
files: { [filename: string]: PdfFile }
files: { [fileName: string]: SigitFile }
submittedBy: string
signers: `npub1${string}`[]
viewers: `npub1${string}`[]
@ -105,7 +105,7 @@ export const DisplayMeta = ({
}, [signers, viewers])
useEffect(() => {
const metadataController = new MetadataController()
const metadataController = MetadataController.getInstance()
const hexKeys: string[] = [
npubToHex(submittedBy)!,
@ -141,14 +141,11 @@ export const DisplayMeta = ({
})
}
})
}, [users, submittedBy])
}, [users, submittedBy, metadata])
const downloadFile = async (filename: string) => {
const arrayBuffer = await files[filename].file.arrayBuffer()
if (!arrayBuffer) return
const blob = new Blob([arrayBuffer])
saveAs(blob, filename)
const downloadFile = async (fileName: string) => {
const file = files[fileName]
saveAs(file)
}
return (
@ -170,20 +167,7 @@ export const DisplayMeta = ({
<Typography variant="h6" sx={{ color: textColor }}>
Submitted By
</Typography>
{(function () {
const profile = metadata[submittedBy]
return (
<UserAvatar
pubkey={submittedBy}
name={
profile?.display_name ||
profile?.name ||
shorten(hexToNpub(submittedBy))
}
image={profile?.picture}
/>
)
})()}
<UserAvatar pubkey={submittedBy} isNameVisible={true} />
</ListItem>
<ListItem
sx={{
@ -283,14 +267,12 @@ type DisplayUserProps = {
const DisplayUser = ({
meta,
user,
metadata,
signedBy,
nextSigner,
getPrevSignersSig
}: DisplayUserProps) => {
const theme = useTheme()
const userMeta = metadata[user.pubkey]
const [userStatus, setUserStatus] = useState<UserStatus>(UserStatus.Pending)
const [prevSignatureStatus, setPreviousSignatureStatus] =
useState<PrevSignatureValidationEnum>(PrevSignatureValidationEnum.Pending)
@ -373,15 +355,7 @@ const DisplayUser = ({
return (
<TableRow>
<TableCell className={styles.tableCell}>
<UserAvatar
pubkey={user.pubkey}
name={
userMeta?.display_name ||
userMeta?.name ||
shorten(hexToNpub(user.pubkey))
}
image={userMeta?.picture}
/>
<UserAvatar pubkey={user.pubkey} isNameVisible={true} />
</TableCell>
<TableCell className={styles.tableCell}>{user.role}</TableCell>
<TableCell>

View File

@ -2,8 +2,6 @@
.container {
color: $text-color;
//width: 550px;
//max-width: 550px;
.inputBlock {
position: relative;
@ -16,6 +14,7 @@
border-bottom: 0.5px solid;
padding: 8px 16px;
font-size: 1.5rem;
z-index: 2;
}
.filesWrapper {
@ -64,10 +63,9 @@
display: flex;
justify-content: center;
align-items: center;
//z-index: 200;
}
.fixedBottomForm input[type="text"] {
.fixedBottomForm input[type='text'] {
width: 80%;
padding: 10px;
font-size: 16px;

View File

@ -1,85 +1,368 @@
import { Box, Button, Tooltip, Typography, useTheme } from '@mui/material'
import { Box, Button, Typography } from '@mui/material'
import JSZip from 'jszip'
import { MuiFileInput } from 'mui-file-input'
import { Event, verifyEvent } from 'nostr-tools'
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { NostrController } from '../../controllers'
import { CreateSignatureEventContent, Meta } from '../../types'
import {
DocSignatureEvent,
Meta,
SignedEvent,
OpenTimestamp,
OpenTimestampUpgradeVerifyResponse
} from '../../types'
import {
decryptArrayBuffer,
extractMarksFromSignedMeta,
getHash,
hexToNpub,
unixNow,
parseJson,
readContentOfZipEntry,
signEventForMetaFile,
shorten
getCurrentUserFiles,
updateUsersAppData,
npubToHex,
sendNotification
} from '../../utils'
import styles from './style.module.scss'
import { Cancel, CheckCircle } from '@mui/icons-material'
import { useLocation } from 'react-router-dom'
import axios from 'axios'
import { PdfFile } from '../../types/drawing.ts'
import {
addMarks,
convertToPdfBlob,
convertToPdfFile,
groupMarksByPage
} from '../../utils/pdf.ts'
import { State } from '../../store/rootReducer.ts'
import { useSelector } from 'react-redux'
import { FONT_SIZE, FONT_TYPE, inPx } from '../../utils/pdf.ts'
import { useAppSelector } from '../../hooks/store'
import { getLastSignersSig } from '../../utils/sign.ts'
import { saveAs } from 'file-saver'
import { Container } from '../../components/Container'
import { useSigitMeta } from '../../hooks/useSigitMeta.tsx'
import { StickySideColumns } from '../../layouts/StickySideColumns.tsx'
import { UsersDetails } from '../../components/UsersDetails.tsx/index.tsx'
import { UserAvatar } from '../../components/UserAvatar/index.tsx'
import { useSigitProfiles } from '../../hooks/useSigitProfiles.tsx'
import { TooltipChild } from '../../components/TooltipChild.tsx'
import { UsersDetails } from '../../components/UsersDetails.tsx'
import FileList from '../../components/FileList'
import { CurrentUserFile } from '../../types/file.ts'
import { Mark } from '../../types/mark.ts'
import React from 'react'
import {
convertToSigitFile,
getZipWithFiles,
SigitFile
} from '../../utils/file.ts'
import { FileDivider } from '../../components/FileDivider.tsx'
import { ExtensionFileBox } from '../../components/ExtensionFileBox.tsx'
import { useScale } from '../../hooks/useScale.tsx'
import {
faCircleInfo,
faFile,
faFileDownload
} from '@fortawesome/free-solid-svg-icons'
import { upgradeAndVerifyTimestamp } from '../../utils/opentimestamps.ts'
import _ from 'lodash'
import { MARK_TYPE_CONFIG } from '../../components/getMarkComponents.tsx'
interface PdfViewProps {
files: CurrentUserFile[]
currentFile: CurrentUserFile | null
parsedSignatureEvents: {
[signer: `npub1${string}`]: DocSignatureEvent
}
}
const SlimPdfView = ({
files,
currentFile,
parsedSignatureEvents
}: PdfViewProps) => {
const pdfRefs = useRef<(HTMLDivElement | null)[]>([])
const { from } = useScale()
useEffect(() => {
if (currentFile !== null && !!pdfRefs.current[currentFile.id]) {
pdfRefs.current[currentFile.id]?.scrollIntoView({
behavior: 'smooth'
})
}
}, [currentFile])
return (
<div className="files-wrapper">
{files.length > 0 ? (
files.map((currentUserFile, i) => {
const { hash, file, id } = currentUserFile
const signatureEvents = Object.keys(parsedSignatureEvents)
if (!hash) return
return (
<React.Fragment key={file.name}>
<div
id={file.name}
ref={(el) => (pdfRefs.current[id] = el)}
className="file-wrapper"
>
{file.isPdf &&
file.pages?.map((page, i) => {
const marks: Mark[] = []
signatureEvents.forEach((e) => {
const m = parsedSignatureEvents[
e as `npub1${string}`
].parsedContent?.marks.filter(
(m) => m.pdfFileHash == hash && m.location.page == i
)
if (m) {
marks.push(...m)
}
})
return (
<div className="image-wrapper" key={i}>
<img
draggable="false"
src={page.image}
alt={`page ${i} of ${file.name}`}
/>
{marks.map((m) => {
const { render: MarkRenderComponent } =
MARK_TYPE_CONFIG[m.type] || {}
return (
<div
className={`file-mark ${styles.mark}`}
key={m.id}
style={{
left: inPx(from(page.width, m.location.left)),
top: inPx(from(page.width, m.location.top)),
width: inPx(from(page.width, m.location.width)),
height: inPx(
from(page.width, m.location.height)
),
fontFamily: FONT_TYPE,
fontSize: inPx(from(page.width, FONT_SIZE))
}}
>
{typeof MarkRenderComponent !== 'undefined' && (
<MarkRenderComponent value={m.value} mark={m} />
)}
</div>
)
})}
</div>
)
})}
{file.isImage && (
<img
className="file-image"
src={file.objectUrl}
alt={file.name}
/>
)}
{!(file.isPdf || file.isImage) && (
<ExtensionFileBox extension={file.extension} />
)}
</div>
{i < files.length - 1 && <FileDivider />}
</React.Fragment>
)
})
) : (
<LoadingSpinner variant="small" />
)}
</div>
)
}
export const VerifyPage = () => {
const theme = useTheme()
const textColor = theme.palette.getContrastText(
theme.palette.background.paper
)
const location = useLocation()
/**
* uploadedZip will be received from home page when a user uploads a sigit zip wrapper that contains meta.json
* meta will be received in navigation from create & home page in online mode
*/
const { uploadedZip, meta } = location.state || {}
const usersPubkey = useAppSelector((state) => state.auth.usersPubkey)
const { submittedBy, zipUrl, encryptionKey, signers, viewers, fileHashes } =
useSigitMeta(meta)
const profiles = useSigitProfiles([
...(submittedBy ? [submittedBy] : []),
...signers,
...viewers
])
const nostrController = NostrController.getInstance()
const [isLoading, setIsLoading] = useState(false)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
/**
* uploadedZip will be received from home page when a user uploads a sigit zip wrapper that contains meta.json
* meta will be received in navigation from create & home page in online mode
*/
const { uploadedZip, meta: metaInNavState } = location.state || {}
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [currentFileHashes, setCurrentFileHashes] = useState<{
[key: string]: string | null
}>(fileHashes)
const [files, setFiles] = useState<{ [filename: string]: PdfFile }>({})
const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)
const nostrController = NostrController.getInstance()
useEffect(() => {
if (uploadedZip) {
setSelectedFile(uploadedZip)
} else if (meta && encryptionKey) {
}
}, [uploadedZip])
const [meta, setMeta] = useState<Meta>(metaInNavState)
const {
submittedBy,
zipUrl,
encryptionKey,
signers,
viewers,
fileHashes,
parsedSignatureEvents,
timestamps
} = useSigitMeta(meta)
const [files, setFiles] = useState<{ [filename: string]: SigitFile }>({})
const [currentFile, setCurrentFile] = useState<CurrentUserFile | null>(null)
const [currentFileHashes, setCurrentFileHashes] = useState<{
[key: string]: string | null
}>({})
const signTimestampEvent = async (signerContent: {
timestamps: OpenTimestamp[]
}): Promise<SignedEvent | null> => {
return await signEventForMetaFile(
JSON.stringify(signerContent),
nostrController,
setIsLoading
)
}
useEffect(() => {
if (Object.entries(files).length > 0) {
const tmp = getCurrentUserFiles(files, currentFileHashes, fileHashes)
setCurrentFile(tmp[0])
}
}, [currentFileHashes, fileHashes, files])
useEffect(() => {
if (
timestamps &&
timestamps.length > 0 &&
usersPubkey &&
submittedBy &&
parsedSignatureEvents
) {
if (timestamps.every((t) => !!t.verification)) {
return
}
const upgradeT = async (timestamps: OpenTimestamp[]) => {
try {
setLoadingSpinnerDesc('Upgrading your timestamps.')
const findCreatorTimestamp = (timestamps: OpenTimestamp[]) => {
if (usersPubkey === submittedBy) {
return timestamps[0]
}
}
const findSignerTimestamp = (timestamps: OpenTimestamp[]) => {
const parsedEvent = parsedSignatureEvents[hexToNpub(usersPubkey)]
if (parsedEvent?.id) {
return timestamps.find((t) => t.nostrId === parsedEvent.id)
}
}
/**
* Checks if timestamp verification has been achieved for the first time.
* Note that the upgrade flag is separate from verification. It is possible for a timestamp
* to not be upgraded, but to be verified for the first time.
* @param upgradedTimestamp
* @param timestamps
*/
const isNewlyVerified = (
upgradedTimestamp: OpenTimestampUpgradeVerifyResponse,
timestamps: OpenTimestamp[]
) => {
if (!upgradedTimestamp.verified) return false
const oldT = timestamps.find(
(t) => t.nostrId === upgradedTimestamp.timestamp.nostrId
)
if (!oldT) return false
if (!oldT.verification && upgradedTimestamp.verified) return true
}
const userTimestamps: OpenTimestamp[] = []
const creatorTimestamp = findCreatorTimestamp(timestamps)
if (creatorTimestamp) {
userTimestamps.push(creatorTimestamp)
}
const signerTimestamp = findSignerTimestamp(timestamps)
if (signerTimestamp) {
userTimestamps.push(signerTimestamp)
}
if (userTimestamps.every((t) => !!t.verification)) {
return
}
const upgradedUserTimestamps = await Promise.all(
userTimestamps.map(upgradeAndVerifyTimestamp)
)
const upgradedTimestamps = upgradedUserTimestamps
.filter((t) => t.upgraded || isNewlyVerified(t, userTimestamps))
.map((t) => {
const timestamp: OpenTimestamp = { ...t.timestamp }
if (t.verified) {
timestamp.verification = t.verification
}
return timestamp
})
if (upgradedTimestamps.length === 0) {
return
}
setLoadingSpinnerDesc('Signing a timestamp upgrade event.')
const signedEvent = await signTimestampEvent({
timestamps: upgradedTimestamps
})
if (!signedEvent) return
const finalTimestamps = timestamps.map((t) => {
const upgraded = upgradedTimestamps.find(
(tu) => tu.nostrId === t.nostrId
)
if (upgraded) {
return {
...upgraded,
signature: JSON.stringify(signedEvent, null, 2)
}
}
return t
})
const updatedMeta = _.cloneDeep(meta)
updatedMeta.timestamps = [...finalTimestamps]
updatedMeta.modifiedAt = unixNow()
const updatedEvent = await updateUsersAppData(updatedMeta)
if (!updatedEvent) return
const userSet = new Set<`npub1${string}`>()
signers.forEach((signer) => {
if (signer !== usersPubkey) {
userSet.add(signer)
}
})
viewers.forEach((viewer) => {
userSet.add(viewer)
})
const users = Array.from(userSet)
const promises = users.map((user) =>
sendNotification(npubToHex(user)!, updatedMeta)
)
await Promise.all(promises)
toast.success('Timestamp updates have been sent successfully.')
setMeta(meta)
} catch (err) {
console.error(err)
toast.error(
'There was an error upgrading or verifying your timestamps!'
)
}
}
upgradeT(timestamps)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [timestamps, submittedBy, parsedSignatureEvents])
useEffect(() => {
if (metaInNavState && encryptionKey) {
const processSigit = async () => {
setIsLoading(true)
@ -115,7 +398,7 @@ export const VerifyPage = () => {
if (!zip) return
const files: { [filename: string]: PdfFile } = {}
const files: { [fileName: string]: SigitFile } = {}
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files).map(
(entry) => entry.name
@ -131,7 +414,7 @@ export const VerifyPage = () => {
)
if (arrayBuffer) {
files[fileName] = await convertToPdfFile(
files[fileName] = await convertToSigitFile(
arrayBuffer,
fileName!
)
@ -164,7 +447,7 @@ export const VerifyPage = () => {
processSigit()
}
}, [encryptionKey, meta, uploadedZip, zipUrl])
}, [encryptionKey, metaInNavState, zipUrl])
const handleVerify = async () => {
if (!selectedFile) return
@ -178,6 +461,7 @@ export const VerifyPage = () => {
if (!zip) return
const files: { [filename: string]: SigitFile } = {}
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files)
.filter((entry) => entry.name.startsWith('files/') && !entry.dir)
@ -185,25 +469,27 @@ export const VerifyPage = () => {
// generate hashes for all entries in files folder of zipArchive
// these hashes can be used to verify the originality of files
for (const fileName of fileNames) {
for (const zipFilePath of fileNames) {
const arrayBuffer = await readContentOfZipEntry(
zip,
fileName,
zipFilePath,
'arraybuffer'
)
const fileName = zipFilePath.replace(/^files\//, '')
if (arrayBuffer) {
files[fileName] = await convertToSigitFile(arrayBuffer, fileName)
const hash = await getHash(arrayBuffer)
if (hash) {
fileHashes[fileName.replace(/^files\//, '')] = hash
fileHashes[fileName] = hash
}
} else {
fileHashes[fileName.replace(/^files\//, '')] = null
fileHashes[fileName] = null
}
}
console.log('fileHashes :>> ', fileHashes)
setFiles(files)
setCurrentFileHashes(fileHashes)
setLoadingSpinnerDesc('Parsing meta.json')
@ -232,48 +518,12 @@ export const VerifyPage = () => {
if (!parsedMetaJson) return
const createSignatureEvent = await parseJson<Event>(
parsedMetaJson.createSignature
).catch((err) => {
console.log('err in parsing the createSignature event:>> ', err)
toast.error(
err.message || 'error occurred in parsing the create signature event'
)
setIsLoading(false)
return null
})
if (!createSignatureEvent) return
const isValidCreateSignature = verifyEvent(createSignatureEvent)
if (!isValidCreateSignature) {
toast.error('Create signature is invalid')
setIsLoading(false)
return
}
const createSignatureContent = await parseJson<CreateSignatureEventContent>(
createSignatureEvent.content
).catch((err) => {
console.log(
`err in parsing the createSignature event's content :>> `,
err
)
toast.error(
err.message ||
`error occurred in parsing the create signature event's content`
)
setIsLoading(false)
return null
})
if (!createSignatureContent) return
setMeta(parsedMetaJson)
setIsLoading(false)
}
const handleExport = async () => {
const handleMarkedExport = async () => {
if (Object.entries(files).length === 0 || !meta || !usersPubkey) return
const usersNpub = hexToNpub(usersPubkey)
@ -303,18 +553,9 @@ export const VerifyPage = () => {
const updatedMeta = { ...meta, exportSignature }
const stringifiedMeta = JSON.stringify(updatedMeta, null, 2)
const zip = new JSZip()
const zip = await getZipWithFiles(updatedMeta, files)
zip.file('meta.json', stringifiedMeta)
const marks = extractMarksFromSignedMeta(updatedMeta)
const marksByPage = groupMarksByPage(marks)
for (const [fileName, pdf] of Object.entries(files)) {
const pages = await addMarks(pdf.file, marksByPage)
const blob = await convertToPdfBlob(pages)
zip.file(`/files/${fileName}`, blob)
}
const arrayBuffer = await zip
.generateAsync({
type: 'arraybuffer',
@ -338,47 +579,6 @@ export const VerifyPage = () => {
setIsLoading(false)
}
const displayExportedBy = () => {
if (!meta || !meta.exportSignature) return null
const exportSignatureString = meta.exportSignature
try {
const exportSignatureEvent = JSON.parse(exportSignatureString) as Event
if (verifyEvent(exportSignatureEvent)) {
const exportedBy = exportSignatureEvent.pubkey
const profile = profiles[exportedBy]
return (
<Tooltip
title={
profile?.display_name ||
profile?.name ||
shorten(hexToNpub(exportedBy))
}
placement="top"
arrow
disableInteractive
>
<TooltipChild>
<UserAvatar pubkey={exportedBy} image={profile?.picture} />
</TooltipChild>
</Tooltip>
)
} else {
toast.error(`Invalid export signature!`)
return (
<Typography component="label" sx={{ color: 'red' }}>
Invalid export signature
</Typography>
)
}
} catch (error) {
console.error(`An error occurred wile parsing exportSignature`, error)
return null
}
}
return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
@ -413,52 +613,31 @@ export const VerifyPage = () => {
{meta && (
<StickySideColumns
left={
<>
<Box className={styles.filesWrapper}>
{Object.entries(currentFileHashes).map(
([filename, hash], index) => {
const isValidHash = fileHashes[filename] === hash
return (
<Box key={`file-${index}`} className={styles.file}>
<Typography
component="label"
sx={{
color: textColor,
flexGrow: 1
}}
>
{filename}
</Typography>
{isValidHash && (
<Tooltip title="File integrity check passed" arrow>
<CheckCircle
sx={{ color: theme.palette.success.light }}
/>
</Tooltip>
)}
{!isValidHash && (
<Tooltip title="File integrity check failed" arrow>
<Cancel
sx={{ color: theme.palette.error.main }}
/>
</Tooltip>
)}
</Box>
)
}
currentFile !== null && (
<FileList
files={getCurrentUserFiles(
files,
currentFileHashes,
fileHashes
)}
</Box>
{displayExportedBy()}
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExport} variant="contained">
Export Sigit
</Button>
</Box>
</>
currentFile={currentFile}
setCurrentFile={setCurrentFile}
handleDownload={handleMarkedExport}
downloadLabel="Download Sigit"
/>
)
}
right={<UsersDetails meta={meta} />}
/>
leftIcon={faFileDownload}
centerIcon={faFile}
rightIcon={faCircleInfo}
>
<SlimPdfView
currentFile={currentFile}
files={getCurrentUserFiles(files, currentFileHashes, fileHashes)}
parsedSignatureEvents={parsedSignatureEvents}
/>
</StickySideColumns>
)}
</Container>
</>

View File

@ -50,3 +50,17 @@
}
}
}
.mark {
position: absolute;
display: flex;
justify-content: center;
align-items: center;
}
[data-dev='true'] {
.mark {
outline: 1px dotted black;
}
}

View File

@ -1,13 +1,10 @@
import { Modal } from '../layouts/modal'
import { CreatePage } from '../pages/create'
import { HomePage } from '../pages/home'
import { LandingPage } from '../pages/landing'
import { Login } from '../pages/login'
import { Nostr } from '../pages/nostr'
import { ProfilePage } from '../pages/profile'
import { Register } from '../pages/register'
import { SettingsPage } from '../pages/settings/Settings'
import { CacheSettingsPage } from '../pages/settings/cache'
import { NostrLoginPage } from '../pages/settings/nostrLogin'
import { ProfileSettingsPage } from '../pages/settings/profile'
import { RelaysPage } from '../pages/settings/relays'
import { SignPage } from '../pages/sign'
@ -22,7 +19,8 @@ export const appPrivateRoutes = {
settings: '/settings',
profileSettings: '/settings/profile/:npub',
cacheSettings: '/settings/cache',
relays: '/settings/relays'
relays: '/settings/relays',
nostrLogin: '/settings/nostrLogin'
}
export const appPublicRoutes = {
@ -85,29 +83,7 @@ export const publicRoutes: PublicRouteProps[] = [
{
path: appPublicRoutes.landingPage,
hiddenWhenLoggedIn: true,
element: <LandingPage />,
children: [
{
element: <Modal />,
children: [
{
path: appPublicRoutes.login,
hiddenWhenLoggedIn: true,
element: <Login />
},
{
path: appPublicRoutes.register,
hiddenWhenLoggedIn: true,
element: <Register />
},
{
path: appPublicRoutes.nostr,
hiddenWhenLoggedIn: true,
element: <Nostr />
}
]
}
]
element: <LandingPage />
},
{
path: appPublicRoutes.profile,
@ -129,7 +105,7 @@ export const privateRoutes = [
element: <CreatePage />
},
{
path: appPrivateRoutes.sign,
path: `${appPrivateRoutes.sign}/:id?`,
element: <SignPage />
},
{
@ -147,5 +123,9 @@ export const privateRoutes = [
{
path: appPrivateRoutes.relays,
element: <RelaysPage />
},
{
path: appPrivateRoutes.nostrLogin,
element: <NostrLoginPage />
}
]

View File

@ -0,0 +1,81 @@
import { Event, UnsignedEvent, EventTemplate, NostrEvent } from 'nostr-tools'
import { SignedEvent } from '../../types'
import { LoginMethodStrategy } from './loginMethodStrategy'
import { WindowNostr } from 'nostr-tools/nip07'
/**
* Login Method Strategy when using nostr-login package.
*
* This class extends {@link LoginMethodStrategy base strategy} and implements all login method operations
* @see {@link LoginMethodStrategy}
*/
export class NostrLoginStrategy extends LoginMethodStrategy {
private nostr: WindowNostr
constructor() {
super()
if (!window.nostr) {
throw new Error(
`window.nostr object not present. Make sure you have an nostr extension installed/working properly.`
)
}
this.nostr = window.nostr as WindowNostr
}
async nip04Encrypt(receiver: string, content: string): Promise<string> {
if (!this.nostr.nip04) {
throw new Error(
`Your nostr extension does not support nip04 encryption & decryption`
)
}
const encrypted = await this.nostr.nip04.encrypt(receiver, content)
return encrypted
}
async nip04Decrypt(sender: string, content: string): Promise<string> {
if (!this.nostr.nip04) {
throw new Error(
`Your nostr extension does not support nip04 encryption & decryption`
)
}
const decrypted = await this.nostr.nip04.decrypt(sender, content)
return decrypted
}
async nip44Encrypt(receiver: string, content: string): Promise<string> {
if (!this.nostr.nip44) {
throw new Error(
`Your nostr extension does not support nip44 encryption & decryption`
)
}
// Encrypt the content using NIP-44 provided by the nostr extension.
const encrypted = await this.nostr.nip44.encrypt(receiver, content)
return encrypted as string
}
async nip44Decrypt(sender: string, content: string): Promise<string> {
if (!this.nostr.nip44) {
throw new Error(
`Your nostr extension does not support nip44 encryption & decryption`
)
}
// Decrypt the content using NIP-44 provided by the nostr extension.
const decrypted = await this.nostr.nip44.decrypt(sender, content)
return decrypted as string
}
async signEvent(event: UnsignedEvent | EventTemplate): Promise<SignedEvent> {
return (await this.nostr
.signEvent(event as NostrEvent)
.catch((err: unknown) => {
console.log('Error while signing event: ', err)
throw err
})) as Event
}
}

View File

@ -0,0 +1,124 @@
import {
UnsignedEvent,
EventTemplate,
nip19,
nip44,
finalizeEvent,
nip04
} from 'nostr-tools'
import { SignedEvent } from '../../types'
import store from '../../store/store'
import { LoginMethod } from '../../store/auth/types'
import { LoginMethodStrategy } from './loginMethodStrategy'
import { verifySignedEvent } from '../../utils/nostr'
/**
* Login Method Strategy when using dev private key login.
*
* This class extends {@link LoginMethodStrategy base strategy} and implements all login method operations
* @see {@link LoginMethodStrategy}
*/
export class PrivateKeyStrategy extends LoginMethodStrategy {
async nip04Encrypt(receiver: string, content: string): Promise<string> {
const keys = store.getState().auth.keyPair
if (!keys) {
throw new Error(
`Login method is ${LoginMethod.privateKey} but private & public key pair is not found.`
)
}
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
const encrypted = await nip04.encrypt(privateKey, receiver, content)
return encrypted
}
async nip04Decrypt(sender: string, content: string): Promise<string> {
const keys = store.getState().auth.keyPair
if (!keys) {
throw new Error(
`Login method is ${LoginMethod.privateKey} but private & public key pair is not found.`
)
}
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
const decrypted = await nip04.decrypt(privateKey, sender, content)
return decrypted
}
async nip44Encrypt(receiver: string, content: string): Promise<string> {
const keys = store.getState().auth.keyPair
// Check if the private and public key pair is available.
if (!keys) {
throw new Error(
`Login method is ${LoginMethod.privateKey} but private & public key pair is not found.`
)
}
// Decode the private key.
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
// Generate the conversation key using NIP-44 utilities.
const nip44ConversationKey = nip44.v2.utils.getConversationKey(
privateKey,
receiver
)
// Encrypt the content using the generated conversation key.
const encrypted = nip44.v2.encrypt(content, nip44ConversationKey)
return encrypted
}
async nip44Decrypt(sender: string, content: string): Promise<string> {
const keys = store.getState().auth.keyPair
// Check if the private and public key pair is available.
if (!keys) {
throw new Error(
`Login method is ${LoginMethod.privateKey} but private & public key pair is not found.`
)
}
// Decode the private key.
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
// Generate the conversation key using NIP-44 utilities.
const nip44ConversationKey = nip44.v2.utils.getConversationKey(
privateKey,
sender
)
// Decrypt the content using the generated conversation key.
const decrypted = nip44.v2.decrypt(content, nip44ConversationKey)
return decrypted
}
async signEvent(event: UnsignedEvent | EventTemplate): Promise<SignedEvent> {
const keys = store.getState().auth.keyPair
if (!keys) {
return Promise.reject(
`Login method is ${LoginMethod.privateKey}, but keys are not found`
)
}
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
const signedEvent = finalizeEvent(event, privateKey)
verifySignedEvent(signedEvent)
return Promise.resolve(signedEvent)
}
}

View File

@ -0,0 +1,50 @@
import { UnsignedEvent, EventTemplate } from 'nostr-tools'
import { SignedEvent } from '../../types'
import {
LoginMethodStrategy,
LoginMethodOperations
} from './loginMethodStrategy'
import { LoginMethod } from '../../store/auth/types'
import { NostrLoginStrategy } from './NostrLoginStrategy'
import { PrivateKeyStrategy } from './PrivateKeyStrategy'
/**
* This class is a context provider and helper class. This MUST be instantiated and used as an entry point for any of the {@link LoginMethodOperations LoginMethodOperations}
* @constructor Takes {@link LoginMethod LoginMethod} as an argument and sets the correct strategy
*
* @see {@link LoginMethod}
* @see {@link LoginMethodOperations}
*/
export class LoginMethodContext implements LoginMethodOperations {
private strategy: LoginMethodStrategy
constructor(loginMethod?: LoginMethod) {
switch (loginMethod) {
case LoginMethod.nostrLogin:
this.strategy = new NostrLoginStrategy()
break
case LoginMethod.privateKey:
this.strategy = new PrivateKeyStrategy()
break
default:
this.strategy = new LoginMethodStrategy()
break
}
}
nip04Encrypt(receiver: string, content: string): Promise<string> {
return this.strategy.nip04Encrypt(receiver, content)
}
nip04Decrypt(sender: string, content: string): Promise<string> {
return this.strategy.nip04Decrypt(sender, content)
}
nip44Encrypt(receiver: string, content: string): Promise<string> {
return this.strategy.nip44Encrypt(receiver, content)
}
nip44Decrypt(sender: string, content: string): Promise<string> {
return this.strategy.nip44Decrypt(sender, content)
}
signEvent(event: UnsignedEvent | EventTemplate): Promise<SignedEvent> {
return this.strategy.signEvent(event)
}
}

View File

@ -0,0 +1,38 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { EventTemplate, UnsignedEvent } from 'nostr-tools'
import { SignedEvent } from '../../types/nostr'
/**
* This interface holds all operations that are dependant on the login method and is used as the basis for the login strategies.
*/
export interface LoginMethodOperations {
nip04Encrypt(receiver: string, content: string): Promise<string>
nip04Decrypt(sender: string, content: string): Promise<string>
nip44Encrypt(receiver: string, content: string): Promise<string>
nip44Decrypt(sender: string, content: string): Promise<string>
signEvent(event: UnsignedEvent | EventTemplate): Promise<SignedEvent>
}
/**
* This is the fallback class that provides base implementation for the {@link LoginMethodOperations login method operations} . Only used to throw errors in case when the LoginMethod is missing (login context not set).
* @see {@link LoginMethodOperations}
*/
export class LoginMethodStrategy implements LoginMethodOperations {
async nip04Encrypt(_receiver: string, _content: string): Promise<string> {
throw new Error('Login method strategy is undefined')
}
async nip04Decrypt(_sender: string, _content: string): Promise<string> {
throw new Error('Login method strategy is undefined')
}
async nip44Encrypt(_receiver: string, _content: string): Promise<string> {
throw new Error('Login method strategy is undefined')
}
async nip44Decrypt(_sender: string, _content: string): Promise<string> {
throw new Error('Login method strategy is undefined')
}
async signEvent(_event: UnsignedEvent | EventTemplate): Promise<SignedEvent> {
return Promise.reject(
`We could not sign the event, none of the signing methods are available`
)
}
}

View File

@ -4,9 +4,8 @@ export const USER_LOGOUT = 'USER_LOGOUT'
export const SET_AUTH_STATE = 'SET_AUTH_STATE'
export const UPDATE_LOGIN_METHOD = 'UPDATE_LOGIN_METHOD'
export const UPDATE_NOSTR_LOGIN_AUTH_METHOD = 'UPDATE_NOSTR_LOGIN_AUTH_METHOD'
export const UPDATE_KEYPAIR = 'UPDATE_KEYPAIR'
export const UPDATE_NSECBUNKER_PUBKEY = 'UPDATE_NSECBUNKER_PUBKEY'
export const UPDATE_NSECBUNKER_RELAYS = 'UPDATE_NSECBUNKER_RELAYS'
export const SET_METADATA_EVENT = 'SET_METADATA_EVENT'
@ -15,8 +14,6 @@ export const SET_USER_ROBOT_IMAGE = 'SET_USER_ROBOT_IMAGE'
export const SET_RELAY_MAP = 'SET_RELAY_MAP'
export const SET_RELAY_INFO = 'SET_RELAY_INFO'
export const SET_RELAY_MAP_UPDATED = 'SET_RELAY_MAP_UPDATED'
export const SET_MOST_POPULAR_RELAYS = 'SET_MOST_POPULAR_RELAYS'
export const SET_RELAY_CONNECTION_STATUS = 'SET_RELAY_CONNECTION_STATUS'
export const UPDATE_USER_APP_DATA = 'UPDATE_USER_APP_DATA'
export const UPDATE_PROCESSED_GIFT_WRAPS = 'UPDATE_PROCESSED_GIFT_WRAPS'

View File

@ -18,6 +18,10 @@ export interface RestoreState {
payload: State
}
export interface UserLogout {
type: typeof ActionTypes.USER_LOGOUT
}
export const userLogOutAction = () => {
return {
type: ActionTypes.USER_LOGOUT

View File

@ -2,12 +2,12 @@ import * as ActionTypes from '../actionTypes'
import {
AuthState,
Keys,
LoginMethods,
LoginMethod,
SetAuthState,
UpdateKeyPair,
UpdateLoginMethod,
UpdateNsecBunkerPubkey,
UpdateNsecBunkerRelays
NostrLoginAuthMethod,
UpdateNostrLoginAuthMethod
} from './types'
export const setAuthState = (payload: AuthState): SetAuthState => ({
@ -16,27 +16,20 @@ export const setAuthState = (payload: AuthState): SetAuthState => ({
})
export const updateLoginMethod = (
payload: LoginMethods | undefined
payload: LoginMethod | undefined
): UpdateLoginMethod => ({
type: ActionTypes.UPDATE_LOGIN_METHOD,
payload
})
export const updateNostrLoginAuthMethod = (
payload: NostrLoginAuthMethod | undefined
): UpdateNostrLoginAuthMethod => ({
type: ActionTypes.UPDATE_NOSTR_LOGIN_AUTH_METHOD,
payload
})
export const updateKeyPair = (payload: Keys | undefined): UpdateKeyPair => ({
type: ActionTypes.UPDATE_KEYPAIR,
payload
})
export const updateNsecbunkerPubkey = (
payload: string | undefined
): UpdateNsecBunkerPubkey => ({
type: ActionTypes.UPDATE_NSECBUNKER_PUBKEY,
payload
})
export const updateNsecbunkerRelays = (
payload: string[] | undefined
): UpdateNsecBunkerRelays => ({
type: ActionTypes.UPDATE_NSECBUNKER_RELAYS,
payload
})

View File

@ -8,16 +8,15 @@ const initialState: AuthState = {
const reducer = (
state = initialState,
action: AuthDispatchTypes
): AuthState | null => {
): AuthState => {
switch (action.type) {
case ActionTypes.SET_AUTH_STATE: {
const { loginMethod, keyPair, nsecBunkerPubkey, nsecBunkerRelays } = state
const { loginMethod, nostrLoginAuthMethod, keyPair } = state
return {
loginMethod,
nostrLoginAuthMethod,
keyPair,
nsecBunkerPubkey,
nsecBunkerRelays,
...action.payload
}
}
@ -30,6 +29,15 @@ const reducer = (
}
}
case ActionTypes.UPDATE_NOSTR_LOGIN_AUTH_METHOD: {
const { payload } = action
return {
...state,
nostrLoginAuthMethod: payload
}
}
case ActionTypes.UPDATE_KEYPAIR: {
const { payload } = action
@ -39,26 +47,8 @@ const reducer = (
}
}
case ActionTypes.UPDATE_NSECBUNKER_PUBKEY: {
const { payload } = action
return {
...state,
nsecBunkerPubkey: payload
}
}
case ActionTypes.UPDATE_NSECBUNKER_RELAYS: {
const { payload } = action
return {
...state,
nsecBunkerRelays: payload
}
}
case ActionTypes.RESTORE_STATE:
return action.payload.auth
return action.payload.auth || initialState
default:
return state

View File

@ -1,10 +1,17 @@
import * as ActionTypes from '../actionTypes'
import { RestoreState } from '../actions'
import { RestoreState, UserLogout } from '../actions'
export enum LoginMethods {
extension = 'extension',
export enum NostrLoginAuthMethod {
Connect = 'connect',
ReadOnly = 'readOnly',
Extension = 'extension',
Local = 'local',
OTP = 'otp'
}
export enum LoginMethod {
nostrLogin = 'nostrLogin',
privateKey = 'privateKey',
nsecBunker = 'nsecBunker',
register = 'register'
}
@ -16,10 +23,21 @@ export interface Keys {
export interface AuthState {
loggedIn: boolean
usersPubkey?: string
loginMethod?: LoginMethods
/**
* sigit login {@link LoginMethod methods }
* @see {@link LoginMethod}
*/
loginMethod?: LoginMethod
/**
* nostr-login package specific {@link NostrLoginAuthMethod method }
* @see {@link NostrLoginAuthMethod}
*/
nostrLoginAuthMethod?: NostrLoginAuthMethod
/**
* {@link Keys keyPair} for user auth (usually only public is available)
* @see {@link Keys}
*/
keyPair?: Keys
nsecBunkerPubkey?: string
nsecBunkerRelays?: string[]
}
export interface SetAuthState {
@ -29,7 +47,12 @@ export interface SetAuthState {
export interface UpdateLoginMethod {
type: typeof ActionTypes.UPDATE_LOGIN_METHOD
payload: LoginMethods | undefined
payload: LoginMethod | undefined
}
export interface UpdateNostrLoginAuthMethod {
type: typeof ActionTypes.UPDATE_NOSTR_LOGIN_AUTH_METHOD
payload: NostrLoginAuthMethod | undefined
}
export interface UpdateKeyPair {
@ -37,20 +60,10 @@ export interface UpdateKeyPair {
payload: Keys | undefined
}
export interface UpdateNsecBunkerPubkey {
type: typeof ActionTypes.UPDATE_NSECBUNKER_PUBKEY
payload: string | undefined
}
export interface UpdateNsecBunkerRelays {
type: typeof ActionTypes.UPDATE_NSECBUNKER_RELAYS
payload: string[] | undefined
}
export type AuthDispatchTypes =
| RestoreState
| SetAuthState
| UpdateLoginMethod
| UpdateNostrLoginAuthMethod
| UpdateKeyPair
| UpdateNsecBunkerPubkey
| UpdateNsecBunkerRelays
| UserLogout

View File

@ -15,7 +15,7 @@ const reducer = (
}
case ActionTypes.RESTORE_STATE:
return action.payload.metadata || null
return action.payload.metadata || initialState
default:
return state

View File

@ -1,12 +1,10 @@
import * as ActionTypes from '../actionTypes'
import {
SetRelayMapAction,
SetMostPopularRelaysAction,
SetRelayInfoAction,
SetRelayConnectionStatusAction,
SetRelayMapUpdatedAction
} from './types'
import { RelayMap, RelayInfoObject, RelayConnectionStatus } from '../../types'
import { RelayMap, RelayInfoObject } from '../../types'
export const setRelayMapAction = (payload: RelayMap): SetRelayMapAction => ({
type: ActionTypes.SET_RELAY_MAP,
@ -20,20 +18,6 @@ export const setRelayInfoAction = (
payload
})
export const setMostPopularRelaysAction = (
payload: string[]
): SetMostPopularRelaysAction => ({
type: ActionTypes.SET_MOST_POPULAR_RELAYS,
payload
})
export const setRelayConnectionStatusAction = (
payload: RelayConnectionStatus
): SetRelayConnectionStatusAction => ({
type: ActionTypes.SET_RELAY_CONNECTION_STATUS,
payload
})
export const setRelayMapUpdatedAction = (): SetRelayMapUpdatedAction => ({
type: ActionTypes.SET_RELAY_MAP_UPDATED
})

View File

@ -4,15 +4,13 @@ import { RelaysDispatchTypes, RelaysState } from './types'
const initialState: RelaysState = {
map: undefined,
mapUpdated: undefined,
mostPopular: undefined,
info: undefined,
connectionStatus: undefined
info: undefined
}
const reducer = (
state = initialState,
action: RelaysDispatchTypes
): RelaysState | null => {
): RelaysState => {
switch (action.type) {
case ActionTypes.SET_RELAY_MAP:
return { ...state, map: action.payload, mapUpdated: Date.now() }
@ -26,17 +24,8 @@ const reducer = (
info: { ...state.info, ...action.payload }
}
case ActionTypes.SET_RELAY_CONNECTION_STATUS:
return {
...state,
connectionStatus: action.payload
}
case ActionTypes.SET_MOST_POPULAR_RELAYS:
return { ...state, mostPopular: action.payload }
case ActionTypes.RESTORE_STATE:
return action.payload.relays
return action.payload.relays || initialState
default:
return state

View File

@ -1,13 +1,11 @@
import * as ActionTypes from '../actionTypes'
import { RestoreState } from '../actions'
import { RelayMap, RelayInfoObject, RelayConnectionStatus } from '../../types'
import { RelayMap, RelayInfoObject } from '../../types'
export type RelaysState = {
map?: RelayMap
mapUpdated?: number
mostPopular?: string[]
info?: RelayInfoObject
connectionStatus?: RelayConnectionStatus
}
export interface SetRelayMapAction {
@ -15,21 +13,11 @@ export interface SetRelayMapAction {
payload: RelayMap
}
export interface SetMostPopularRelaysAction {
type: typeof ActionTypes.SET_MOST_POPULAR_RELAYS
payload: string[]
}
export interface SetRelayInfoAction {
type: typeof ActionTypes.SET_RELAY_INFO
payload: RelayInfoObject
}
export interface SetRelayConnectionStatusAction {
type: typeof ActionTypes.SET_RELAY_CONNECTION_STATUS
payload: RelayConnectionStatus
}
export interface SetRelayMapUpdatedAction {
type: typeof ActionTypes.SET_RELAY_MAP_UPDATED
}
@ -38,6 +26,4 @@ export type RelaysDispatchTypes =
| SetRelayMapAction
| SetRelayInfoAction
| SetRelayMapUpdatedAction
| SetMostPopularRelaysAction
| SetRelayConnectionStatusAction
| RestoreState

View File

@ -3,12 +3,15 @@ import { combineReducers } from 'redux'
import { UserAppData } from '../types'
import * as ActionTypes from './actionTypes'
import authReducer from './auth/reducer'
import { AuthState } from './auth/types'
import { AuthDispatchTypes, AuthState } from './auth/types'
import metadataReducer from './metadata/reducer'
import relaysReducer from './relays/reducer'
import { RelaysState } from './relays/types'
import { RelaysDispatchTypes, RelaysState } from './relays/types'
import UserAppDataReducer from './userAppData/reducer'
import userRobotImageReducer from './userRobotImage/reducer'
import { MetadataDispatchTypes } from './metadata/types'
import { UserAppDataDispatchTypes } from './userAppData/types'
import { UserRobotImageDispatchTypes } from './userRobotImage/types'
export interface State {
auth: AuthState
@ -18,6 +21,13 @@ export interface State {
userAppData?: UserAppData
}
type AppActions =
| AuthDispatchTypes
| MetadataDispatchTypes
| UserRobotImageDispatchTypes
| RelaysDispatchTypes
| UserAppDataDispatchTypes
export const appReducer = combineReducers({
auth: authReducer,
metadata: metadataReducer,
@ -26,8 +36,10 @@ export const appReducer = combineReducers({
userAppData: UserAppDataReducer
})
// FIXME: define types
export default (state: any, action: any) => {
export default (
state: ReturnType<typeof appReducer> | undefined,
action: AppActions
) => {
switch (action.type) {
case ActionTypes.USER_LOGOUT:
return appReducer(undefined, action)

View File

@ -1,18 +1,18 @@
import * as ActionTypes from '../actionTypes'
import { MetadataDispatchTypes } from './types'
import { UserRobotImageDispatchTypes } from './types'
const initialState: string | null = null
const reducer = (
state = initialState,
action: MetadataDispatchTypes
action: UserRobotImageDispatchTypes
): string | null | undefined => {
switch (action.type) {
case ActionTypes.SET_USER_ROBOT_IMAGE:
return action.payload
case ActionTypes.RESTORE_STATE:
return action.payload.userRobotImage
return action.payload.userRobotImage || initialState
default:
return state

View File

@ -6,4 +6,4 @@ export interface SetUserRobotImage {
payload: string | null
}
export type MetadataDispatchTypes = SetUserRobotImage | RestoreState
export type UserRobotImageDispatchTypes = SetUserRobotImage | RestoreState

View File

@ -2,3 +2,5 @@ $header-height: 65px;
$body-vertical-padding: 25px;
$default-container-padding-inline: 10px;
$tabs-height: 40px;

View File

@ -1,5 +1,6 @@
import { Mark } from './mark'
import { Keys } from '../store/auth/types'
import { Event } from 'nostr-tools'
export enum UserRole {
signer = 'Signer',
@ -17,6 +18,7 @@ export interface Meta {
docSignatures: { [key: `npub1${string}`]: string }
exportSignature?: string
keys?: { sender: string; keys: { [user: `npub1${string}`]: string } }
timestamps?: OpenTimestamp[]
}
export interface CreateSignatureEventContent {
@ -38,9 +40,46 @@ export interface Sigit {
meta: Meta
}
export interface UserAppData {
sigits: { [key: string]: Meta } // key will be id of create signature
processedGiftWraps: string[] // an array of ids of processed gift wrapped events
keyPair?: Keys // this key pair is used for blossom requests authentication
blossomUrls: string[] // array for storing Urls for the files that stores all the sigits and processedGiftWraps on blossom
export interface OpenTimestamp {
nostrId: string
value: string
verification?: OpenTimestampVerification
signature?: string
}
export interface OpenTimestampVerification {
height: number
timestamp: number
}
export interface OpenTimestampUpgradeVerifyResponse {
timestamp: OpenTimestamp
upgraded: boolean
verified?: boolean
verification?: OpenTimestampVerification
}
export interface UserAppData {
/**
* Key will be id of create signature
*/
sigits: { [key: string]: Meta }
/**
* An array of ids of processed gift wrapped events
*/
processedGiftWraps: string[]
/**
* Generated ephemeral key pair (https://docs.sigit.io/#/technical?id=storing-app-data).
* This {@link Keys key pair} is used for blossom requests authentication.
* @see {@link Keys}
*/
keyPair?: Keys
/**
* Array for storing Urls for the files that stores all the sigits and processedGiftWraps on blossom.
*/
blossomUrls: string[]
}
export interface DocSignatureEvent extends Event {
parsedContent?: SignedEventContent
}

View File

@ -1,29 +1,23 @@
import { IconDefinition } from '@fortawesome/fontawesome-svg-core'
import { MarkRect } from './mark'
export interface MouseState {
clicked?: boolean
dragging?: boolean
resizing?: boolean
coordsInWrapper?: {
mouseX: number
mouseY: number
x: number
y: number
}
}
export interface PdfFile {
file: File
pages: PdfPage[]
expanded?: boolean
}
export interface PdfPage {
image: string
width: number
drawnFields: DrawnField[]
}
export interface DrawnField {
left: number
top: number
width: number
height: number
export interface DrawnField extends MarkRect {
type: MarkType
/**
* npub of a counter part
@ -34,16 +28,32 @@ export interface DrawnField {
export interface DrawTool {
identifier: MarkType
label: string
icon: JSX.Element
icon: IconDefinition
defaultValue?: string
selected?: boolean
active?: boolean
/** show or hide the toolbox item */
isHidden?: boolean
/** show or hide "coming soon" message on the toolbox item */
isComingSoon?: boolean
}
export enum MarkType {
TEXT = 'TEXT',
SIGNATURE = 'SIGNATURE',
JOBTITLE = 'JOBTITLE',
FULLNAME = 'FULLNAME',
INITIALS = 'INITIALS',
DATETIME = 'DATETIME',
DATE = 'DATE',
DATETIME = 'DATETIME'
NUMBER = 'NUMBER',
IMAGES = 'IMAGES',
CHECKBOX = 'CHECKBOX',
MULTIPLE = 'MULTIPLE',
FILE = 'FILE',
RADIO = 'RADIO',
SELECT = 'SELECT',
CELLS = 'CELLS',
STAMP = 'STAMP',
PAYMENT = 'PAYMENT',
PHONE = 'PHONE'
}

Some files were not shown because too many files have changed in this diff Show More