Compare commits

...
125 Commits
Author SHA1 Message Date
Gani Georgiev 3b9f2141fe updated jsvm types 2026-02-16 22:04:19 +02:00
Gani Georgiev 2b39757fbc bumped app version 2026-02-16 21:08:13 +02:00
Gani Georgiev 15091999e3 use temp dir for the $filesystem.local test 2026-02-14 12:08:57 +02:00
Gani Georgiev fcc680794c [#7526] added $filesystem.s3 and $filesystem.local JSVM bindings 2026-02-14 11:49:50 +02:00
Gani Georgiev bc72525013 [#7525] made Bearer prefix case-insensitive 2026-02-14 11:19:13 +02:00
Gani Georgiev 23ca5a77e1 fixed changelog typo 2026-02-13 21:00:25 +02:00
Gani Georgiev 266b56ecbb updated goja deps 2026-02-13 20:07:31 +02:00
Gani Georgiev ac8a4583cb updated test status codes to 2xx due to go 1.26.0 stricter checks 2026-02-13 20:02:55 +02:00
Gani Georgiev 1d72c8487e bumped app version 2026-02-13 17:21:34 +02:00
Gani Georgiev 97eb9b300b renamed arguments to make it more clear that they are dangeous 2026-02-13 16:40:29 +02:00
Gani Georgiev 5b2cae8509 [#7523] added Accept-Encoding:identity to the S3 requests 2026-02-13 16:16:12 +02:00
Gani Georgiev 5715e11e52 bumped go deps 2026-02-11 15:02:38 +02:00
Gani Georgiev 90e9fa705d bumped app version 2026-02-01 09:40:10 +02:00
Gani Georgiev d4101be9f6 updated go deps 2026-02-01 09:34:17 +02:00
Gani Georgiev 6cec679f02 updated changelog 2026-01-28 11:52:56 +02:00
Gani Georgiev 0e0b862bd7 silenced race detector errors per #7484 2026-01-28 11:52:08 +02:00
Gani Georgiev b2bf26122f updated changelog 2026-01-27 16:53:09 +02:00
Gani Georgiev adc5c3cf18 updated goja 2026-01-27 16:51:55 +02:00
Gani Georgiev 4a1e3aed6e added extra collection field exist check to minimize misuse and have a more clear error message 2026-01-27 16:46:04 +02:00
Gani Georgiev 55e24344ff updated modernc.org/sqlite to v1.44.3 2026-01-23 00:44:23 +02:00
Gani Georgiev 17086722f4 updated thumb style and title for non-previewable files 2026-01-23 00:34:58 +02:00
Gani Georgiev 9b036fb10f updated modernc.org/sqlite to 1.44.2 2026-01-18 18:57:18 +02:00
Gani Georgiev 8e3f0f2e32 regenerated jsvm types and bumped app version 2026-01-18 18:53:03 +02:00
Gani Georgiev 65750bca8d revert GROUP BY optimization 2026-01-18 18:38:40 +02:00
Gani Georgiev adb991eb02 fixed comment typos 2026-01-17 10:58:12 +02:00
Gani Georgiev d87a887673 fixed docs link in the changelog 2026-01-16 06:55:02 +02:00
Gani Georgiev f2eb295fa2 updated modernc.org deps 2026-01-16 06:27:55 +02:00
Gani Georgiev d11a9f9d99 updated JSVM types and bumped app version 2026-01-15 22:24:07 +02:00
Gani Georgiev bbd7f4e4ae replaced NoCoalesce with NullFallback and updated tests 2026-01-15 18:06:15 +02:00
Gani Georgiev b0a5bce4c4 updated 0.35.1 changelog to reflect the modernc.org/sqlite 1.42.0 retraction and updated the driver to 1.44.0 2026-01-15 14:45:26 +02:00
Gani Georgiev 9234cbf0d1 updated changelog 2026-01-15 14:34:45 +02:00
Gani Georgiev 6bf5eccfa7 added strftime filter function 2026-01-15 14:27:53 +02:00
Gani Georgiev 8bbd0c2d77 updated changelog 2026-01-13 22:30:31 +02:00
Gani Georgiev 2af60a85c5 fixed typo and updated changelog 2026-01-13 22:23:23 +02:00
Gani Georgiev 56e53e885c added more UpdateQuery tests 2026-01-13 22:15:50 +02:00
Gani Georgiev 3115f08d4a updated ui version 2026-01-13 18:56:23 +02:00
Gani Georgiev 0b9a646d41 use group by instead of distinct when possible 2026-01-13 18:47:32 +02:00
Gani Georgiev 5f8cce3558 [#7444] remove unnecessery subquery when resolving single back-relation fields 2026-01-13 14:54:35 +02:00
Gani Georgiev 3da2c00f32 updated modernc.org/sqlite to 1.43.0 2026-01-10 10:57:33 +02:00
Gani Georgiev 352ee72740 normalized multiple to single field confirmation detection 2026-01-06 18:33:44 +02:00
Gani Georgiev 98510103c3 normalized relations picker maxSelect value 2026-01-06 18:19:01 +02:00
Gani Georgiev 25c044a3a2 updated changelog 2026-01-03 14:25:04 +02:00
Gani Georgiev 0536c779d5 updated modernc.org/sqlite to 1.42.2 2026-01-03 11:23:26 +02:00
Gani Georgiev b1da83e516 fixed comment typo 2025-12-21 09:24:07 +02:00
Gani Georgiev 6b5d7b216b bumped go deps and updated jsvm types 2025-12-21 08:11:36 +02:00
Gani Georgiev 26d6a98355 updated ui/dist 2025-12-19 19:25:08 +02:00
Gani Georgiev 4abc018d7c upgraded to math/rand/v2 2025-12-19 19:08:56 +02:00
Gani Georgiev f0a9cbf31b updated modernc.org/sqlite to v1.41.0 2025-12-19 17:11:21 +02:00
Gani Georgiev d08da7594a cap the file name before normalization 2025-12-19 16:58:08 +02:00
Gani Georgiev c2d6530065 added test for file name normalization with leading dot 2025-12-19 16:30:11 +02:00
Gani Georgiev 94c4d4ec65 removed legacy and unnecessery call 2025-12-19 10:49:34 +02:00
Gani Georgiev be7ec34516 fixed error msg typo 2025-12-19 10:19:31 +02:00
Gani Georgiev 27cb36ffd7 [#7396] added nullable JSVM type helpers 2025-12-17 19:27:17 +02:00
Gani Georgiev e7af58efac updated goja 2025-12-12 09:05:04 +02:00
Gani Georgiev ab51b3c038 updated ui/dist 2025-12-12 08:55:08 +02:00
Gani Georgiev 5773f46fea replace TrimSuffix with Trim 2025-12-12 08:52:22 +02:00
Gani Georgiev 4d5b7cc1d0 updated go deps 2025-12-12 08:50:33 +02:00
Gani Georgiev 7286f34104 trim normalized file extension 2025-12-12 08:49:10 +02:00
Gani Georgiev 4399a6c1ab added small threshold for the cron time based tests 2025-12-12 08:48:29 +02:00
Gani Georgiev e89603497f store the correct image/png as attrs content type when generating a thumb fallback 2025-12-09 17:09:32 +02:00
Gani Georgiev abb6bcd6de [#7369] bumped JS SDK to fix Safari AbortError detection introduced with the previous release 2025-12-04 14:46:28 +02:00
Gani Georgiev 5604fe672e updated changelog 2025-12-02 20:20:41 +02:00
Gani Georgiev 7825baab13 updated v0.22 changelog and bumped actions/setup-go to v6 2025-12-02 20:20:27 +02:00
Gani Georgiev 68b9d0e403 updated go deps and bumped min go github version 2025-12-02 19:28:27 +02:00
Gani Georgiev 85232ed6e4 updated js sdk 2025-12-02 19:23:21 +02:00
Gani Georgiev d76d4089cf [#7357] added Copy raw JSON collection dropdown option 2025-12-02 08:21:20 +02:00
Gani Georgievandjb.muscat 2e5f8bff63 [#7353] added missing : char to the autocomplete regex
Co-authored-by: jb.muscat <jb.muscat@criteo.com>
2025-12-02 07:56:54 +02:00
Gani Georgiev 90d896e1cc updated changelog 2025-11-22 10:59:25 +02:00
Gani Georgiev c13d83adb1 updated jsvm types 2025-11-22 10:59:15 +02:00
Gani Georgiev 9b73295a7c added dumy request info to directly return an error on invalid API rule 2025-11-22 10:58:32 +02:00
Gani Georgiev 3c6ce2de74 updated go deps 2025-11-22 09:36:50 +02:00
Gani Georgiev 63b89533a9 use TEST_IP for the test auth alert email 2025-11-22 09:36:20 +02:00
Gani Georgiev 779059eca3 added short info about the backup restore steps 2025-11-22 09:36:02 +02:00
Gani Georgiev 9abdadf0dc updated modernc.org/sqlite 2025-11-18 22:24:49 +02:00
Gani Georgiev 6500b8c518 renamed outdated rate limit struct name and added reminder to reavulate the algorithm 2025-11-18 22:23:59 +02:00
Stephen Daves 91f1ca273d [#7333] updated CHANGELOG with typo fixed for geoDistance url 2025-11-18 07:39:28 +02:00
Gani Georgiev 6e739fd33d added :changed request body modifier 2025-11-17 13:58:43 +02:00
Gani Georgiev 2525f29c1c adde auth alert info as OnMailerRecordAuthAlertSend meta 2025-11-15 21:21:06 +02:00
Gani Georgiev 1dc5e061b8 updated changelog and ui/dist 2025-11-13 15:51:51 +02:00
Gani Georgiev 09d7f6a7c3 added missing mails.sendRecordAuthAlert jsvm binding 2025-11-13 10:45:33 +02:00
Gani Georgiev 1775585b68 updated goja and migrate timestamp 2025-11-13 09:59:14 +02:00
Gani Georgiev f4e6c5edee updated x/sync and other go deps 2025-11-12 15:17:36 +02:00
Gani Georgiev 94b11bf2c3 added test for escaped alert info 2025-11-12 15:15:54 +02:00
Gani Georgiev ddb8c88a37 replaced placeholder in migration and updated jsvm types 2025-11-10 17:59:11 +02:00
Gani Georgiev 0f5411d81c [#7314] added ALERT_INFO placeholder to the auth alert mail template 2025-11-10 17:56:36 +02:00
Gani Georgiev 423d234da1 added pk test for * character 2025-11-10 07:17:01 +02:00
Gani Georgiev 6184b31d82 [#7312] added extra id validations 2025-11-09 15:24:24 +02:00
Gani Georgiev 63a9d045a1 [#7312] excluded id from the excerpt list 2025-11-08 23:32:30 +02:00
Gani Georgiev 501ab0e6be updated modernc.org/sqlite to 1.40.0 2025-11-08 11:17:26 +02:00
Gani Georgiev 7ad08ef6bf updated changelog 2025-11-08 10:57:22 +02:00
Gani Georgiev 6210f361b0 bumped app version and updated ui/dist 2025-11-08 10:49:41 +02:00
Gani GeorgievandFelix fcb5b5dd67 [#7305] fixed deadlock when manually triggering the OnTerminate hook
Co-authored-by: Felix <FelixM@yer.tools>
2025-11-07 17:03:15 +02:00
Gani Georgiev 41607679a0 updated readme 2025-11-04 13:03:30 +02:00
Gani Georgiev ca7e5b7f7b updated jsvm types 2025-11-04 11:23:35 +02:00
Gani Georgiev 593721dcea flatten relation joins 2025-11-03 14:21:01 +02:00
Gani Georgiev 153ad12e64 set allowHiddenFields to prevent infinite recursion 2025-11-01 14:54:22 +02:00
Gani Georgiev 482fe2bce0 updated ui/dist 2025-10-31 22:41:52 +02:00
Gani Georgiev 48489b6a07 updated jsvm types 2025-10-31 22:24:47 +02:00
Gani Georgiev 67ee431585 add extra subquery check for client-side relation filtering 2025-10-31 22:22:28 +02:00
Gani Georgiev d5dcd01551 updated ui/dist 2025-10-23 22:33:12 +03:00
Gani Georgiev 749bf7815c updated changelog 2025-10-23 20:28:13 +03:00
Gani Georgiev ceae5e005f updated jsvm types and npm deps 2025-10-23 18:21:34 +03:00
Gani Georgiev 7b6b71e18d disallow client-side filtering and sorting of relations where the collection of the last targeted field has superusers only List/Search API rule 2025-10-23 17:22:47 +03:00
Gani Georgiev 885d907beb updated jsvm types 2025-10-23 13:15:03 +03:00
Gani Georgiev afb942bc41 updated thumb error message 2025-10-23 11:55:19 +03:00
Gani Georgiev 83a26d436e [#7268] added FileDownloadRequestEvent.ThumbError field 2025-10-23 11:48:59 +03:00
Gani Georgiev 7b52d0b56a [#7267] added tests.ApiScenario.DisableTestAppCleanup optional field 2025-10-23 11:13:49 +03:00
Gani Georgiev 5a8eae7089 add fallback in case the collection name in the response was stripped 2025-10-23 10:55:04 +03:00
Gani Georgiev 0bd712752f moved ValidateTokenSignature to jwk and added tests 2025-10-19 18:19:26 +03:00
Gani Georgiev 0b6157e1cc added no bounties note in the security policy 2025-10-19 15:49:10 +03:00
Gani Georgiev c8980edf85 updated npm deps 2025-10-19 15:41:07 +03:00
Gani Georgiev a7ebb98e20 wrap record info fields separatedly from link btn 2025-10-19 15:38:21 +03:00
Gani Georgiev 69be986132 limit max expanded presentable relations to 2 2025-10-19 14:03:28 +03:00
Gani Georgiev 58da159641 [#7252] support ed25519 oidc id_token signature validation 2025-10-19 13:49:39 +03:00
Gani Georgiev 8acb48b884 updated record-info-excerpt styles 2025-10-17 19:11:21 +03:00
Gani Georgiev 91b521595a [#7260] print nested presentable multiple relation fields 2025-10-17 14:43:36 +03:00
Gani Georgiev 52a53b5b91 updated ui/dist 2025-10-17 10:47:48 +03:00
Gani Georgiev 1137a35ded unify code-editor wrapper fields padding 2025-10-17 10:45:24 +03:00
Gani Georgiev 280005e35c [#7259] fixed json field overflow 2025-10-17 10:27:04 +03:00
Gani Georgiev 6656d9820a [#7223] workaround firefox overflow issue 2025-10-15 20:31:40 +03:00
Gani Georgiev 0d8b426b0c updated modernc.org/sqlite 2025-10-15 20:27:35 +03:00
Gani Georgiev acd12ce9dd [#7256] fixed legacy identitity field priority check when a username is a valid email address 2025-10-15 17:25:51 +03:00
Gani Georgiev 47d3da28d5 updated supported modernc.org build targets list 2025-10-08 20:08:16 +03:00
Gani Georgiev 6f8524961f updated go deps 2025-10-08 19:44:46 +03:00
Gani Georgiev fda6ad8d5d bumped min go action version 2025-10-08 17:55:23 +03:00
139 changed files with 7945 additions and 5265 deletions
+2
View File
@@ -2,4 +2,6 @@
If you discover a security vulnerability within PocketBase, please send an e-mail to **support at pocketbase.io**.
**This is non-commercial personal open source project, so there are no bounties!**
All reports will be promptly addressed and you'll be credited in the fix release notes.
+2 -2
View File
@@ -26,9 +26,9 @@ jobs:
node-version: 20.17.0
- name: Set up Go
uses: actions/setup-go@v5
uses: actions/setup-go@v6
with:
go-version: '>=1.24.7'
go-version: '>=1.26.0'
# This step usually is not needed because the /ui/dist is pregenerated locally
# but its here to ensure that each release embeds the latest admin ui artifacts.
+198 -1
View File
@@ -1,3 +1,200 @@
## v0.36.4
- Made the optional `Bearer` token prefix case-insensitive ([#7525](https://github.com/pocketbase/pocketbase/pull/7525); thanks @benjamesfleming).
- Enabled `$filesystem.s3(...)` and `$filesystem.local(...)` JSVM bindings ([#7526](https://github.com/pocketbase/pocketbase/issues/7526)).
## v0.36.3
- Added `Accept-Encoding: identity` to the S3 requests per the suggestion in [#7523](https://github.com/pocketbase/pocketbase/issues/7523).
_This should help fixing the 0-bytes file response when S3 API compression is enabled._
- Bumped min Go GitHub action version to 1.26.0 _(it comes with minor [GC performance improvements](https://go.dev/doc/go1.26#runtime))_.
- Other minor fixes _(updated `modernc.org/sqlite` to v1.45.0, updated `goja_nodejs` adding `Buffer.concat`, updated the arguments of `app.DeleteTable(...)`, `app.DeleteView(...)` and other similar methods to make it more clear that they are dangerous and shouldn't be used with untrusted input, etc.)_.
## v0.36.2
- Updated `modernc.org/sqlite` to v1.44.3 _(race check fix)_, `goja` _(circular references fix)_ and other go deps.
- Other minor fixes _(updated tests to silence some of the race detector errors, updated `FindFirstRecordByData` with more clear error message when missing or invalid key is used, etc.)_.
## v0.36.1
- Reverted the `DISTINCT` with `GROUP BY` replacement optimization from v0.36.0 as it was reported to negatively impact the indexes utilization for some queries
and the minor performance boost that you may get when used on large records is not enough to justify the more common use ([#7461](https://github.com/pocketbase/pocketbase/discussions/7461)).
_A better generic deduplication optimization for large records (aka. records with large `text`/`json` fields or many small ones) will be researched but there are no ETAs._
- Updated `modernc.org/sqlite` to v1.44.2 _(SQLite 3.51.2)_.
- Fixed code comment typos.
## v0.36.0
- List query and API rules optimizations:
- Removed unnecessary correlated subquery expression when using back-relations via single `relation` field.
- Replaced `DISTINCT` with `GROUP BY id` when rows deduplication is needed and when deemed safe.
_This should help with having a more stable and predictable performance even if the collection records are on the larger side._
For some queries and data sets the above 2 optimizations have shown significant improvements but if you notice a performance degradation after upgrading,
please open a Q&A discussion with export of your collections structure and the problematic request so that it can be analyzed.
- Added [`strftime(format, timevalue, modifiers...)`](https://pocketbase.io/docs/api-rules-and-filters/#strftimeformat-time-value-modifiers-) date formatting filter and API rules function.
It works similarly to the [SQLite `strftime` builtin function](https://sqlite.org/lang_datefunc.html)
with the main difference that NULL results will be normalized for consistency with the non-nullable PocketBase `text` and `date` fields.
Multi-match expressions are also supported and works the same as if the collection field is referenced, for example:
```js
// requires ANY/AT-LEAST-ONE-OF multiRel records to have "created" date matching the formatted string "2026-01"
strftime('%Y-%m', multiRel.created) ?= '2026-01'
// requires ALL multiRel records to have "created" date matching the formatted string "2026-01"
strftime('%Y-%m', multiRel.created) = '2026-01'
```
- ⚠️ Minor changes to the `search.ResolverResult` struct _(mostly used internally)_:
- Replaced `NoCoalesce` field with the more explicit `NullFallback` _(`NullFallbackDisabled` is the same as `NoCoalesce:true`)_.
- Replaced the expression interface of the `MultiMatchSubQuery` field with the concrete struct type `search.MultiMatchSubquery` to avoid excessive type assertions and allow direct mutations of the field.
- Updated `modernc.org/sqlite` to v1.44.1 _(SQLite 3.51.1)_.
- Bumped min Go GitHub action version to 1.25.6 because it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.25.6).
## v0.35.1
- Updated `modernc.org/sqlite` to v1.43.0 _(query cancellation race fix)_.
- Other minor UI fixes (normalized relations picker selection and confirmation message when `maxSelect=0/1`, updated node deps).
## v0.35.0
- Added `nullString()`, `nullInt()`, `nullFloat()`, `nullBool`, `nullArray()`, `nullObject()` JSVM helpers for scanning nullable columns ([#7396](https://github.com/pocketbase/pocketbase/issues/7396)).
- Store the correct `image/png` as attrs content type when generating a thumb fallback _(e.g. for `webp`)_.
- Trimmed custom uploaded file name and extension from leftover `.` characters after `filesystem.File` normalization.
_This was done to prevent issues with external files sync programs that may have special handling for "invisible" files._
- Updated `modernc.org/sqlite` _(v1.41.0 includes prepared statements optimization)_ and other minor Go deps.
## v0.34.2
- Bumped JS SDK to v0.26.5 to fix Safari AbortError detection introduced with the previous release ([#7369](https://github.com/pocketbase/pocketbase/issues/7369)).
## v0.34.1
- Added missing `:` char to the autocomplete regex ([#7353](https://github.com/pocketbase/pocketbase/pull/7353); thanks @ouvreboite).
- Added "Copy raw JSON" collection dropdown option ([#7357](https://github.com/pocketbase/pocketbase/issues/7357)).
- Updated Go deps and JS SDK.
- Bumped min Go GitHub action version to 1.25.5 because it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.25.5).
_The runner action was also updated to `actions/setup-go@v6` since the previous v5 Go source seems [no longer accessible](https://github.com/actions/setup-go/pull/665#issuecomment-3416693714)._
## v0.34.0
- Added `@request.body.someField:changed` modifier.
It could be used when you want to ensure that a body field either wasn't submitted or was submitted with the same value.
Or in other words, if you want to disallow a field change the below 2 expressions would be equivalent:
```js
// (old)
(@request.body.someField:isset = false || @request.body.someField = someField)
// (new)
@request.body.someField:changed = false
```
- Added `MailerRecordEvent.Meta["info"]` property for the `OnMailerRecordAuthAlertSend` hook.
- Updated the backup restore popup with a short info about the performed restore steps.
- Updated Go deps.
## v0.33.0
- Added extra `id` characters validation in addition to the user specified regex pattern ([#7312](https://github.com/pocketbase/pocketbase/issues/7312)).
_The following special characters are always forbidden: `./\|"'``<>:?*%$\n\r\t\0 `. Common reserved Windows file names such as `aux`, `prn`, `con`, `nul`, `com1-9`, `lpt1-9` are also not allowed._
_The list is not exhaustive but it should help minimizing eventual filesystem compatibility issues in case of wildcards or other loose regex patterns._
- Added `{ALERT_INFO}` placeholder to the auth alert mail template ([#7314](https://github.com/pocketbase/pocketbase/issues/7314)).
_⚠️ `mails.SendRecordAuthAlert(app, authRecord, info)` also now accepts a 3rd `info` string argument._
- Updated Go deps.
## v0.32.0
- ⚠️ Added extra List/Search API rules checks for the client-side `filter`/`sort` relations.
This is continuation of the effort to eliminate the risk of information disclosure _(and eventually the side-channel attacks that may originate from that)_.
So far this was accepted tradeoff between performance, usability and correctness since the solutions at the time weren't really practical _(especially with the back-relations as mentioned in ["Security and performance" section in #4417](https://github.com/pocketbase/pocketbase/discussions/4417))_, but with v0.23+ changes we can implement the extra checks without littering the code too much, with very little impact on the performance and at the same time ensuring better out of the box security _(especially for the cases where users operate with sensitive fields like "code", "token", "secret", etc.)_.
Similar to the previous release, probably for most users with already configured API rules this change won't be breaking, but if you have an _intermediate/junction collection_ that is "locked" (superusers-only) we no longer will allow the client-side relation filter to pass through it and you'll have to set its List/Search API rule to enable the current user to search in it.
For example, if you have a client-side filter that targets `rel1.rel2.token`, the client must have not only List/Search API rule access to the main collection BUT also to the collections referenced by "rel1" and "rel2" relation fields.
Note that this change is only for the **client-side** `filter`/`sort` and doesn't affect the execution of superuser requests, API rules and `expand` - they continue to work the same as it is.
An optional environment variable to toggle this behavior was considered but for now I think having 2 ways of resolving client-side filters would introduce maintenance burden and can even cause confusion (this change should actually make things more intuitive and clear because we can simply say something like _"you can search by a collection X field only if you have List/Search API rule access to it"_ no matter whether the targeted collection is the request's main collection, the first or last relation from the filter chain, etc.).
If you stumble on an error or extreme query performance degradation as a result of the extra checks, please open a Q&A discussion with the failing request and export of your collections configuration as JSON (_Settings > Export collections_) and I'll try to investigate it.
- Increased the default SQLite `PRAGMA cache_size` to ~32MB.
- Fixed deadlock when manually triggering the `OnTerminate` hook ([#7305](https://github.com/pocketbase/pocketbase/pull/7305); thanks @yerTools).
- Fixed some code comment typos, regenerated the JSVM types and updated npm dependencies.
- Updated `modernc.org/sqlite` to 1.40.0.
## v0.31.0
- Visualize presentable multiple `relation` fields ([#7260](https://github.com/pocketbase/pocketbase/issues/7260)).
- Support Ed25519 in the optional OIDC `id_token` signature validation ([#7252](https://github.com/pocketbase/pocketbase/issues/7252); thanks @shynome).
- Added `ApiScenario.DisableTestAppCleanup` optional field to skip the auto test app cleanup and leave it up to the developers to do the cleanup manually ([#7267](https://github.com/pocketbase/pocketbase/discussions/7267)).
- Added `FileDownloadRequestEvent.ThumbError` field that is populated in case of a thumb generation failure (e.g. unsupported format, timing out, etc.), allowing developers to reject the thumb fallback and/or supply their own custom thumb generation ([#7268](https://github.com/pocketbase/pocketbase/discussions/7268)).
- ⚠️ Disallow client-side filtering and sorting of relations where the collection of the last targeted relation field has superusers-only List/Search API rule to further minimize the risk of eventual side-channel attack.
_This should be a non-breaking change for most users, but if you want the old behavior, please open a new Q&A discussion with details about your use case to evaluate making it configurable._
_Note also that as mentioned in the "Security and performance" section of [#4417](https://github.com/pocketbase/pocketbase/discussions/4417) and [#5863](https://github.com/pocketbase/pocketbase/discussions/5863), the easiest and recommended solution to protect security sensitive fields (tokens, codes, passwords, etc.) is to mark them as "Hidden" (aka. make them non-API filterable)._
- Regenerated JSVM types and updated npm and Go deps.
## v0.30.4
- Fixed `json` field CSS regression introduced with the overflow workaround in v0.30.3 ([#7259](https://github.com/pocketbase/pocketbase/issues/7259)).
## v0.30.3
- Fixed legacy identitity field priority check when a username is a valid email address ([#7256](https://github.com/pocketbase/pocketbase/issues/7256)).
- Workaround autocomplete overflow issue with Firefox 144 ([#7223](https://github.com/pocketbase/pocketbase/issues/7223)).
- Updated `modernc.org/sqlite` to 1.39.1 (SQLite 3.50.4).
## v0.30.2
- Bumped min Go GitHub action version to 1.24.8 since it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.24.8+label%3ACherryPickApproved).
## v0.30.1
- ⚠️ Excluded the `lost+found` directory from the backups ([#7208](https://github.com/pocketbase/pocketbase/pull/7208); thanks @lbndev).
@@ -167,7 +364,7 @@
If you are having difficulties adjusting your code, feel free to open a [Q&A discussion](https://github.com/pocketbase/pocketbase/discussions) with the failing/problematic code sample.
- Added [new `geoPoint` field](https://pocketbase.io/docs/collections/#geopoint) for storing `{"lon":x,"lat":y}` geographic coordinates.
In addition, a new [`geoDistance(lonA, lotA, lonB, lotB)` function](htts://pocketbase.io/docs/api-rules-and-filters/#geodistancelona-lata-lonb-latb) was also implemented that could be used to apply an API rule or filter constraint based on the distance (in km) between 2 geo points.
In addition, a new [`geoDistance(lonA, lotA, lonB, lotB)` function](https://pocketbase.io/docs/api-rules-and-filters/#geodistancelona-lata-lonb-latb) was also implemented that could be used to apply an API rule or filter constraint based on the distance (in km) between 2 geo points.
- Updated the `select` field UI to accommodate better larger lists and RTL languages ([#4674](https://github.com/pocketbase/pocketbase/issues/4674)).
+18
View File
@@ -2,6 +2,24 @@
> For the most recent versions, please refer to [CHANGELOG.md](./CHANGELOG.md)
---
## v0.22.38
- (_Backported from v0.36.0_) Bumped min Go GitHub action version to 1.25.6 because it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.25.6).
## v0.22.37
- (_Backported from v0.34.1_) - Added missing `:` char to the autocomplete regex ([#7353](https://github.com/pocketbase/pocketbase/pull/7353)).
- (_Backported from v0.34.1_) Bumped min Go GitHub action version to 1.25.5 because it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.25.5).
_The runner action was also updated to `actions/setup-go@v6` since the previous v5 Go source seems [no longer accessible](https://github.com/actions/setup-go/pull/665#issuecomment-3416693714)._
## v0.22.36
- (_Backported from v0.30.2_) Bumped min Go GitHub action version to 1.24.8 since it comes with some [minor security fixes](https://github.com/golang/go/issues?q=milestone%3AGo1.24.8+label%3ACherryPickApproved).
## v0.22.35
- (_Backported from v0.29.2_) Bumped min Go GitHub action version to 1.23.12 since it comes with some [minor fixes for the runtime and `database/sql` package](https://github.com/golang/go/issues?q=milestone%3AGo1.23.12+label%3ACherryPickApproved).
+1 -1
View File
@@ -10,7 +10,7 @@ This document describes how to prepare a PR for a change in the main repository.
## Prerequisites
- Go 1.23+ (for making changes in the Go code)
- Go 1.24+ (for making changes in the Go code)
- Node 18+ (for making changes in the Admin UI)
If you haven't already, you can fork the main repository and clone your fork so that you can work locally:
+3 -1
View File
@@ -92,7 +92,7 @@ _For more details please refer to [Extend with Go](https://pocketbase.io/docs/go
To build the minimal standalone executable, like the prebuilt ones in the releases page, you can simply run `go build` inside the `examples/base` directory:
0. [Install Go 1.23+](https://go.dev/doc/install) (_if you haven't already_)
0. [Install Go 1.24+](https://go.dev/doc/install) (_if you haven't already_)
1. Clone/download the repo
2. Navigate to `examples/base`
3. Run `GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build`
@@ -110,9 +110,11 @@ linux 386
linux amd64
linux arm
linux arm64
linux loong64
linux ppc64le
linux riscv64
linux s390x
windows 386
windows amd64
windows arm64
```
+20 -17
View File
@@ -142,8 +142,14 @@ func (api *fileApi) download(e *core.RequestEvent) error {
defer fsys.Close()
originalPath := baseFilesPath + "/" + filename
servedPath := originalPath
servedName := filename
event := new(core.FileDownloadRequestEvent)
event.RequestEvent = e
event.Collection = collection
event.Record = record
event.FileField = fileField
event.ServedPath = originalPath
event.ServedName = filename
// check for valid thumb size param
thumbSize := e.Request.URL.Query().Get("thumb")
@@ -157,34 +163,31 @@ func (api *fileApi) download(e *core.RequestEvent) error {
// check if it is an image
if list.ExistInSlice(oAttrs.ContentType, imageContentTypes) {
// add thumb size as file suffix
servedName = thumbSize + "_" + filename
servedPath = baseFilesPath + "/thumbs_" + filename + "/" + servedName
event.ServedName = thumbSize + "_" + filename
event.ServedPath = baseFilesPath + "/thumbs_" + filename + "/" + event.ServedName
// create a new thumb if it doesn't exist
if exists, _ := fsys.Exists(servedPath); !exists {
if err := api.createThumb(e, fsys, originalPath, servedPath, thumbSize); err != nil {
if exists, _ := fsys.Exists(event.ServedPath); !exists {
if err := api.createThumb(e, fsys, originalPath, event.ServedPath, thumbSize); err != nil {
e.App.Logger().Warn(
"Fallback to original - failed to create thumb "+servedName,
"Fallback to original - failed to create thumb "+event.ServedName,
slog.Any("error", err),
slog.String("original", originalPath),
slog.String("thumb", servedPath),
slog.String("thumb", event.ServedPath),
)
// fallback to the original
servedName = filename
servedPath = originalPath
event.ThumbError = err
event.ServedName = filename
event.ServedPath = originalPath
}
}
}
}
event := new(core.FileDownloadRequestEvent)
event.RequestEvent = e
event.Collection = collection
event.Record = record
event.FileField = fileField
event.ServedPath = servedPath
event.ServedName = servedName
if thumbSize != "" && event.ThumbError == nil && event.ServedPath == originalPath {
event.ThumbError = fmt.Errorf("the thumb size %q or the original file format are not supported", thumbSize)
}
// clickjacking shouldn't be a concern when serving uploaded files,
// so it safe to unset the global X-Frame-Options to allow files embedding
+88 -24
View File
@@ -181,9 +181,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - missing thumb (should fallback to the original)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=999x999",
Name: "existing image - missing thumb (should fallback to the original)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=999x999",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError == nil {
t.Fatal("Expected thumb error, got nil")
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testImg)},
ExpectedEvents: map[string]int{
@@ -192,9 +200,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (crop center)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50",
Name: "existing image - existing thumb (crop center)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbCropCenter)},
ExpectedEvents: map[string]int{
@@ -203,9 +219,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (crop top)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50t",
Name: "existing image - existing thumb (crop top)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50t",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbCropTop)},
ExpectedEvents: map[string]int{
@@ -214,9 +238,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (crop bottom)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50b",
Name: "existing image - existing thumb (crop bottom)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50b",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbCropBottom)},
ExpectedEvents: map[string]int{
@@ -225,9 +257,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (fit)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50f",
Name: "existing image - existing thumb (fit)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x50f",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbFit)},
ExpectedEvents: map[string]int{
@@ -236,9 +276,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (zero width)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=0x50",
Name: "existing image - existing thumb (zero width)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=0x50",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbZeroWidth)},
ExpectedEvents: map[string]int{
@@ -247,9 +295,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing image - existing thumb (zero height)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x0",
Name: "existing image - existing thumb (zero height)",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/4q1xlclmfloku33/300_1SEi6Q6U72.png?thumb=70x0",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError != nil {
t.Fatalf("Expected no thumb error, got %v", e.ThumbError)
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testThumbZeroHeight)},
ExpectedEvents: map[string]int{
@@ -258,9 +314,17 @@ func TestFileDownload(t *testing.T) {
},
},
{
Name: "existing non image file - thumb parameter should be ignored",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/oap640cot4yru2s/test_kfd2wYLxkz.txt?thumb=100x100",
Name: "existing non image file - thumb parameter should be ignored",
Method: http.MethodGet,
URL: "/api/files/_pb_users_auth_/oap640cot4yru2s/test_kfd2wYLxkz.txt?thumb=100x100",
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
app.OnFileDownloadRequest().BindFunc(func(e *core.FileDownloadRequestEvent) error {
if e.ThumbError == nil {
t.Fatal("Expected thumb error, got nil")
}
return e.Next()
})
},
ExpectedStatus: 200,
ExpectedContent: []string{string(testFile)},
ExpectedEvents: map[string]int{
+6 -4
View File
@@ -207,11 +207,13 @@ func loadAuthToken() *hook.Handler[*core.RequestEvent] {
func getAuthTokenFromRequest(e *core.RequestEvent) string {
token := e.Request.Header.Get("Authorization")
if token != "" {
// the schema prefix is not required and it is only for
// compatibility with the defaults of some HTTP clients
token = strings.TrimPrefix(token, "Bearer ")
// the "Bearer" schema prefix is not required by PocketBase and it is
// supported only for compatibility with the defaults of some HTTP clients
if len(token) > 7 && strings.EqualFold(token[:7], "Bearer ") {
return token[7:]
}
return token
}
+17 -11
View File
@@ -234,12 +234,12 @@ func newRateLimiter(maxAllowed int, intervalInSec int64, minDeleteIntervalInSec
maxAllowed: maxAllowed,
interval: intervalInSec,
minDeleteInterval: minDeleteIntervalInSec,
clients: map[string]*fixedWindow{},
clients: map[string]*rateClient{},
}
}
type rateLimiter struct {
clients map[string]*fixedWindow
clients map[string]*rateClient
maxAllowed int
interval int64
@@ -250,7 +250,7 @@ type rateLimiter struct {
}
//nolint:unused
func (rt *rateLimiter) getClient(key string) (*fixedWindow, bool) {
func (rt *rateLimiter) getClient(key string) (*rateClient, bool) {
rt.RLock()
client, ok := rt.clients[key]
rt.RUnlock()
@@ -269,7 +269,7 @@ func (rt *rateLimiter) isAllowed(key string) bool {
// check again in case the client was added by another request
client, ok = rt.clients[key]
if !ok {
client = newFixedWindow(rt.maxAllowed, rt.interval)
client = newRateClient(rt.maxAllowed, rt.interval)
rt.clients[key] = client
}
rt.Unlock()
@@ -295,7 +295,7 @@ func (rt *rateLimiter) clean() {
//
// @todo remove after https://github.com/golang/go/issues/20135
if rt.totalDeleted >= 300 {
shrunk := make(map[string]*fixedWindow, len(rt.clients))
shrunk := make(map[string]*rateClient, len(rt.clients))
for k, v := range rt.clients {
shrunk[k] = v
}
@@ -304,14 +304,20 @@ func (rt *rateLimiter) clean() {
}
}
func newFixedWindow(maxAllowed int, intervalInSec int64) *fixedWindow {
return &fixedWindow{
func newRateClient(maxAllowed int, intervalInSec int64) *rateClient {
return &rateClient{
maxAllowed: maxAllowed,
interval: intervalInSec,
}
}
type fixedWindow struct {
// @todo evaluate swiching to a more traditional fixed window or sliding window counter
// implementations since some users complained that it is not intuitive (see #7329).
//
// rateClient is a mixture of token bucket and fixed window rate limit strategies
// that refills the allowance only after at least "interval" seconds
// has elapsed since the last request.
type rateClient struct {
// use plain Mutex instead of RWMutex since the operations are expected
// to be mostly writes (e.g. consume()) and it should perform better
sync.Mutex
@@ -324,18 +330,18 @@ type fixedWindow struct {
// hasExpired checks whether it has been at least minElapsed seconds since the lastConsume time.
// (usually used to perform periodic cleanup of staled instances).
func (l *fixedWindow) hasExpired(relativeNow int64, minElapsed int64) bool {
func (l *rateClient) hasExpired(relativeNow int64, minElapsed int64) bool {
l.Lock()
defer l.Unlock()
return relativeNow-l.lastConsume > minElapsed
}
// consume decrease the current window allowance with 1 (if not exhausted already).
// consume decreases the current allowance with 1 (if not exhausted already).
//
// It returns false if the allowance has been already exhausted and the user
// has to wait until it resets back to its maxAllowed value.
func (l *fixedWindow) consume() bool {
func (l *rateClient) consume() bool {
l.Lock()
defer l.Unlock()
+16
View File
@@ -224,6 +224,22 @@ func TestRequireAuth(t *testing.T) {
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
{
Name: "valid record auth token with Bearer case-insensitive prefix",
Method: http.MethodGet,
URL: "/my/test",
Headers: map[string]string{
// regular user
"Authorization": "BeArEr eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjRxMXhsY2xtZmxva3UzMyIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoiX3BiX3VzZXJzX2F1dGhfIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.ZT3F0Z3iM-xbGgSG3LEKiEzHrPHr8t8IuHLZGGNuxLo",
},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
e.Router.GET("/my/test", func(e *core.RequestEvent) error {
return e.String(200, "test123")
}).Bind(apis.RequireAuth())
},
ExpectedStatus: 200,
ExpectedContent: []string{"test123"},
},
}
for _, scenario := range scenarios {
+5 -1
View File
@@ -769,7 +769,11 @@ func realtimeCanAccessRecord(
}
q.AndWhere(expr)
resolver.UpdateQuery(q)
err = resolver.UpdateQuery(q)
if err != nil {
return false
}
err = q.Limit(1).Row(&exists)
+23 -14
View File
@@ -40,23 +40,32 @@ func recordAuthWithPassword(e *core.RequestEvent) error {
if form.IdentityField != "" {
foundRecord, foundErr = findRecordByIdentityField(e.App, collection, form.IdentityField, form.Identity)
} else {
// prioritize email lookup
isEmail := is.EmailFormat.Validate(form.Identity) == nil
if isEmail && list.ExistInSlice(core.FieldNameEmail, collection.PasswordAuth.IdentityFields) {
foundRecord, foundErr = findRecordByIdentityField(e.App, collection, core.FieldNameEmail, form.Identity)
identityFields := collection.PasswordAuth.IdentityFields
// @todo consider removing with the stable release or moving it in the collection save
//
// prioritize email lookup to minimize breaking changes with earlier versions
if len(identityFields) > 1 && identityFields[0] != core.FieldNameEmail {
identityFields = slices.Clone(identityFields)
slices.SortStableFunc(identityFields, func(a, b string) int {
if a == "email" {
return -1
}
if b == "email" {
return 1
}
return 0
})
}
// search by the other identity fields
if !isEmail || foundErr != nil {
for _, name := range collection.PasswordAuth.IdentityFields {
if !isEmail && name == core.FieldNameEmail {
continue // no need to search by the email field if it is not an email
}
for _, name := range identityFields {
if name == core.FieldNameEmail && is.EmailFormat.Validate(form.Identity) != nil {
continue // no need to query the database if we know that the submitted value is not an email
}
foundRecord, foundErr = findRecordByIdentityField(e.App, collection, name, form.Identity)
if foundErr == nil {
break
}
foundRecord, foundErr = findRecordByIdentityField(e.App, collection, name, form.Identity)
if foundErr == nil {
break
}
}
}
+51
View File
@@ -212,6 +212,57 @@ func TestRecordAuthWithPassword(t *testing.T) {
"OnMailerRecordAuthAlertSend": 1,
},
},
{
// https://github.com/pocketbase/pocketbase/issues/7256
Name: "valid non-email identity field with a value that is a properly formatted email",
Method: http.MethodPost,
URL: "/api/collections/clients/auth-with-password",
Body: strings.NewReader(`{
"identity":"username_as_email@example.com",
"password":"1234567890"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
record, err := app.FindAuthRecordByEmail("clients", "test@example.com")
if err != nil {
t.Fatal(err)
}
record.Set("username", "username_as_email@example.com")
err = app.SaveNoValidate(record)
if err != nil {
t.Fatal(err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"email":"test@example.com"`,
`"username":"username_as_email@example.com"`,
`"token":`,
},
NotExpectedContent: []string{
// hidden fields
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithPasswordRequest": 1,
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
// authOrigin track
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelAfterCreateSuccess": 1,
"OnModelValidate": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordAfterCreateSuccess": 1,
"OnRecordValidate": 1,
"OnMailerSend": 1,
"OnMailerRecordAuthAlertSend": 1,
},
},
{
Name: "unknown explicit identityField",
Method: http.MethodPost,
+30 -6
View File
@@ -118,7 +118,7 @@ func recordsList(e *core.RequestEvent) error {
len(e.Records) == 0 &&
checkRateLimit(e.RequestEvent, "@pb_list_timing_check_"+collection.Id, listTimingRateLimitRule) != nil {
e.App.Logger().Debug("Randomized throttle because of too many failed searches", "collectionId", collection.Id)
randomizedThrottle(150)
randomizedThrottle(500)
}
return execAfterSuccessTx(true, e.App, func() error {
@@ -169,12 +169,18 @@ func recordView(e *core.RequestEvent) error {
ruleFunc := func(q *dbx.SelectQuery) error {
if !requestInfo.HasSuperuserAuth() && collection.ViewRule != nil && *collection.ViewRule != "" {
resolver := core.NewRecordFieldResolver(e.App, collection, requestInfo, true)
expr, err := search.FilterData(*collection.ViewRule).BuildExpr(resolver)
if err != nil {
return err
}
resolver.UpdateQuery(q)
q.AndWhere(expr)
err = resolver.UpdateQuery(q)
if err != nil {
return err
}
}
return nil
}
@@ -310,7 +316,10 @@ func recordCreate(responseWriteAfterTx bool, optFinalizer func(data any) error)
}
ruleQuery.AndWhere(expr)
resolver.UpdateQuery(ruleQuery)
err = resolver.UpdateQuery(ruleQuery)
if err != nil {
return e.BadRequestError("Failed to create record", fmt.Errorf("create rule update query failure: %w", err))
}
var exists int
err = ruleQuery.Limit(1).Row(&exists)
@@ -430,12 +439,18 @@ func recordUpdate(responseWriteAfterTx bool, optFinalizer func(data any) error)
ruleFunc := func(q *dbx.SelectQuery) error {
if !hasSuperuserAuth && collection.UpdateRule != nil && *collection.UpdateRule != "" {
resolver := core.NewRecordFieldResolver(e.App, collection, requestInfo, true)
expr, err := search.FilterData(*collection.UpdateRule).BuildExpr(resolver)
if err != nil {
return err
}
resolver.UpdateQuery(q)
q.AndWhere(expr)
err = resolver.UpdateQuery(q)
if err != nil {
return err
}
}
return nil
}
@@ -546,12 +561,18 @@ func recordDelete(responseWriteAfterTx bool, optFinalizer func(data any) error)
ruleFunc := func(q *dbx.SelectQuery) error {
if !requestInfo.HasSuperuserAuth() && collection.DeleteRule != nil && *collection.DeleteRule != "" {
resolver := core.NewRecordFieldResolver(e.App, collection, requestInfo, true)
expr, err := search.FilterData(*collection.DeleteRule).BuildExpr(resolver)
if err != nil {
return err
}
resolver.UpdateQuery(q)
q.AndWhere(expr)
err = resolver.UpdateQuery(q)
if err != nil {
return err
}
}
return nil
}
@@ -732,7 +753,10 @@ func hasAuthManageAccess(app core.App, requestInfo *core.RequestInfo, collection
}
query.AndWhere(expr)
resolver.UpdateQuery(query)
err = resolver.UpdateQuery(query)
if err != nil {
return false
}
var exists int
+30 -4
View File
@@ -382,10 +382,32 @@ func TestRecordCrudList(t *testing.T) {
},
},
{
Name: "multi-match - at least one of",
Name: "multi-match - at least one of (guest - non-satisfied relation filter API rule)",
Method: http.MethodGet,
URL: "/api/collections/demo4/records?filter=" + url.QueryEscape("rel_many_no_cascade_required.files:length?=2"),
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
`"totalPages":0`,
`"totalItems":0`,
`"items":[]`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordsListRequest": 1,
"OnRecordEnrich": 0,
},
},
{
Name: "multi-match - at least one of (clients)",
Method: http.MethodGet,
URL: "/api/collections/demo4/records?filter=" + url.QueryEscape("rel_many_no_cascade_required.files:length?=2"),
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
`"perPage":30`,
@@ -401,9 +423,13 @@ func TestRecordCrudList(t *testing.T) {
},
},
{
Name: "multi-match - all",
Method: http.MethodGet,
URL: "/api/collections/demo4/records?filter=" + url.QueryEscape("rel_many_no_cascade_required.files:length=2"),
Name: "multi-match - all (clients)",
Method: http.MethodGet,
URL: "/api/collections/demo4/records?filter=" + url.QueryEscape("rel_many_no_cascade_required.files:length=2"),
Headers: map[string]string{
// clients, test@example.com
"Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImdrMzkwcWVnczR5NDd3biIsInR5cGUiOiJhdXRoIiwiY29sbGVjdGlvbklkIjoidjg1MXE0cjc5MHJoa25sIiwiZXhwIjoyNTI0NjA0NDYxLCJyZWZyZXNoYWJsZSI6dHJ1ZX0.0ONnm_BsvPRZyDNT31GN1CKUB6uQRxvVvQ-Wc9AZfG0",
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"page":1`,
+30 -9
View File
@@ -15,6 +15,7 @@ import (
"github.com/pocketbase/pocketbase/tools/routine"
"github.com/pocketbase/pocketbase/tools/search"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/types"
)
const (
@@ -160,7 +161,11 @@ func wantsMFA(e *core.RequestEvent, record *core.Record) (bool, error) {
if err != nil {
return true, err
}
resolver.UpdateQuery(query)
err = resolver.UpdateQuery(query)
if err != nil {
return true, err
}
err = query.AndWhere(expr).Limit(1).Row(&exists)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
@@ -379,12 +384,18 @@ func expandFetch(app core.App, originalRequestInfo *core.RequestInfo) core.Expan
if *relCollection.ViewRule != "" {
resolver := core.NewRecordFieldResolver(app, relCollection, requestInfoPtr, true)
expr, err := search.FilterData(*(relCollection.ViewRule)).BuildExpr(resolver)
if err != nil {
return err
}
resolver.UpdateQuery(q)
q.AndWhere(expr)
err = resolver.UpdateQuery(q)
if err != nil {
return err
}
}
return nil
@@ -465,10 +476,16 @@ func autoResolveRecordsFlags(app core.App, records []*core.Record, requestInfo *
if err != nil {
return err
}
resolver.UpdateQuery(query)
query.AndWhere(expr)
if err := query.Column(&managedIds); err != nil {
err = resolver.UpdateQuery(query)
if err != nil {
return err
}
err = query.Column(&managedIds)
if err != nil {
return err
}
// ---
@@ -563,13 +580,17 @@ func execAfterSuccessTx(checkTx bool, app core.App, fn func() error) error {
const maxAuthOrigins = 5
func authAlert(e *core.RequestEvent, authRecord *core.Record) error {
// generating fingerprint
// generate fingerprint
// ---
ip := e.RealIP()
userAgent := e.Request.UserAgent()
if len(userAgent) > 300 {
userAgent = userAgent[:300]
if len(userAgent) > 200 {
userAgent = userAgent[:200] + "..."
}
fingerprint := security.MD5(e.RealIP() + userAgent)
fingerprint := security.MD5(ip + userAgent)
alertInfo := fmt.Sprintf("%s - %s %s", types.NowDateTime().String(), ip, userAgent)
// ---
origins, err := e.App.FindAllAuthOriginsByRecord(authRecord)
@@ -609,7 +630,7 @@ func authAlert(e *core.RequestEvent, authRecord *core.Record) error {
})
routine.FireAndForget(func() {
err := mails.SendRecordAuthAlert(e.App, authRecord)
err := mails.SendRecordAuthAlert(e.App, authRecord, alertInfo)
timer.Stop()
mailSent <- err
})
+12 -9
View File
@@ -240,29 +240,32 @@ type App interface {
// This method is a no-op if a table with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "tableName" argument must come only from trusted input!
DeleteTable(tableName string) error
// "dangerousTableName" argument must come only from trusted input!
DeleteTable(dangerousTableName string) error
// DeleteView drops the specified view name.
//
// This method is a no-op if a view with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "name" argument must come only from trusted input!
DeleteView(name string) error
// "dangerousViewName" argument must come only from trusted input!
DeleteView(dangerousViewName string) error
// SaveView creates (or updates already existing) persistent SQL view.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "selectQuery" argument must come only from trusted input!
SaveView(name string, selectQuery string) error
// NB! Be aware that this method is vulnerable to SQL injection and
// its arguments must come only from trusted input!
SaveView(dangerousViewName string, dangerousSelectQuery string) error
// CreateViewFields creates a new FieldsList from the provided select query.
//
// There are some caveats:
// - The select query must have an "id" column.
// - Wildcard ("*") columns are not supported to avoid accidentally leaking sensitive data.
CreateViewFields(selectQuery string) (FieldsList, error)
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "dangerousSelectQuery" argument must come only from trusted input!
CreateViewFields(dangerousSelectQuery string) (FieldsList, error)
// FindRecordByViewFile returns the original Record of the provided view collection file.
FindRecordByViewFile(viewCollectionModelOrIdentifier any, fileFieldName string, filename string) (*Record, error)
@@ -1195,7 +1198,7 @@ type App interface {
// ---------------------------------------------------------------
// OnMailerSend hook is triggered every time when a new email is
// being send using the [App.NewMailClient()] instance.
// being sent using the [App.NewMailClient()] instance.
//
// It allows intercepting the email message or to use a custom mailer client.
OnMailerSend() *hook.Hook[*MailerEvent]
+6 -2
View File
@@ -1408,7 +1408,7 @@ func getLoggerMinLevel(app App) slog.Level {
func (app *BaseApp) initLogger() error {
duration := 3 * time.Second
ticker := time.NewTicker(duration)
done := make(chan bool)
done := make(chan bool, 1)
handler := logger.NewBatchHandler(logger.BatchOptions{
Level: getLoggerMinLevel(app),
@@ -1479,7 +1479,11 @@ func (app *BaseApp) initLogger() error {
ticker.Stop()
done <- true
// don't block in case OnTerminate is triggered more than once
select {
case done <- true:
default:
}
return e.Next()
},
+16
View File
@@ -552,3 +552,19 @@ func TestBaseAppAuxDBDualBuilder(t *testing.T) {
}
}
}
func TestBaseAppTriggerOnTerminate(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
event := new(core.TerminateEvent)
event.App = app
// trigger OnTerminate multiple times to ensure that it doesn't deadlock
// https://github.com/pocketbase/pocketbase/pull/7305
app.OnTerminate().Trigger(event)
app.OnTerminate().Trigger(event)
app.OnTerminate().Trigger(event)
}
+9 -7
View File
@@ -2,11 +2,12 @@ package core
// Common settings placeholder tokens
const (
EmailPlaceholderAppName string = "{APP_NAME}"
EmailPlaceholderAppURL string = "{APP_URL}"
EmailPlaceholderToken string = "{TOKEN}"
EmailPlaceholderOTP string = "{OTP}"
EmailPlaceholderOTPId string = "{OTP_ID}"
EmailPlaceholderAppName string = "{APP_NAME}"
EmailPlaceholderAppURL string = "{APP_URL}"
EmailPlaceholderToken string = "{TOKEN}"
EmailPlaceholderOTP string = "{OTP}"
EmailPlaceholderOTPId string = "{OTP_ID}"
EmailPlaceholderAlertInfo string = "{ALERT_INFO}"
)
var defaultVerificationTemplate = EmailTemplate{
@@ -65,9 +66,10 @@ var defaultOTPTemplate = EmailTemplate{
var defaultAuthAlertTemplate = EmailTemplate{
Subject: "Login from a new location",
Body: `<p>Hello,</p>
<p>We noticed a login to your ` + EmailPlaceholderAppName + ` account from a new location.</p>
<p>If this was you, you may disregard this email.</p>
<p>We noticed a login to your ` + EmailPlaceholderAppName + ` account from a new location:</p>
<p><em>` + EmailPlaceholderAlertInfo + `</em></p>
<p><strong>If this wasn't you, you should immediately change your ` + EmailPlaceholderAppName + ` account password to revoke access from all other locations.</strong></p>
<p>If this was you, you may disregard this email.</p>
<p>
Thanks,<br/>
` + EmailPlaceholderAppName + ` team
+1 -1
View File
@@ -489,7 +489,7 @@ func (validator *collectionValidator) checkRule(value any) error {
return nil // nothing to check
}
r := NewRecordFieldResolver(validator.app, validator.new, nil, true)
r := NewRecordFieldResolver(validator.app, validator.new, &RequestInfo{}, true)
_, err := search.FilterData(vStr).BuildExpr(r)
if err != nil {
return validation.NewError("validation_invalid_rule", "Invalid rule. Raw error: "+err.Error())
+3 -3
View File
@@ -319,8 +319,8 @@ func TestCollectionValidate(t *testing.T) {
c.ListRule = types.Pointer("!invalid")
c.ViewRule = types.Pointer("missing = 123")
c.CreateRule = types.Pointer("id = 123 && missing = 456")
c.UpdateRule = types.Pointer("(id = 123")
c.DeleteRule = types.Pointer("missing = 123")
c.UpdateRule = types.Pointer("@request.body.missing:changed = false")
c.DeleteRule = types.Pointer("(id=123")
return c, nil
},
expectedErrors: []string{"listRule", "viewRule", "createRule", "updateRule", "deleteRule"},
@@ -333,7 +333,7 @@ func TestCollectionValidate(t *testing.T) {
c.ListRule = types.Pointer("")
c.ViewRule = types.Pointer("f1 = 123")
c.CreateRule = types.Pointer("id = 123 && f1 = 456")
c.UpdateRule = types.Pointer("(id = 123)")
c.UpdateRule = types.Pointer("(id = 123 && @request.body.f1:changed = false)")
c.DeleteRule = types.Pointer("f1 = 123")
return c, nil
},
+1 -1
View File
@@ -11,7 +11,7 @@ func DefaultDBConnect(dbPath string) (*dbx.DB, error) {
// Note: the busy_timeout pragma must be first because
// the connection needs to be set to block on busy before WAL mode
// is set in case it hasn't been already set by another connection.
pragmas := "?_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=journal_size_limit(200000000)&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(ON)&_pragma=temp_store(MEMORY)&_pragma=cache_size(-16000)"
pragmas := "?_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=journal_size_limit(200000000)&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(ON)&_pragma=temp_store(MEMORY)&_pragma=cache_size(-32000)"
db, err := dbx.Open("sqlite", dbPath+pragmas)
if err != nil {
+3 -3
View File
@@ -85,11 +85,11 @@ func (app *BaseApp) TableIndexes(tableName string) (map[string]string, error) {
// This method is a no-op if a table with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "tableName" argument must come only from trusted input!
func (app *BaseApp) DeleteTable(tableName string) error {
// "dangerousTableName" argument must come only from trusted input!
func (app *BaseApp) DeleteTable(dangerousTableName string) error {
_, err := app.NonconcurrentDB().NewQuery(fmt.Sprintf(
"DROP TABLE IF EXISTS {{%s}}",
tableName,
dangerousTableName,
)).Execute()
return err
+7
View File
@@ -384,6 +384,13 @@ type FileDownloadRequestEvent struct {
FileField *FileField
ServedPath string
ServedName string
// ThumbError indicates the a thumb wasn't able to be generated
// (e.g. because it didn't satisfy the support image formats or it timed out).
//
// Note that PocketBase fallbacks to the original file in case of a thumb error,
// but developers can check the field and provide their own custom thumb generation if necessary.
ThumbError error
}
// -------------------------------------------------------------------
+39 -14
View File
@@ -31,6 +31,22 @@ var (
_ RecordInterceptor = (*TextField)(nil)
)
var forbiddenPKCharacters = []string{
".", "/", `\`, "|", `"`, "'", "`",
"<", ">", ":", "?", "*", "%", "$",
"\000", "\t", "\n", "\r", " ",
}
// (see largestReservedPKLength)
var caseInsensitiveReservedPKs = []string{
// reserved Windows files names
"CON", "PRN", "AUX", "NUL",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
}
const largestReservedPKLength = 4
// TextField defines "text" type field for storing any string value.
//
// The respective zero record field value is empty string.
@@ -155,8 +171,6 @@ func (f *TextField) PrepareValue(record *Record, raw any) (any, error) {
return cast.ToString(raw), nil
}
var forbiddenPKChars = []string{"/", "\\"}
// ValidateValue implements [Field.ValidateValue] interface method.
func (f *TextField) ValidateValue(ctx context.Context, app App, record *Record) error {
newVal, ok := record.GetRaw(f.Name).(string)
@@ -178,15 +192,6 @@ func (f *TextField) ValidateValue(ctx context.Context, app App, record *Record)
return nil
}
} else {
// disallow PK special characters no matter of the Pattern validator to minimize
// side-effects when the primary key is used for example in a directory path
for _, c := range forbiddenPKChars {
if strings.Contains(newVal, c) {
return validation.NewError("validation_pk_forbidden", "The record primary key contains forbidden characters.").
SetParams(map[string]any{"forbidden": c})
}
}
// this technically shouldn't be necessarily but again to
// minimize misuse of the Pattern validator that could cause
// side-effects on some platforms check for duplicates in a case-insensitive manner
@@ -226,7 +231,7 @@ func (f *TextField) ValidatePlainValue(value string) error {
length := len([]rune(value))
if f.Min > 0 && length < f.Min {
return validation.NewError("validation_min_text_constraint", "Must be at least {{.min}} character(s)").
return validation.NewError("validation_min_text_constraint", "Must be at least {{.min}} character(s).").
SetParams(map[string]any{"min": f.Min})
}
@@ -236,14 +241,34 @@ func (f *TextField) ValidatePlainValue(value string) error {
}
if max > 0 && length > max {
return validation.NewError("validation_max_text_constraint", "Must be no more than {{.max}} character(s)").
return validation.NewError("validation_max_text_constraint", "Must be no more than {{.max}} character(s).").
SetParams(map[string]any{"max": max})
}
if f.Pattern != "" {
match, _ := regexp.MatchString(f.Pattern, value)
if !match {
return validation.NewError("validation_invalid_format", "Invalid value format")
return validation.NewError("validation_invalid_format", "Invalid value format.")
}
}
// additional primary key checks to minimize eventual filesystem compatibility issues
// because the primary key is often used as a file/directory name
if f.PrimaryKey && f.Pattern != defaultLowercaseRecordIdPattern {
for _, ch := range forbiddenPKCharacters {
if strings.Contains(value, ch) {
return validation.NewError("validation_forbidden_pk_character", "'{{.ch}}' is not a valid primary key character.").
SetParams(map[string]any{"ch": ch})
}
}
if largestReservedPKLength >= length {
for _, reserved := range caseInsensitiveReservedPKs {
if strings.EqualFold(value, reserved) {
return validation.NewError("validation_reserved_pk", "The primary key '{{.reserved}}' is reserved and cannot be used.").
SetParams(map[string]any{"reserved": reserved})
}
}
}
}
+94 -4
View File
@@ -129,7 +129,7 @@ func TestTextFieldValidateValue(t *testing.T) {
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "/")
record.SetRaw("test", "abc/")
return record
},
false,
@@ -139,7 +139,37 @@ func TestTextFieldValidateValue(t *testing.T) {
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "\\")
record.SetRaw("test", "abc\\")
return record
},
false,
},
{
"special forbidden character . (non-primaryKey)",
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc.")
return record
},
false,
},
{
"special forbidden character ' ' (non-primaryKey)",
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "ab c")
return record
},
false,
},
{
"special forbidden character * (non-primaryKey)",
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc*")
return record
},
false,
@@ -149,7 +179,7 @@ func TestTextFieldValidateValue(t *testing.T) {
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "/")
record.SetRaw("test", "abc/")
return record
},
true,
@@ -159,11 +189,71 @@ func TestTextFieldValidateValue(t *testing.T) {
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "\\")
record.SetRaw("test", "abc\\")
return record
},
true,
},
{
"special forbidden character . (primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc.")
return record
},
true,
},
{
"special forbidden character ' ' (primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "ab c")
return record
},
true,
},
{
"special forbidden character * (primaryKey; used in the realtime events too)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "abc*")
return record
},
true,
},
{
"reserved pk literal (non-primaryKey)",
&core.TextField{Name: "test", PrimaryKey: false},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "aUx")
return record
},
false,
},
{
"reserved pk literal (primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "aUx")
return record
},
true,
},
{
"reserved pk literal (non-exact match, primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
func() *core.Record {
record := core.NewRecord(collection)
record.SetRaw("test", "aUx-")
return record
},
false,
},
{
"zero field value (primaryKey)",
&core.TextField{Name: "test", PrimaryKey: true},
+177 -21
View File
@@ -9,6 +9,7 @@ import (
"strings"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/inflector"
"github.com/pocketbase/pocketbase/tools/search"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/types"
@@ -17,10 +18,11 @@ import (
// filter modifiers
const (
eachModifier string = "each"
issetModifier string = "isset"
lengthModifier string = "length"
lowerModifier string = "lower"
eachModifier string = "each"
issetModifier string = "isset"
lengthModifier string = "length"
lowerModifier string = "lower"
changedModifier string = "changed"
)
// ensure that `search.FieldResolver` interface is implemented
@@ -46,8 +48,12 @@ type RecordFieldResolver struct {
requestInfo *RequestInfo
staticRequestInfo map[string]any
allowedFields []string
joins []*join
joins []*search.Join
allowHiddenFields bool
// ---
listRuleJoins map[string]*Collection // tableAlias->collection
joinAliasSuffix string // used for uniqueness in the flatten collection list rule join
baseCollectionAlias string
}
// AllowedFields returns a copy of the resolver's allowed fields.
@@ -82,7 +88,7 @@ func NewRecordFieldResolver(
baseCollection: baseCollection,
requestInfo: requestInfo,
allowHiddenFields: allowHiddenFields, // note: it is not based only on the requestInfo.auth since it could be used by a non-request internal method
joins: []*join{},
joins: []*search.Join{},
allowedFields: []string{
`^\w+[\w\.\:]*$`,
`^\@request\.context$`,
@@ -115,18 +121,63 @@ func NewRecordFieldResolver(
return r
}
// @todo think of a better a way how to call it automatically after BuildExpr
//
// UpdateQuery implements `search.FieldResolver` interface.
//
// Conditionally updates the provided search query based on the
// resolved fields (eg. dynamically joining relations).
func (r *RecordFieldResolver) UpdateQuery(query *dbx.SelectQuery) error {
if len(r.joins) > 0 {
query.Distinct(true)
r.updateQueryWithDeduplicateConstraint(query)
for _, join := range r.joins {
query.LeftJoin(
(join.tableName + " " + join.tableAlias),
join.on,
(join.TableName + " " + join.TableAlias),
join.On,
)
}
}
// note: for now the joins are not applied for multi-match conditions to avoid excessive checks
if len(r.listRuleJoins) > 0 {
for alias, c := range r.listRuleJoins {
err := r.updateQueryWithCollectionListRule(c, alias, query)
if err != nil {
return err
}
}
}
return nil
}
func (r *RecordFieldResolver) updateQueryWithCollectionListRule(c *Collection, tableAlias string, query *dbx.SelectQuery) error {
if r.allowHiddenFields || c == nil || c.ListRule == nil || *c.ListRule == "" {
return nil
}
cloneR := *r
cloneR.joins = []*search.Join{}
cloneR.baseCollection = c
cloneR.baseCollectionAlias = tableAlias
cloneR.allowHiddenFields = true
cloneR.joinAliasSuffix = security.PseudorandomString(8)
expr, err := search.FilterData(*c.ListRule).BuildExpr(&cloneR)
if err != nil {
return fmt.Errorf("to buld %q list rule join subquery filter expression: %w", c.Name, err)
}
query.AndWhere(expr)
if len(cloneR.joins) > 0 {
r.updateQueryWithDeduplicateConstraint(query)
for _, j := range cloneR.joins {
query.LeftJoin(
(j.TableName + " " + j.TableAlias),
j.On,
)
}
}
@@ -134,6 +185,79 @@ func (r *RecordFieldResolver) UpdateQuery(query *dbx.SelectQuery) error {
return nil
}
func (r *RecordFieldResolver) updateQueryWithDeduplicateConstraint(query *dbx.SelectQuery) {
query.Distinct(true)
// @todo Research better options for generic rows deduplication.
//
// Disable the GROUP BY conditional checks for now since it prevents
// proper utilization of ORDER BY indexes (and maybe others)
// (https://github.com/pocketbase/pocketbase/discussions/7461)
// info := query.Info()
// if info.Distinct {
// return
// }
// // already has the group by registered
// var groupByCol = r.baseCollection.Name
// if r.baseCollectionAlias != "" {
// groupByCol = r.baseCollectionAlias
// }
// groupByCol += ".id"
// if len(info.GroupBy) > 0 && info.GroupBy[0] == groupByCol {
// return
// }
// // when deemed safe (GROUP BY could have different execution order compared to DISTINCT),
// // prefer GROUP BY to deduplicate only on the id field instead of all columns
// // so that the size of a single row wouldn't matter that much
// if preferGroupBy(info, groupByCol) {
// query.GroupBy(groupByCol)
// } else {
// query.Distinct(true)
// }
}
func preferGroupBy(info *dbx.QueryInfo, fullUnquotedGroupByCol string) bool {
if len(info.GroupBy) != 0 {
return false
}
if info.Having != nil {
return false
}
// dbx fallbacks to * if not set
if len(info.Selects) == 0 {
return true
}
if len(info.Selects) != 1 {
return false
}
identifier := info.Selects[0]
if identifier == "*" || identifier == fullUnquotedGroupByCol {
return true
}
// try again as direct col match in an unquoted column format
identifier = inflector.Columnify(identifier)
if identifier == fullUnquotedGroupByCol {
return true
}
// remains table.* to check
// (aliased columns for now are ignored as they could be represented by expressions)
if !strings.HasSuffix(identifier, ".*") {
return false
}
return strings.HasPrefix(fullUnquotedGroupByCol, strings.TrimSuffix(identifier, "*"))
}
// Resolve implements `search.FieldResolver` interface.
//
// Example of some resolvable fieldName formats:
@@ -186,7 +310,7 @@ func (r *RecordFieldResolver) resolveStaticRequestField(path ...string) (*search
switch v := resultVal.(type) {
case nil:
return &search.ResolverResult{Identifier: "NULL"}, nil
// no further processing is needed...
case string:
// check if it is a number field and explicitly try to cast to
// float in case of a numeric string value was used
@@ -216,8 +340,20 @@ func (r *RecordFieldResolver) resolveStaticRequestField(path ...string) (*search
resultVal = val
}
placeholder := "f" + security.PseudorandomString(8)
// unsupported modifier
// @todo consider deprecating with the introduction of filter functions
if modifier != "" && modifier != lowerModifier {
return nil, fmt.Errorf("invalid modifier sequence %s:%s", lastProp, modifier)
}
// no need to wrap as placeholder if we already know that it is null
if resultVal == nil {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
placeholder := "f" + security.PseudorandomString(10)
// @todo consider deprecating with the introduction of filter functions
if modifier == lowerModifier {
return &search.ResolverResult{
Identifier: "LOWER({:" + placeholder + "})",
@@ -239,23 +375,42 @@ func (r *RecordFieldResolver) loadCollection(collectionNameOrId string) (*Collec
return getCollectionByModelOrIdentifier(r.app, collectionNameOrId)
}
func (r *RecordFieldResolver) registerJoin(tableName string, tableAlias string, on dbx.Expression) {
join := &join{
tableName: tableName,
tableAlias: tableAlias,
on: on,
func (r *RecordFieldResolver) registerJoin(tableName string, tableAlias string, on dbx.Expression) error {
newJoin := &search.Join{
TableName: tableName,
TableAlias: tableAlias,
On: on,
}
// (see updateQueryWithCollectionListRule)
if !r.allowHiddenFields {
c, _ := r.loadCollection(tableName)
// ignore non-collections since the table name could be an expression (e.g. json) or some other subquery
if c != nil {
// treat all fields as if they are hidden
if c.ListRule == nil {
return fmt.Errorf("%q fields can be accessed only when allowHiddenFields is enabled or by superusers", c.Name)
}
if r.listRuleJoins == nil {
r.listRuleJoins = map[string]*Collection{}
}
r.listRuleJoins[newJoin.TableAlias] = c
}
}
// replace existing join
for i, j := range r.joins {
if j.tableAlias == join.tableAlias {
r.joins[i] = join
return
if j.TableAlias == newJoin.TableAlias {
r.joins[i] = newJoin
return nil
}
}
// register new join
r.joins = append(r.joins, join)
r.joins = append(r.joins, newJoin)
return nil
}
type mapExtractor interface {
@@ -395,7 +550,8 @@ func splitModifier(combined string) (string, string, error) {
case issetModifier,
eachModifier,
lengthModifier,
lowerModifier:
lowerModifier,
changedModifier:
return parts[0], parts[1], nil
}
-70
View File
@@ -1,70 +0,0 @@
package core
import (
"fmt"
"strings"
"github.com/pocketbase/dbx"
)
var _ dbx.Expression = (*multiMatchSubquery)(nil)
// join defines the specification for a single SQL JOIN clause.
type join struct {
tableName string
tableAlias string
on dbx.Expression
}
// multiMatchSubquery defines a record multi-match subquery expression.
type multiMatchSubquery struct {
baseTableAlias string
fromTableName string
fromTableAlias string
valueIdentifier string
joins []*join
params dbx.Params
}
// Build converts the expression into a SQL fragment.
//
// Implements [dbx.Expression] interface.
func (m *multiMatchSubquery) Build(db *dbx.DB, params dbx.Params) string {
if m.baseTableAlias == "" || m.fromTableName == "" || m.fromTableAlias == "" {
return "0=1"
}
if params == nil {
params = m.params
} else {
// merge by updating the parent params
for k, v := range m.params {
params[k] = v
}
}
var mergedJoins strings.Builder
for i, j := range m.joins {
if i > 0 {
mergedJoins.WriteString(" ")
}
mergedJoins.WriteString("LEFT JOIN ")
mergedJoins.WriteString(db.QuoteTableName(j.tableName))
mergedJoins.WriteString(" ")
mergedJoins.WriteString(db.QuoteTableName(j.tableAlias))
if j.on != nil {
mergedJoins.WriteString(" ON ")
mergedJoins.WriteString(j.on.Build(db, params))
}
}
return fmt.Sprintf(
`SELECT %s as [[multiMatchValue]] FROM %s %s %s WHERE %s = %s`,
db.QuoteColumnName(m.valueIdentifier),
db.QuoteTableName(m.fromTableName),
db.QuoteTableName(m.fromTableAlias),
mergedJoins.String(),
db.QuoteColumnName(m.fromTableAlias+".id"),
db.QuoteColumnName(m.baseTableAlias+".id"),
)
}
@@ -0,0 +1,31 @@
package core
import (
"strings"
"github.com/pocketbase/dbx"
)
var _ dbx.Expression = (*replaceWithExpression)(nil)
// replaceWithExpression defines a custom expression that will replace
// a placeholder identifier found in "old" with the result of "new".
type replaceWithExpression struct {
placeholder string
old dbx.Expression
new dbx.Expression
}
// Build converts the expression into a SQL fragment.
//
// Implements [dbx.Expression] interface.
func (e *replaceWithExpression) Build(db *dbx.DB, params dbx.Params) string {
if e.placeholder == "" || e.old == nil || e.new == nil {
return "0=1"
}
oldResult := e.old.Build(db, params)
newResult := e.new.Build(db, params)
return strings.ReplaceAll(oldResult, e.placeholder, newResult)
}
+201 -140
View File
@@ -49,14 +49,13 @@ type runner struct {
// shared processing state
// ---------------------------------------------------------------
activeProps []string // holds the active props that remains to be processed
activeCollectionName string // the last used collection name
activeTableAlias string // the last used table alias
allowHiddenFields bool // indicates whether hidden fields (eg. email) should be allowed without extra conditions
nullifyMisingField bool // indicating whether to return null on missing field or return an error
withMultiMatch bool // indicates whether to attach a multiMatchSubquery condition to the ResolverResult
multiMatchActiveTableAlias string // the last used multi-match table alias
multiMatch *multiMatchSubquery // the multi-match subquery expression generated from the fieldName
activeProps []string // holds the active props that remains to be processed
activeCollectionName string // the last used collection name
activeTableAlias string // the last used table alias
nullifyMisingField bool // indicating whether to return null on missing field or return an error
withMultiMatch bool // indicates whether to attach a MultiMatchSubquery condition to the ResolverResult
multiMatchActiveTableAlias string // the last used multi-match table alias
multiMatch *search.MultiMatchSubquery // the multi-match subquery expression generated from the fieldName
}
func (r *runner) run() (*search.ResolverResult, error) {
@@ -81,6 +80,7 @@ func (r *runner) run() (*search.ResolverResult, error) {
}
if r.activeProps[0] == "@request" {
// @todo consider returning an error instead?
if r.resolver.requestInfo == nil {
return &search.ResolverResult{Identifier: "NULL"}, nil
}
@@ -89,7 +89,9 @@ func (r *runner) run() (*search.ResolverResult, error) {
return r.processRequestAuthField()
}
if strings.HasPrefix(r.fieldName, "@request.body.") && len(r.activeProps) > 2 {
totalProps := len(r.activeProps)
if strings.HasPrefix(r.fieldName, "@request.body.") && totalProps > 2 {
name, modifier, err := splitModifier(r.activeProps[2])
if err != nil {
return nil, err
@@ -101,23 +103,21 @@ func (r *runner) run() (*search.ResolverResult, error) {
}
// check for body relation field
if bodyField.Type() == FieldTypeRelation && len(r.activeProps) > 3 {
return r.processRequestInfoRelationField(bodyField)
if bodyField.Type() == FieldTypeRelation && totalProps > 3 {
return r.processRequestBodyRelationField(bodyField)
}
// check for body arrayble fields ":each" modifier
if modifier == eachModifier && len(r.activeProps) == 3 {
return r.processRequestInfoEachModifier(bodyField)
}
// check for body arrayble fields ":length" modifier
if modifier == lengthModifier && len(r.activeProps) == 3 {
return r.processRequestInfoLengthModifier(bodyField)
}
// check for body arrayble fields ":lower" modifier
if modifier == lowerModifier && len(r.activeProps) == 3 {
return r.processRequestInfoLowerModifier(bodyField)
if totalProps == 3 { // aka. last prop
switch modifier {
case eachModifier:
return r.processRequestBodyEachModifier(bodyField)
case lengthModifier:
return r.processRequestBodyLengthModifier(bodyField)
case lowerModifier:
return r.processRequestBodyLowerModifier(bodyField)
case changedModifier:
return r.processRequestBodyChangedModifier(bodyField)
}
}
}
@@ -133,12 +133,10 @@ func (r *runner) prepare() {
r.activeProps = strings.Split(r.fieldName, ".")
r.activeCollectionName = r.resolver.baseCollection.Name
r.activeTableAlias = inflector.Columnify(r.activeCollectionName)
r.allowHiddenFields = r.resolver.allowHiddenFields
// always allow hidden fields since the @.* filter is a system one
if r.activeProps[0] == "@collection" || r.activeProps[0] == "@request" {
r.allowHiddenFields = true
if r.resolver.baseCollectionAlias == "" {
r.activeTableAlias = inflector.Columnify(r.activeCollectionName)
} else {
r.activeTableAlias = r.resolver.baseCollectionAlias
}
// enable the ignore flag for missing @request.* fields for backward
@@ -146,13 +144,13 @@ func (r *runner) prepare() {
r.nullifyMisingField = r.activeProps[0] == "@request"
// prepare a multi-match subquery
r.multiMatch = &multiMatchSubquery{
baseTableAlias: r.activeTableAlias,
params: dbx.Params{},
r.multiMatch = &search.MultiMatchSubquery{
TargetTableAlias: r.activeTableAlias,
Params: dbx.Params{},
}
r.multiMatch.fromTableName = inflector.Columnify(r.activeCollectionName)
r.multiMatch.fromTableAlias = "__mm_" + r.activeTableAlias
r.multiMatchActiveTableAlias = r.multiMatch.fromTableAlias
r.multiMatch.FromTableName = inflector.Columnify(r.activeCollectionName)
r.multiMatch.FromTableAlias = "__mm_" + r.activeTableAlias
r.multiMatchActiveTableAlias = r.multiMatch.FromTableAlias
r.withMultiMatch = false
}
@@ -172,21 +170,24 @@ func (r *runner) processCollectionField() (*search.ResolverResult, error) {
r.activeCollectionName = collection.Name
if len(collectionParts) == 2 && collectionParts[1] != "" {
r.activeTableAlias = inflector.Columnify("__collection_alias_" + collectionParts[1])
r.activeTableAlias = inflector.Columnify("__collection_alias_"+collectionParts[1]) + r.resolver.joinAliasSuffix
} else {
r.activeTableAlias = inflector.Columnify("__collection_" + r.activeCollectionName)
r.activeTableAlias = inflector.Columnify("__collection_"+r.activeCollectionName) + r.resolver.joinAliasSuffix
}
r.withMultiMatch = true
// join the collection to the main query
r.resolver.registerJoin(inflector.Columnify(collection.Name), r.activeTableAlias, nil)
err = r.resolver.registerJoin(inflector.Columnify(collection.Name), r.activeTableAlias, nil)
if err != nil {
return nil, err
}
// join the collection to the multi-match subquery
r.multiMatchActiveTableAlias = "__mm" + r.activeTableAlias
r.multiMatch.joins = append(r.multiMatch.joins, &join{
tableName: inflector.Columnify(collection.Name),
tableAlias: r.multiMatchActiveTableAlias,
r.multiMatchActiveTableAlias = "__mm_" + r.activeTableAlias
r.multiMatch.Joins = append(r.multiMatch.Joins, &search.Join{
TableName: inflector.Columnify(collection.Name),
TableAlias: r.multiMatchActiveTableAlias,
})
// leave only the collection fields
@@ -212,10 +213,10 @@ func (r *runner) processRequestAuthField() (*search.ResolverResult, error) {
collection := r.resolver.requestInfo.Auth.Collection()
r.activeCollectionName = collection.Name
r.activeTableAlias = "__auth_" + inflector.Columnify(r.activeCollectionName)
r.activeTableAlias = "__auth_" + inflector.Columnify(r.activeCollectionName) + r.resolver.joinAliasSuffix
// join the auth collection to the main query
r.resolver.registerJoin(
err := r.resolver.registerJoin(
inflector.Columnify(r.activeCollectionName),
r.activeTableAlias,
dbx.HashExp{
@@ -223,15 +224,18 @@ func (r *runner) processRequestAuthField() (*search.ResolverResult, error) {
(r.activeTableAlias + ".id"): r.resolver.requestInfo.Auth.Id,
},
)
if err != nil {
return nil, err
}
// join the auth collection to the multi-match subquery
r.multiMatchActiveTableAlias = "__mm_" + r.activeTableAlias
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: inflector.Columnify(r.activeCollectionName),
tableAlias: r.multiMatchActiveTableAlias,
on: dbx.HashExp{
r.multiMatch.Joins = append(
r.multiMatch.Joins,
&search.Join{
TableName: inflector.Columnify(r.activeCollectionName),
TableAlias: r.multiMatchActiveTableAlias,
On: dbx.HashExp{
(r.multiMatchActiveTableAlias + ".id"): r.resolver.requestInfo.Auth.Id,
},
},
@@ -268,10 +272,37 @@ func toSlice(value any) []any {
return result
}
func (r *runner) processRequestInfoLowerModifier(bodyField Field) (*search.ResolverResult, error) {
func (r *runner) processRequestBodyChangedModifier(bodyField Field) (*search.ResolverResult, error) {
name := bodyField.GetName()
alias := search.FilterData(fmt.Sprintf("@request.body.%s:isset = true && @request.body.%s != %s", name, name, name))
aliasExpr, err := alias.BuildExpr(r.resolver)
if err != nil {
return nil, err
}
placeholder := "@changed@" + name + security.PseudorandomString(8)
result := &search.ResolverResult{
Identifier: placeholder,
NullFallback: search.NullFallbackDisabled,
AfterBuild: func(expr dbx.Expression) dbx.Expression {
return &replaceWithExpression{
placeholder: placeholder,
old: expr,
new: aliasExpr,
}
},
}
return result, nil
}
func (r *runner) processRequestBodyLowerModifier(bodyField Field) (*search.ResolverResult, error) {
rawValue := cast.ToString(r.resolver.requestInfo.Body[bodyField.GetName()])
placeholder := "infoLower" + bodyField.GetName() + security.PseudorandomString(6)
placeholder := "infoLower" + bodyField.GetName() + security.PseudorandomString(8)
result := &search.ResolverResult{
Identifier: "LOWER({:" + placeholder + "})",
@@ -281,7 +312,7 @@ func (r *runner) processRequestInfoLowerModifier(bodyField Field) (*search.Resol
return result, nil
}
func (r *runner) processRequestInfoLengthModifier(bodyField Field) (*search.ResolverResult, error) {
func (r *runner) processRequestBodyLengthModifier(bodyField Field) (*search.ResolverResult, error) {
if _, ok := bodyField.(MultiValuer); !ok {
return nil, fmt.Errorf("field %q doesn't support multivalue operations", bodyField.GetName())
}
@@ -295,7 +326,7 @@ func (r *runner) processRequestInfoLengthModifier(bodyField Field) (*search.Reso
return result, nil
}
func (r *runner) processRequestInfoEachModifier(bodyField Field) (*search.ResolverResult, error) {
func (r *runner) processRequestBodyEachModifier(bodyField Field) (*search.ResolverResult, error) {
multiValuer, ok := bodyField.(MultiValuer)
if !ok {
return nil, fmt.Errorf("field %q doesn't support multivalue operations", bodyField.GetName())
@@ -307,11 +338,15 @@ func (r *runner) processRequestInfoEachModifier(bodyField Field) (*search.Resolv
return nil, fmt.Errorf("cannot serialize the data for field %q", r.activeProps[2])
}
placeholder := "dataEach" + security.PseudorandomString(6)
placeholder := "dataEach" + security.PseudorandomString(8)
cleanFieldName := inflector.Columnify(bodyField.GetName())
jeTable := fmt.Sprintf("json_each({:%s})", placeholder)
jeAlias := "__dataEach_" + cleanFieldName + "_je"
r.resolver.registerJoin(jeTable, jeAlias, nil)
jeAlias := "__dataEach_je_" + cleanFieldName + r.resolver.joinAliasSuffix
err = r.resolver.registerJoin(jeTable, jeAlias, nil)
if err != nil {
return nil, err
}
result := &search.ResolverResult{
Identifier: fmt.Sprintf("[[%s.value]]", jeAlias),
@@ -325,14 +360,14 @@ func (r *runner) processRequestInfoEachModifier(bodyField Field) (*search.Resolv
if r.withMultiMatch {
placeholder2 := "mm" + placeholder
jeTable2 := fmt.Sprintf("json_each({:%s})", placeholder2)
jeAlias2 := "__mm" + jeAlias
jeAlias2 := "__mm_" + jeAlias
r.multiMatch.joins = append(r.multiMatch.joins, &join{
tableName: jeTable2,
tableAlias: jeAlias2,
r.multiMatch.Joins = append(r.multiMatch.Joins, &search.Join{
TableName: jeTable2,
TableAlias: jeAlias2,
})
r.multiMatch.params[placeholder2] = bodyItemsRaw
r.multiMatch.valueIdentifier = fmt.Sprintf("[[%s.value]]", jeAlias2)
r.multiMatch.Params[placeholder2] = bodyItemsRaw
r.multiMatch.ValueIdentifier = fmt.Sprintf("[[%s.value]]", jeAlias2)
result.MultiMatchSubQuery = r.multiMatch
}
@@ -340,7 +375,7 @@ func (r *runner) processRequestInfoEachModifier(bodyField Field) (*search.Resolv
return result, nil
}
func (r *runner) processRequestInfoRelationField(bodyField Field) (*search.ResolverResult, error) {
func (r *runner) processRequestBodyRelationField(bodyField Field) (*search.ResolverResult, error) {
relField, ok := bodyField.(*RelationField)
if !ok {
return nil, fmt.Errorf("failed to initialize data relation field %q", bodyField.GetName())
@@ -360,10 +395,10 @@ func (r *runner) processRequestInfoRelationField(bodyField Field) (*search.Resol
}
r.activeCollectionName = dataRelCollection.Name
r.activeTableAlias = inflector.Columnify("__data_" + dataRelCollection.Name + "_" + relField.Name)
r.activeTableAlias = inflector.Columnify("__data_"+dataRelCollection.Name+"_"+relField.Name) + r.resolver.joinAliasSuffix
// join the data rel collection to the main collection
r.resolver.registerJoin(
err = r.resolver.registerJoin(
r.activeCollectionName,
r.activeTableAlias,
dbx.In(
@@ -371,19 +406,22 @@ func (r *runner) processRequestInfoRelationField(bodyField Field) (*search.Resol
list.ToInterfaceSlice(dataRelIds)...,
),
)
if err != nil {
return nil, err
}
if relField.IsMultiple() {
r.withMultiMatch = true
}
// join the data rel collection to the multi-match subquery
r.multiMatchActiveTableAlias = inflector.Columnify("__data_mm_" + dataRelCollection.Name + "_" + relField.Name)
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: r.activeCollectionName,
tableAlias: r.multiMatchActiveTableAlias,
on: dbx.In(
r.multiMatchActiveTableAlias = "__mm_" + r.activeTableAlias
r.multiMatch.Joins = append(
r.multiMatch.Joins,
&search.Join{
TableName: r.activeCollectionName,
TableAlias: r.multiMatchActiveTableAlias,
On: dbx.In(
fmt.Sprintf("[[%s.id]]", r.multiMatchActiveTableAlias),
list.ToInterfaceSlice(dataRelIds)...,
),
@@ -399,6 +437,7 @@ func (r *runner) processRequestInfoRelationField(bodyField Field) (*search.Resol
var viaRegex = regexp.MustCompile(`^(\w+)_via_(\w+)$`)
// @todo refactor and abstract lastProp processing with the support of field plugins
func (r *runner) processActiveProps() (*search.ResolverResult, error) {
totalProps := len(r.activeProps)
@@ -410,17 +449,17 @@ func (r *runner) processActiveProps() (*search.ResolverResult, error) {
// last prop
if i == totalProps-1 {
return r.processLastProp(collection, prop)
return r.finalizeActivePropsProcessing(collection, prop, i)
}
field := collection.Fields.GetByName(prop)
if field != nil && field.GetHidden() && !r.allowHiddenFields {
if field != nil && field.GetHidden() && !r.resolver.allowHiddenFields {
return nil, fmt.Errorf("non-filterable field %q", prop)
}
// @todo consider moving to the finalizer and converting to "JSONExtractable" interface with optional extra validation for the remaining props?
// json or geoPoint field -> treat the rest of the props as json path
// @todo consider converting to "JSONExtractable" interface with optional extra validation for the remaining props?
if field != nil && (field.Type() == FieldTypeJSON || field.Type() == FieldTypeGeoPoint) {
var jsonPath strings.Builder
for j, p := range r.activeProps[i+1:] {
@@ -438,12 +477,12 @@ func (r *runner) processActiveProps() (*search.ResolverResult, error) {
jsonPathStr := jsonPath.String()
result := &search.ResolverResult{
NoCoalesce: true,
Identifier: dbutils.JSONExtract(r.activeTableAlias+"."+inflector.Columnify(prop), jsonPathStr),
NullFallback: search.NullFallbackDisabled,
Identifier: dbutils.JSONExtract(r.activeTableAlias+"."+inflector.Columnify(prop), jsonPathStr),
}
if r.withMultiMatch {
r.multiMatch.valueIdentifier = dbutils.JSONExtract(r.multiMatchActiveTableAlias+"."+inflector.Columnify(prop), jsonPathStr)
r.multiMatch.ValueIdentifier = dbutils.JSONExtract(r.multiMatchActiveTableAlias+"."+inflector.Columnify(prop), jsonPathStr)
result.MultiMatchSubQuery = r.multiMatch
}
@@ -488,7 +527,7 @@ func (r *runner) processActiveProps() (*search.ResolverResult, error) {
return nil, fmt.Errorf("invalid back relation field %q", parts[2])
}
if backField.GetHidden() && !r.allowHiddenFields {
if backField.GetHidden() && !r.resolver.allowHiddenFields {
return nil, fmt.Errorf("non-filterable back relation field %q", backField.GetName())
}
@@ -508,25 +547,24 @@ func (r *runner) processActiveProps() (*search.ResolverResult, error) {
// ---
cleanProp := inflector.Columnify(prop)
cleanBackFieldName := inflector.Columnify(backRelField.Name)
newTableAlias := r.activeTableAlias + "_" + cleanProp
newTableAlias := r.activeTableAlias + "_" + cleanProp + r.resolver.joinAliasSuffix
newCollectionName := inflector.Columnify(backCollection.Name)
isBackRelMultiple := backRelField.IsMultiple()
if !isBackRelMultiple {
// additionally check if the rel field has a single column unique index
_, hasUniqueIndex := dbutils.FindSingleColumnUniqueIndex(backCollection.Indexes, backRelField.Name)
isBackRelMultiple = !hasUniqueIndex
}
if !isBackRelMultiple {
r.resolver.registerJoin(
err := r.resolver.registerJoin(
newCollectionName,
newTableAlias,
dbx.NewExp(fmt.Sprintf("[[%s.%s]] = [[%s.id]]", newTableAlias, cleanBackFieldName, r.activeTableAlias)),
)
if err != nil {
return nil, err
}
} else {
jeAlias := r.activeTableAlias + "_" + cleanProp + "_je"
r.resolver.registerJoin(
jeAlias := "__je_" + newTableAlias
err := r.resolver.registerJoin(
newCollectionName,
newTableAlias,
dbx.NewExp(fmt.Sprintf(
@@ -537,6 +575,9 @@ func (r *runner) processActiveProps() (*search.ResolverResult, error) {
jeAlias,
)),
)
if err != nil {
return nil, err
}
}
r.activeCollectionName = newCollectionName
@@ -547,27 +588,32 @@ func (r *runner) processActiveProps() (*search.ResolverResult, error) {
// ---
if isBackRelMultiple {
r.withMultiMatch = true // enable multimatch if not already
} else if !r.withMultiMatch {
// additionally check if the rel field has a single column unique index;
// if not - apply a multi-match check
_, hasUniqueIndex := dbutils.FindSingleColumnUniqueIndex(backCollection.Indexes, backRelField.Name)
r.withMultiMatch = !hasUniqueIndex
}
newTableAlias2 := r.multiMatchActiveTableAlias + "_" + cleanProp
newTableAlias2 := r.multiMatchActiveTableAlias + "_" + cleanProp + r.resolver.joinAliasSuffix
if !isBackRelMultiple {
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: newCollectionName,
tableAlias: newTableAlias2,
on: dbx.NewExp(fmt.Sprintf("[[%s.%s]] = [[%s.id]]", newTableAlias2, cleanBackFieldName, r.multiMatchActiveTableAlias)),
r.multiMatch.Joins = append(
r.multiMatch.Joins,
&search.Join{
TableName: newCollectionName,
TableAlias: newTableAlias2,
On: dbx.NewExp(fmt.Sprintf("[[%s.%s]] = [[%s.id]]", newTableAlias2, cleanBackFieldName, r.multiMatchActiveTableAlias)),
},
)
} else {
jeAlias2 := r.multiMatchActiveTableAlias + "_" + cleanProp + "_je"
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: newCollectionName,
tableAlias: newTableAlias2,
on: dbx.NewExp(fmt.Sprintf(
jeAlias2 := "__je_" + newTableAlias2
r.multiMatch.Joins = append(
r.multiMatch.Joins,
&search.Join{
TableName: newCollectionName,
TableAlias: newTableAlias2,
On: dbx.NewExp(fmt.Sprintf(
"[[%s.id]] IN (SELECT [[%s.value]] FROM %s {{%s}})",
r.multiMatchActiveTableAlias,
jeAlias2,
@@ -607,28 +653,39 @@ func (r *runner) processActiveProps() (*search.ResolverResult, error) {
if !relField.IsMultiple() &&
// the penultimate prop is "id"
i == totalProps-2 && r.activeProps[i+1] == FieldNameId {
return r.processLastProp(collection, relField.Name)
return r.finalizeActivePropsProcessing(collection, relField.Name, i)
}
cleanFieldName := inflector.Columnify(relField.Name)
prefixedFieldName := r.activeTableAlias + "." + cleanFieldName
newTableAlias := r.activeTableAlias + "_" + cleanFieldName
newTableAlias := r.activeTableAlias + "_" + cleanFieldName + r.resolver.joinAliasSuffix
newCollectionName := relCollection.Name
if !relField.IsMultiple() {
r.resolver.registerJoin(
err := r.resolver.registerJoin(
inflector.Columnify(newCollectionName),
newTableAlias,
dbx.NewExp(fmt.Sprintf("[[%s.id]] = [[%s]]", newTableAlias, prefixedFieldName)),
)
if err != nil {
return nil, err
}
} else {
jeAlias := r.activeTableAlias + "_" + cleanFieldName + "_je"
r.resolver.registerJoin(dbutils.JSONEach(prefixedFieldName), jeAlias, nil)
r.resolver.registerJoin(
jeAlias := "__je_" + newTableAlias
err := r.resolver.registerJoin(dbutils.JSONEach(prefixedFieldName), jeAlias, nil)
if err != nil {
return nil, err
}
err = r.resolver.registerJoin(
inflector.Columnify(newCollectionName),
newTableAlias,
dbx.NewExp(fmt.Sprintf("[[%s.id]] = [[%s.value]]", newTableAlias, jeAlias)),
)
if err != nil {
return nil, err
}
}
r.activeCollectionName = newCollectionName
@@ -645,26 +702,26 @@ func (r *runner) processActiveProps() (*search.ResolverResult, error) {
prefixedFieldName2 := r.multiMatchActiveTableAlias + "." + cleanFieldName
if !relField.IsMultiple() {
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: inflector.Columnify(newCollectionName),
tableAlias: newTableAlias2,
on: dbx.NewExp(fmt.Sprintf("[[%s.id]] = [[%s]]", newTableAlias2, prefixedFieldName2)),
r.multiMatch.Joins = append(
r.multiMatch.Joins,
&search.Join{
TableName: inflector.Columnify(newCollectionName),
TableAlias: newTableAlias2,
On: dbx.NewExp(fmt.Sprintf("[[%s.id]] = [[%s]]", newTableAlias2, prefixedFieldName2)),
},
)
} else {
jeAlias2 := r.multiMatchActiveTableAlias + "_" + cleanFieldName + "_je"
r.multiMatch.joins = append(
r.multiMatch.joins,
&join{
tableName: dbutils.JSONEach(prefixedFieldName2),
tableAlias: jeAlias2,
r.multiMatch.Joins = append(
r.multiMatch.Joins,
&search.Join{
TableName: dbutils.JSONEach(prefixedFieldName2),
TableAlias: jeAlias2,
},
&join{
tableName: inflector.Columnify(newCollectionName),
tableAlias: newTableAlias2,
on: dbx.NewExp(fmt.Sprintf("[[%s.id]] = [[%s.value]]", newTableAlias2, jeAlias2)),
&search.Join{
TableName: inflector.Columnify(newCollectionName),
TableAlias: newTableAlias2,
On: dbx.NewExp(fmt.Sprintf("[[%s.id]] = [[%s.value]]", newTableAlias2, jeAlias2)),
},
)
}
@@ -676,7 +733,7 @@ func (r *runner) processActiveProps() (*search.ResolverResult, error) {
return nil, fmt.Errorf("failed to resolve field %q", r.fieldName)
}
func (r *runner) processLastProp(collection *Collection, prop string) (*search.ResolverResult, error) {
func (r *runner) finalizeActivePropsProcessing(collection *Collection, prop string, propDepth int) (*search.ResolverResult, error) {
name, modifier, err := splitModifier(prop)
if err != nil {
return nil, err
@@ -690,7 +747,7 @@ func (r *runner) processLastProp(collection *Collection, prop string) (*search.R
return nil, fmt.Errorf("unknown field %q", name)
}
if field.GetHidden() && !r.allowHiddenFields {
if field.GetHidden() && !r.resolver.allowHiddenFields {
return nil, fmt.Errorf("non-filterable field %q", name)
}
@@ -709,7 +766,7 @@ func (r *runner) processLastProp(collection *Collection, prop string) (*search.R
if r.withMultiMatch {
jePair2 := r.multiMatchActiveTableAlias + "." + cleanFieldName
r.multiMatch.valueIdentifier = dbutils.JSONArrayLength(jePair2)
r.multiMatch.ValueIdentifier = dbutils.JSONArrayLength(jePair2)
result.MultiMatchSubQuery = r.multiMatch
}
@@ -720,8 +777,12 @@ func (r *runner) processLastProp(collection *Collection, prop string) (*search.R
// -------------------------------------------------------
if modifier == eachModifier && isMultivaluer {
jePair := r.activeTableAlias + "." + cleanFieldName
jeAlias := r.activeTableAlias + "_" + cleanFieldName + "_je"
r.resolver.registerJoin(dbutils.JSONEach(jePair), jeAlias, nil)
jeAlias := "__je_" + r.activeTableAlias + "_" + cleanFieldName + r.resolver.joinAliasSuffix
err := r.resolver.registerJoin(dbutils.JSONEach(jePair), jeAlias, nil)
if err != nil {
return nil, err
}
result := &search.ResolverResult{
Identifier: fmt.Sprintf("[[%s.value]]", jeAlias),
@@ -733,13 +794,13 @@ func (r *runner) processLastProp(collection *Collection, prop string) (*search.R
if r.withMultiMatch {
jePair2 := r.multiMatchActiveTableAlias + "." + cleanFieldName
jeAlias2 := r.multiMatchActiveTableAlias + "_" + cleanFieldName + "_je"
jeAlias2 := "__je_" + r.multiMatchActiveTableAlias + "_" + cleanFieldName + r.resolver.joinAliasSuffix
r.multiMatch.joins = append(r.multiMatch.joins, &join{
tableName: dbutils.JSONEach(jePair2),
tableAlias: jeAlias2,
r.multiMatch.Joins = append(r.multiMatch.Joins, &search.Join{
TableName: dbutils.JSONEach(jePair2),
TableAlias: jeAlias2,
})
r.multiMatch.valueIdentifier = fmt.Sprintf("[[%s.value]]", jeAlias2)
r.multiMatch.ValueIdentifier = fmt.Sprintf("[[%s.value]]", jeAlias2)
result.MultiMatchSubQuery = r.multiMatch
}
@@ -754,12 +815,12 @@ func (r *runner) processLastProp(collection *Collection, prop string) (*search.R
}
if r.withMultiMatch {
r.multiMatch.valueIdentifier = "[[" + r.multiMatchActiveTableAlias + "." + cleanFieldName + "]]"
r.multiMatch.ValueIdentifier = "[[" + r.multiMatchActiveTableAlias + "." + cleanFieldName + "]]"
result.MultiMatchSubQuery = r.multiMatch
}
// allow querying only auth records with emails marked as public
if field.GetName() == FieldNameEmail && !r.allowHiddenFields && collection.IsAuth() {
if field.GetName() == FieldNameEmail && !r.resolver.allowHiddenFields && collection.IsAuth() {
result.AfterBuild = func(expr dbx.Expression) dbx.Expression {
return dbx.Enclose(dbx.And(expr, dbx.NewExp(fmt.Sprintf(
"[[%s.%s]] = TRUE",
@@ -773,10 +834,10 @@ func (r *runner) processLastProp(collection *Collection, prop string) (*search.R
// stored as json work correctly when compared to their SQL equivalent
// (https://github.com/pocketbase/pocketbase/issues/4068)
if field.Type() == FieldTypeJSON {
result.NoCoalesce = true
result.NullFallback = search.NullFallbackDisabled
result.Identifier = dbutils.JSONExtract(r.activeTableAlias+"."+cleanFieldName, "")
if r.withMultiMatch {
r.multiMatch.valueIdentifier = dbutils.JSONExtract(r.multiMatchActiveTableAlias+"."+cleanFieldName, "")
r.multiMatch.ValueIdentifier = dbutils.JSONExtract(r.multiMatchActiveTableAlias+"."+cleanFieldName, "")
}
}
@@ -784,7 +845,7 @@ func (r *runner) processLastProp(collection *Collection, prop string) (*search.R
if modifier == lowerModifier {
result.Identifier = "LOWER(" + result.Identifier + ")"
if r.withMultiMatch {
r.multiMatch.valueIdentifier = "LOWER(" + r.multiMatch.valueIdentifier + ")"
r.multiMatch.ValueIdentifier = "LOWER(" + r.multiMatch.ValueIdentifier + ")"
}
}
File diff suppressed because one or more lines are too long
+20 -3
View File
@@ -314,9 +314,19 @@ func (app *BaseApp) FindAllRecords(collectionModelOrIdentifier any, exprs ...dbx
// FindFirstRecordByData returns the first found record matching
// the provided key-value pair.
func (app *BaseApp) FindFirstRecordByData(collectionModelOrIdentifier any, key string, value any) (*Record, error) {
collection, err := getCollectionByModelOrIdentifier(app, collectionModelOrIdentifier)
if err != nil {
return nil, err
}
field := collection.Fields.GetByName(key)
if field == nil {
return nil, errors.New("invalid or missing field " + key)
}
record := &Record{}
err := app.RecordQuery(collectionModelOrIdentifier).
err = app.RecordQuery(collection).
AndWhere(dbx.HashExp{inflector.Columnify(key): value}).
Limit(1).
One(record)
@@ -397,7 +407,10 @@ func (app *BaseApp) FindRecordsByFilter(
}
}
resolver.UpdateQuery(q) // attaches any adhoc joins and aliases
err = resolver.UpdateQuery(q) // attaches any adhoc joins and aliases
if err != nil {
return nil, err
}
// ---
if offset > 0 {
@@ -611,7 +624,11 @@ func (app *BaseApp) CanAccessRecord(record *Record, requestInfo *RequestInfo, ac
if err != nil {
return false, err
}
resolver.UpdateQuery(query)
err = resolver.UpdateQuery(query)
if err != nil {
return false, err
}
err = query.AndWhere(expr).Limit(1).Row(&exists)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
+7
View File
@@ -525,6 +525,13 @@ func TestFindFirstRecordByData(t *testing.T) {
"",
true,
},
{
"demo2",
"invalid_or_missing",
"llvuca81nly1qls",
"",
true,
},
{
"demo2",
"id",
+2 -2
View File
@@ -423,7 +423,7 @@ type BatchConfig struct {
// MaxRequests is the maximum allowed batch request to execute.
MaxRequests int `form:"maxRequests" json:"maxRequests"`
// Timeout is the the max duration in seconds to wait before cancelling the batch transaction.
// Timeout is the max duration in seconds to wait before cancelling the batch transaction.
Timeout int64 `form:"timeout" json:"timeout"`
// MaxBodySize is the maximum allowed batch request body size in bytes.
@@ -449,7 +449,7 @@ type BackupsConfig struct {
// Leave it empty to disable the auto backups functionality.
Cron string `form:"cron" json:"cron"`
// CronMaxKeep is the the max number of cron generated backups to
// CronMaxKeep is the max number of cron generated backups to
// keep before removing older entries.
//
// This field works only when the cron config has valid cron expression.
+19 -16
View File
@@ -19,11 +19,11 @@ import (
// This method is a no-op if a view with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "name" argument must come only from trusted input!
func (app *BaseApp) DeleteView(name string) error {
// "dangerousViewName" argument must come only from trusted input!
func (app *BaseApp) DeleteView(dangerousViewName string) error {
_, err := app.DB().NewQuery(fmt.Sprintf(
"DROP VIEW IF EXISTS {{%s}}",
name,
dangerousViewName,
)).Execute()
return err
@@ -31,19 +31,19 @@ func (app *BaseApp) DeleteView(name string) error {
// SaveView creates (or updates already existing) persistent SQL view.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "selectQuery" argument must come only from trusted input!
func (app *BaseApp) SaveView(name string, selectQuery string) error {
// NB! Be aware that this method is vulnerable to SQL injection and
// its arguments must come only from trusted input!
func (app *BaseApp) SaveView(dangerousViewName string, dangerousSelectQuery string) error {
return app.RunInTransaction(func(txApp App) error {
// delete old view (if exists)
if err := txApp.DeleteView(name); err != nil {
if err := txApp.DeleteView(dangerousViewName); err != nil {
return err
}
selectQuery = strings.Trim(strings.TrimSpace(selectQuery), ";")
dangerousSelectQuery = strings.Trim(strings.TrimSpace(dangerousSelectQuery), ";")
// try to loosely detect multiple inline statements
tk := tokenizer.NewFromString(selectQuery)
tk := tokenizer.NewFromString(dangerousSelectQuery)
tk.Separators(';')
if queryParts, _ := tk.ScanAll(); len(queryParts) > 1 {
return errors.New("multiple statements are not supported")
@@ -53,17 +53,17 @@ func (app *BaseApp) SaveView(name string, selectQuery string) error {
//
// note: the query is wrapped in a secondary SELECT as a rudimentary
// measure to discourage multiple inline sql statements execution
viewQuery := fmt.Sprintf("CREATE VIEW {{%s}} AS SELECT * FROM (%s)", name, selectQuery)
viewQuery := fmt.Sprintf("CREATE VIEW {{%s}} AS SELECT * FROM (%s)", dangerousViewName, dangerousSelectQuery)
if _, err := txApp.DB().NewQuery(viewQuery).Execute(); err != nil {
return err
}
// fetch the view table info to ensure that the view was created
// because missing tables or columns won't return an error
if _, err := txApp.TableInfo(name); err != nil {
if _, err := txApp.TableInfo(dangerousViewName); err != nil {
// manually cleanup previously created view in case the func
// is called in a nested transaction and the error is discarded
txApp.DeleteView(name)
txApp.DeleteView(dangerousViewName)
return err
}
@@ -77,18 +77,21 @@ func (app *BaseApp) SaveView(name string, selectQuery string) error {
// There are some caveats:
// - The select query must have an "id" column.
// - Wildcard ("*") columns are not supported to avoid accidentally leaking sensitive data.
func (app *BaseApp) CreateViewFields(selectQuery string) (FieldsList, error) {
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "dangerousSelectQuery" argument must come only from trusted input!
func (app *BaseApp) CreateViewFields(dangerousSelectQuery string) (FieldsList, error) {
result := NewFieldsList()
suggestedFields, err := parseQueryToFields(app, selectQuery)
suggestedFields, err := parseQueryToFields(app, dangerousSelectQuery)
if err != nil {
return result, err
}
// note wrap in a transaction in case the selectQuery contains
// note wrap in a transaction in case the dangerousSelectQuery contains
// multiple statements allowing us to rollback on any error
txErr := app.RunInTransaction(func(txApp App) error {
info, err := getQueryTableInfo(txApp, selectQuery)
info, err := getQueryTableInfo(txApp, dangerousSelectQuery)
if err != nil {
return err
}
+3 -1
View File
@@ -7,6 +7,7 @@ import (
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/mails"
"github.com/pocketbase/pocketbase/tools/types"
)
const (
@@ -109,7 +110,8 @@ func (form *TestEmailSend) Submit() error {
case TestTemplateOTP:
return mails.SendRecordOTP(form.app, record, "_PB_TEST_OTP_ID_", "123456")
case TestTemplateAuthAlert:
return mails.SendRecordAuthAlert(form.app, record)
testEvent := types.NowDateTime().String() + " - TEST_IP TEST_USER_AGENT"
return mails.SendRecordAuthAlert(form.app, record, testEvent)
default:
return errors.New("unknown template " + form.Template)
}
+20 -20
View File
@@ -5,24 +5,24 @@ go 1.24.0
require (
github.com/disintegration/imaging v1.6.2
github.com/domodwyer/mailyak/v3 v3.6.2
github.com/dop251/goja v0.0.0-20250630131328-58d95d85e994
github.com/dop251/goja_nodejs v0.0.0-20250409162600-f7acab6894b0
github.com/dop251/goja v0.0.0-20260106131823-651366fbe6e3
github.com/dop251/goja_nodejs v0.0.0-20260212111938-1f56ff5bcf14
github.com/fatih/color v1.18.0
github.com/fsnotify/fsnotify v1.7.0
github.com/gabriel-vasile/mimetype v1.4.10
github.com/gabriel-vasile/mimetype v1.4.13
github.com/ganigeorgiev/fexpr v0.5.0
github.com/go-ozzo/ozzo-validation/v4 v4.3.0
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/pocketbase/dbx v1.11.0
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/pocketbase/dbx v1.12.0
github.com/pocketbase/tygoja v0.0.0-20250812183945-97ffe055281f
github.com/spf13/cast v1.10.0
github.com/spf13/cobra v1.10.1
golang.org/x/crypto v0.42.0
golang.org/x/image v0.31.0
golang.org/x/net v0.44.0
golang.org/x/oauth2 v0.31.0
golang.org/x/sync v0.17.0
modernc.org/sqlite v1.39.0
github.com/spf13/cobra v1.10.2
golang.org/x/crypto v0.47.0
golang.org/x/image v0.35.0
golang.org/x/net v0.49.0
golang.org/x/oauth2 v0.34.0
golang.org/x/sync v0.19.0
modernc.org/sqlite v1.45.0
)
require (
@@ -31,20 +31,20 @@ require (
github.com/dop251/base64dec v0.0.0-20231022112746-c6c9f9a96217 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e // indirect
github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/spf13/pflag v1.0.10 // indirect
golang.org/x/exp v0.0.0-20250911091902-df9299821621 // indirect
golang.org/x/mod v0.28.0 // indirect
golang.org/x/sys v0.36.0 // indirect
golang.org/x/text v0.29.0 // indirect
golang.org/x/tools v0.37.0 // indirect
modernc.org/libc v1.66.3 // indirect
golang.org/x/exp v0.0.0-20260112195511-716be5621a96 // indirect
golang.org/x/mod v0.32.0 // indirect
golang.org/x/sys v0.40.0 // indirect
golang.org/x/text v0.33.0 // indirect
golang.org/x/tools v0.41.0 // indirect
modernc.org/libc v1.67.6 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
)
+51 -47
View File
@@ -14,10 +14,10 @@ github.com/domodwyer/mailyak/v3 v3.6.2 h1:x3tGMsyFhTCaxp6ycgR0FE/bu5QiNp+hetUuCO
github.com/domodwyer/mailyak/v3 v3.6.2/go.mod h1:lOm/u9CyCVWHeaAmHIdF4RiKVxKUT/H5XX10lIKAL6c=
github.com/dop251/base64dec v0.0.0-20231022112746-c6c9f9a96217 h1:16iT9CBDOniJwFGPI41MbUDfEk74hFaKTqudrX8kenY=
github.com/dop251/base64dec v0.0.0-20231022112746-c6c9f9a96217/go.mod h1:eIb+f24U+eWQCIsj9D/ah+MD9UP+wdxuqzsdLD+mhGM=
github.com/dop251/goja v0.0.0-20250630131328-58d95d85e994 h1:aQYWswi+hRL2zJqGacdCZx32XjKYV8ApXFGntw79XAM=
github.com/dop251/goja v0.0.0-20250630131328-58d95d85e994/go.mod h1:MxLav0peU43GgvwVgNbLAj1s/bSGboKkhuULvq/7hx4=
github.com/dop251/goja_nodejs v0.0.0-20250409162600-f7acab6894b0 h1:fuHXpEVTTk7TilRdfGRLHpiTD6tnT0ihEowCfWjlFvw=
github.com/dop251/goja_nodejs v0.0.0-20250409162600-f7acab6894b0/go.mod h1:Tb7Xxye4LX7cT3i8YLvmPMGCV92IOi4CDZvm/V8ylc0=
github.com/dop251/goja v0.0.0-20260106131823-651366fbe6e3 h1:bVp3yUzvSAJzu9GqID+Z96P+eu5TKnIMJSV4QaZMauM=
github.com/dop251/goja v0.0.0-20260106131823-651366fbe6e3/go.mod h1:MxLav0peU43GgvwVgNbLAj1s/bSGboKkhuULvq/7hx4=
github.com/dop251/goja_nodejs v0.0.0-20260212111938-1f56ff5bcf14 h1:3U8dTgyNBhEQ/GVw0jZW5q+93Zw2gAZPRWhJ9TwV3rM=
github.com/dop251/goja_nodejs v0.0.0-20260212111938-1f56ff5bcf14/go.mod h1:Tb7Xxye4LX7cT3i8YLvmPMGCV92IOi4CDZvm/V8ylc0=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
@@ -26,8 +26,8 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0=
github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/ganigeorgiev/fexpr v0.5.0 h1:XA9JxtTE/Xm+g/JFI6RfZEHSiQlk+1glLvRK1Lpv/Tk=
github.com/ganigeorgiev/fexpr v0.5.0/go.mod h1:RyGiGqmeXhEQ6+mlGdnUleLHgtzzu/VGO2WtJkF5drE=
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 h1:byhDUpfEwjsVQb1vBunvIjh2BHQ9ead57VkAEY4V+Es=
@@ -36,15 +36,17 @@ github.com/go-sourcemap/sourcemap v2.1.4+incompatible h1:a+iTbH5auLKxaNwQFg0B+TC
github.com/go-sourcemap/sourcemap v2.1.4+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg=
github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc=
github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
@@ -55,12 +57,12 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pocketbase/dbx v1.11.0 h1:LpZezioMfT3K4tLrqA55wWFw1EtH1pM4tzSVa7kgszU=
github.com/pocketbase/dbx v1.11.0/go.mod h1:xXRCIAKTHMgUCyCKZm55pUOdvFziJjQfXaWKhu2vhMs=
github.com/pocketbase/dbx v1.12.0 h1:/oLErM+A0b4xI0PWTGPqSDVjzix48PqI/bng2l0PzoA=
github.com/pocketbase/dbx v1.12.0/go.mod h1:xXRCIAKTHMgUCyCKZm55pUOdvFziJjQfXaWKhu2vhMs=
github.com/pocketbase/tygoja v0.0.0-20250812183945-97ffe055281f h1:ahrn66FNJYsFkO0EOTStYs+jdBKBop/anp9hoQSzZjI=
github.com/pocketbase/tygoja v0.0.0-20250812183945-97ffe055281f/go.mod h1:hKJWPGFqavk3cdTa47Qvs8g37lnfI57OYdVVbIqW5aE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
@@ -70,61 +72,63 @@ github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/f
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/cobra v1.10.1 h1:lJeBwCfmrnXthfAupyUTzJ/J4Nc1RsHC/mSRU2dll/s=
github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
golang.org/x/exp v0.0.0-20250911091902-df9299821621 h1:2id6c1/gto0kaHYyrixvknJ8tUK/Qs5IsmBtrc+FtgU=
golang.org/x/exp v0.0.0-20250911091902-df9299821621/go.mod h1:TwQYMMnGpvZyc+JpB/UAuTNIsVJifOlSkrZkhcvpVUk=
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
golang.org/x/exp v0.0.0-20260112195511-716be5621a96 h1:Z/6YuSHTLOHfNFdb8zVZomZr7cqNgTJvA8+Qz75D8gU=
golang.org/x/exp v0.0.0-20260112195511-716be5621a96/go.mod h1:nzimsREAkjBCIEFtHiYkrJyT+2uy9YZJB7H1k68CXZU=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.31.0 h1:mLChjE2MV6g1S7oqbXC0/UcKijjm5fnJLUYKIYrLESA=
golang.org/x/image v0.31.0/go.mod h1:R9ec5Lcp96v9FTF+ajwaH3uGxPH4fKfHHAVbUILxghA=
golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U=
golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI=
golang.org/x/image v0.35.0 h1:LKjiHdgMtO8z7Fh18nGY6KDcoEtVfsgLDPeLyguqb7I=
golang.org/x/image v0.35.0/go.mod h1:MwPLTVgvxSASsxdLzKrl8BRFuyqMyGhLwmC+TO1Sybk=
golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c=
golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
golang.org/x/oauth2 v0.31.0 h1:8Fq0yVZLh4j4YA47vHKFTa9Ew5XIrCP8LC6UeNZnLxo=
golang.org/x/oauth2 v0.31.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE=
golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w=
golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.26.2 h1:991HMkLjJzYBIfha6ECZdjrIYz2/1ayr+FL8GN+CNzM=
modernc.org/cc/v4 v4.26.2/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.28.0 h1:rjznn6WWehKq7dG4JtLRKxb52Ecv8OUGah8+Z/SfpNU=
modernc.org/ccgo/v4 v4.28.0/go.mod h1:JygV3+9AV6SmPhDasu4JgquwU81XAKLd3OKTUDNOiKE=
modernc.org/fileutil v1.3.8 h1:qtzNm7ED75pd1C7WgAGcK4edm4fvhtBsEiI/0NQ54YM=
modernc.org/fileutil v1.3.8/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.30.1 h1:4r4U1J6Fhj98NKfSjnPUN7Ze2c6MnAdL0hWw6+LrJpc=
modernc.org/ccgo/v4 v4.30.1/go.mod h1:bIOeI1JL54Utlxn+LwrFyjCx2n2RDiYEaJVSrgdrRfM=
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.1 h1:k8T3gkXWY9sEiytKhcgyiZ2L0DTyCQ/nvX+LoCljoRE=
modernc.org/gc/v3 v3.1.1/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.66.3 h1:cfCbjTUcdsKyyZZfEUKfoHcP3S0Wkvz3jgSzByEWVCQ=
modernc.org/libc v1.66.3/go.mod h1:XD9zO8kt59cANKvHPXpx7yS2ELPheAey0vjIuZOhOU8=
modernc.org/libc v1.67.6 h1:eVOQvpModVLKOdT+LvBPjdQqfrZq+pC39BygcT+E7OI=
modernc.org/libc v1.67.6/go.mod h1:JAhxUVlolfYDErnwiqaLvUqc8nfb2r6S6slAgZOnaiE=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
@@ -133,8 +137,8 @@ modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.39.0 h1:6bwu9Ooim0yVYA7IZn9demiQk/Ejp0BtTjBWFLymSeY=
modernc.org/sqlite v1.39.0/go.mod h1:cPTJYSlgg3Sfg046yBShXENNtPrWrDX8bsbAQBzgQ5E=
modernc.org/sqlite v1.45.0 h1:r51cSGzKpbptxnby+EIIz5fop4VuE4qFoVEjNvWoObs=
modernc.org/sqlite v1.45.0/go.mod h1:CzbrU2lSB1DKUusvwGz7rqEKIq+NUd8GWuBBZDs9/nA=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
+9 -2
View File
@@ -12,10 +12,14 @@ import (
)
// SendRecordAuthAlert sends a new device login alert to the specified auth record.
func SendRecordAuthAlert(app core.App, authRecord *core.Record) error {
func SendRecordAuthAlert(app core.App, authRecord *core.Record, info string) error {
mailClient := app.NewMailClient()
subject, body, err := resolveEmailTemplate(app, authRecord, authRecord.Collection().AuthAlert.EmailTemplate, nil)
info = html.EscapeString(info)
subject, body, err := resolveEmailTemplate(app, authRecord, authRecord.Collection().AuthAlert.EmailTemplate, map[string]any{
core.EmailPlaceholderAlertInfo: info,
})
if err != nil {
return err
}
@@ -35,6 +39,9 @@ func SendRecordAuthAlert(app core.App, authRecord *core.Record) error {
event.Mailer = mailClient
event.Message = message
event.Record = authRecord
event.Meta = map[string]any{
"info": info,
}
return app.OnMailerRecordAuthAlertSend().Trigger(event, func(e *core.MailerRecordEvent) error {
return e.Mailer.Send(e.Message)
+4 -1
View File
@@ -15,12 +15,14 @@ func TestSendRecordAuthAlert(t *testing.T) {
testApp, _ := tests.NewTestApp()
defer testApp.Cleanup()
info := "<p>test_info</p>"
user, _ := testApp.FindFirstRecordByData("users", "email", "test@example.com")
// to test that it is escaped
user.Set("name", "<p>"+user.GetString("name")+"</p>")
err := mails.SendRecordAuthAlert(testApp, user)
err := mails.SendRecordAuthAlert(testApp, user, info)
if err != nil {
t.Fatal(err)
}
@@ -34,6 +36,7 @@ func TestSendRecordAuthAlert(t *testing.T) {
"login to your " + testApp.Settings().Meta.AppName + " account from a new location",
"If this was you",
"If this wasn't you",
html.EscapeString(info),
}
for _, part := range expectedParts {
if !strings.Contains(testApp.TestMailer.LastMessage().HTML, part) {
@@ -0,0 +1,62 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
)
const oldAuthAlertTemplate = `<p>Hello,</p>
<p>We noticed a login to your {APP_NAME} account from a new location.</p>
<p>If this was you, you may disregard this email.</p>
<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>
<p>
Thanks,<br/>
{APP_NAME} team
</p>`
func init() {
core.SystemMigrations.Register(func(txApp core.App) error {
collections, err := txApp.FindAllCollections(core.CollectionTypeAuth)
if err != nil {
return err
}
newTemplate := core.NewAuthCollection("up").AuthAlert.EmailTemplate.Body
for _, c := range collections {
if c.AuthAlert.EmailTemplate.Body != oldAuthAlertTemplate {
continue
}
c.AuthAlert.EmailTemplate.Body = newTemplate
err = txApp.Save(c)
if err != nil {
return err
}
}
return nil
}, func(txApp core.App) error {
collections, err := txApp.FindAllCollections(core.CollectionTypeAuth)
if err != nil {
return err
}
newTemplate := core.NewAuthCollection("down").AuthAlert.EmailTemplate.Body
for _, c := range collections {
if c.AuthAlert.EmailTemplate.Body != newTemplate {
continue
}
c.AuthAlert.EmailTemplate.Body = oldAuthAlertTemplate
err = txApp.Save(c)
if err != nil {
return err
}
}
return nil
})
}
+2 -2
View File
@@ -10,8 +10,8 @@ import (
)
const (
expectedDriverVersion = "v1.39.0"
expectedLibcVersion = "v1.66.3"
expectedDriverVersion = "v1.45.0"
expectedLibcVersion = "v1.67.6"
// ModerncDepsCheckHookId is the id of the hook that performs the modernc.org/* deps checks.
// It could be used for removing/unbinding the hook if you don't want the checks.
+48 -6
View File
@@ -431,6 +431,32 @@ func baseBinds(vm *goja.Runtime) {
return instanceValue
})
// nullable helpers usually used as DynamicModel shape values
vm.Set("nullString", func() *string {
var v string
return &v
})
vm.Set("nullFloat", func() *float64 {
var v float64
return &v
})
vm.Set("nullInt", func() *int64 {
var v int64
return &v
})
vm.Set("nullBool", func() *bool {
var v bool
return &v
})
vm.Set("nullArray", func() *types.JSONArray[any] {
var v types.JSONArray[any]
return &v
})
vm.Set("nullObject", func() *types.JSONMap[any] {
var v types.JSONMap[any]
return &v
})
vm.Set("Record", func(call goja.ConstructorCall) *goja.Object {
var instance *core.Record
@@ -663,6 +689,7 @@ func mailsBinds(vm *goja.Runtime) {
obj.Set("sendRecordVerification", mails.SendRecordVerification)
obj.Set("sendRecordChangeEmail", mails.SendRecordChangeEmail)
obj.Set("sendRecordOTP", mails.SendRecordOTP)
obj.Set("sendRecordAuthAlert", mails.SendRecordAuthAlert)
}
func securityBinds(vm *goja.Runtime) {
@@ -712,6 +739,8 @@ func filesystemBinds(vm *goja.Runtime) {
obj := vm.NewObject()
vm.Set("$filesystem", obj)
obj.Set("s3", filesystem.NewS3)
obj.Set("local", filesystem.NewLocal)
obj.Set("fileFromPath", filesystem.NewFileFromPath)
obj.Set("fileFromBytes", filesystem.NewFileFromBytes)
obj.Set("fileFromMultipart", filesystem.NewFileFromMultipart)
@@ -1099,12 +1128,19 @@ var cachedDynamicModelStructs = store.New[string, reflect.Type](nil)
// on the specified "shape".
//
// The "shape" values are used as defaults and could be of type:
// - int (ex. 0)
// - float (ex. -0)
// - string (ex. "")
// - bool (ex. false)
// - slice (ex. [])
// - map (ex. map[string]any{})
//
// - int64 (ex.: 0)
// - *int64 (ex.: nullInt())
// - float64 (ex.: -0)
// - *float64 (ex.: nullFloat())
// - string (ex.: "")
// - *string (ex.: nullString())
// - bool (ex.: false)
// - *bool (ex.: nullBool())
// - slice/arr (ex.: [])
// - *slice/arr (ex.: nullArray())
// - map (ex.: {})
// - *map (ex.: nullObject())
//
// Example:
//
@@ -1140,6 +1176,9 @@ func newDynamicModel(shape map[string]any) any {
newV.Scan(raw)
v = newV
vt = reflect.TypeOf(newV)
case reflect.Pointer:
// for pointers always fallback to nil as their default value
v = nil
}
hash.WriteString(k)
@@ -1168,6 +1207,9 @@ func newDynamicModel(shape map[string]any) any {
// load default values into the new model
for i, item := range info {
if item.value == nil {
continue
}
elem.Field(i).Set(reflect.ValueOf(item.value))
}
+118 -34
View File
@@ -9,6 +9,7 @@ import (
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
@@ -46,7 +47,7 @@ func TestBaseBindsCount(t *testing.T) {
vm := goja.New()
baseBinds(vm)
testBindsCount(vm, "this", 35, t)
testBindsCount(vm, "this", 41, t)
}
func TestBaseBindsSleep(t *testing.T) {
@@ -795,7 +796,7 @@ func TestMailsBindsCount(t *testing.T) {
vm := goja.New()
mailsBinds(vm)
testBindsCount(vm, "$mails", 4, t)
testBindsCount(vm, "$mails", 5, t)
}
func TestMailsBinds(t *testing.T) {
@@ -833,6 +834,11 @@ func TestMailsBinds(t *testing.T) {
if (!$app.testMailer.lastMessage().html.includes("test_otp_pass")) {
throw new Error("Expected record OTP email, got:" + JSON.stringify($app.testMailer.lastMessage()))
}
$mails.sendRecordAuthAlert($app, record, "test_alert_info");
if (!$app.testMailer.lastMessage().html.includes("test_alert_info")) {
throw new Error("Expected record OTP email, got:" + JSON.stringify($app.testMailer.lastMessage()))
}
`)
if vmErr != nil {
t.Fatal(vmErr)
@@ -1003,14 +1009,47 @@ func TestFilesystemBinds(t *testing.T) {
}))
defer srv.Close()
tmpDir, err := os.MkdirTemp("", "jsvm")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
vm := goja.New()
vm.Set("mh", &multipart.FileHeader{Filename: "test"})
vm.Set("tmpDir", tmpDir)
vm.Set("testFile", filepath.Join(app.DataDir(), "data.db"))
vm.Set("baseURL", srv.URL)
baseBinds(vm)
filesystemBinds(vm)
testBindsCount(vm, "$filesystem", 4, t)
testBindsCount(vm, "$filesystem", 6, t)
// s3
{
v, err := vm.RunString(`$filesystem.s3("bucketName", "region", "endpoint", "accessKey", "secretKey", true)`)
if err != nil {
t.Fatal(err)
}
fsys, ok := v.Export().(*filesystem.System)
if !ok {
t.Fatalf("[s3] Expected System instance got %v", fsys)
}
}
// local
{
v, err := vm.RunString(`$filesystem.local(tmpDir)`)
if err != nil {
t.Fatal(err)
}
fsys, ok := v.Export().(*filesystem.System)
if !ok {
t.Fatalf("[s3] Expected System instance got %v", fsys)
}
}
// fileFromPath
{
@@ -1157,44 +1196,89 @@ func TestLoadingDynamicModel(t *testing.T) {
_, err := vm.RunString(`
let result = new DynamicModel({
text: "",
bool: false,
number: 0,
select_many: [],
json: [],
// custom map-like field
obj: {},
string: "",
nullString: nullString(),
nullStringEmpty: nullString(),
bool: false,
nullBool: nullBool(),
nullBoolEmpty: nullBool(),
int: 0,
nullInt: nullInt(),
nullIntEmpty: nullInt(),
float: -0,
nullFloat: nullFloat(),
nullFloatEmpty: nullFloat(),
array: [],
nullArray: nullArray(),
nullArrayEmpty: nullArray(),
object: {},
nullObject: nullObject(),
nullObjectEmpty: nullObject(),
})
const expectations = {
"string": "a",
"nullString": "b",
"nullStringEmpty": null,
"bool": false,
"nullBool": true,
"nullBoolEmpty": null,
"int": 1,
"nullInt": 2,
"nullIntEmpty": null,
"float": 1.1,
"nullFloat": 1.2,
"nullFloatEmpty": null,
"array": [1,2],
"nullArray": [3,4],
"nullArrayEmpty": null,
"object": {a:1},
"nullObject": {a:2},
"nullObjectEmpty": null,
};
// constuct dummy SELECT column value literals based on the expectations
const selectColumns = [];
for (const col in expectations) {
const val = expectations[col]
if (val === null) {
selectColumns.push("null as [[" + col + "]]")
} else if (typeof val === "string") {
selectColumns.push("'" + val + "' as [[" + col + "]]")
} else if (typeof val === "object") {
selectColumns.push("'" + JSON.stringify(val) + "' as [[" + col + "]]")
} else {
selectColumns.push(val + " as [[" + col + "]]")
}
}
$app.db()
.select("text", "bool", "number", "select_many", "json", "('{\"test\": 1}') as obj")
.from("demo1")
.where($dbx.hashExp({"id": "84nmscqy84lsi1t"}))
.limit(1)
.newQuery("SELECT " + selectColumns.join(", "))
.one(result)
if (result.text != "test") {
throw new Error('Expected text "test", got ' + result.text);
}
for (const col in expectations) {
let expVal = expectations[col];
let resVal = result[col];
if (result.bool != true) {
throw new Error('Expected bool true, got ' + result.bool);
}
if (expVal !== null && typeof expVal === "object") {
expVal = JSON.stringify(expVal)
resVal = JSON.stringify(resVal)
}
if (result.number != 123456) {
throw new Error('Expected number 123456, got ' + result.number);
}
if (result.select_many.length != 2 || result.select_many[0] != "optionB" || result.select_many[1] != "optionC") {
throw new Error('Expected select_many ["optionB", "optionC"], got ' + result.select_many);
}
if (result.json.length != 3 || result.json[0] != 1 || result.json[1] != 2 || result.json[2] != 3) {
throw new Error('Expected json [1, 2, 3], got ' + result.json);
}
if (result.obj.get("test") != 1) {
throw new Error('Expected obj.get("test") 1, got ' + JSON.stringify(result.obj));
if (expVal != resVal) {
throw new Error("Expected '" + col + "' value " + expVal + ", got " + resVal);
}
}
`)
if err != nil {
File diff suppressed because it is too large Load Diff
+118 -48
View File
@@ -259,27 +259,78 @@ declare function arrayOf<T>(model: T): Array<T>;
*
* Caveats:
* - In order to use 0 as double/float initialization number you have to negate it (` + "`-0`" + `).
* - You need to use lowerCamelCase when accessing the model fields (e.g. ` + "`model.roles`" + ` and not ` + "`model.Roles`" + `).
* - You need to use lowerCamelCase when accessing the model fields (e.g. ` + "`model.roles`" + ` and not ` + "`model.Roles`" + ` even if in the model shape and in the DB table the column is capitalized).
* - Objects are loaded into types.JSONMap, meaning that they need to be accessed with ` + "`get(key)`" + ` (e.g. ` + "`model.meta.get('something')`" + `).
* - For describing nullable types you can use the ` + "`null*()`" + ` helpers - ` + "`nullString()`" + `, ` + "`nullInt()`" + `, ` + "`nullFloat()`" + `, ` + "`nullBool()`" + `, ` + "`nullArray()`" + `, ` + "`nullObject()`" + `.
*
* Example:
*
* ` + "```" + `js
* const model = new DynamicModel({
* name: ""
* age: 0, // int64
* totalSpent: -0, // float64
* active: false,
* Roles: [], // maps to "Roles" in the DB/JSON but the prop would be accessible via "model.roles"
* meta: {}
* name: "" // or nullString() if nullable
* age: 0, // or nullInt() if nullable
* totalSpent: -0, // or nullFloat() if nullable
* active: false, // or nullBool() if nullable
* Roles: [], // or nullArray() if nullable; maps to "Roles" in the DB/JSON but the prop would be accessible via "model.roles"
* meta: {}, // or nullObject() if nullable
* })
* ` + "```" + `
*
* @group PocketBase
*/
declare class DynamicModel {
[key: string]: any;
constructor(shape?: { [key:string]: any })
}
/**
* nullString creates an empty Go string pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` string value.
*
* @group PocketBase
*/
declare function nullString(): string;
/**
* nullInt creates an empty Go int64 pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` int value.
*
* @group PocketBase
*/
declare function nullInt(): number;
/**
* nullFloat creates an empty Go float64 pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` float value.
*
* @group PocketBase
*/
declare function nullFloat(): number;
/**
* nullBool creates an empty Go bool pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` bool value.
*
* @group PocketBase
*/
declare function nullBool(): boolean;
/**
* nullArray creates an empty Go types.JSONArray pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` JSON array value.
*
* @group PocketBase
*/
declare function nullArray(): Array<any>;
/**
* nullObject creates an empty Go types.JSONMap pointer usually used for
* describing a **nullable** ` + "`DynamicModel`" + ` JSON object value.
*
* @group PocketBase
*/
declare function nullObject(): { get(key:string):any; set(key:string,value:any):void };
interface Context extends context.Context{} // merge
/**
* Context creates a new empty Go context.Context.
@@ -788,6 +839,7 @@ declare namespace $mails {
let sendRecordVerification: mails.sendRecordVerification
let sendRecordChangeEmail: mails.sendRecordChangeEmail
let sendRecordOTP: mails.sendRecordOTP
let sendRecordAuthAlert: mails.sendRecordAuthAlert
}
// -------------------------------------------------------------------
@@ -818,17 +870,17 @@ declare namespace $security {
/**
* {@inheritDoc security.newJWT}
*/
export function createJWT(payload: { [key:string]: any }, signingKey: string, secDuration: number): string
function createJWT(payload: { [key:string]: any }, signingKey: string, secDuration: number): string
/**
* {@inheritDoc security.parseUnverifiedJWT}
*/
export function parseUnverifiedJWT(token: string): _TygojaDict
function parseUnverifiedJWT(token: string): _TygojaDict
/**
* {@inheritDoc security.parseJWT}
*/
export function parseJWT(token: string, verificationKey: string): _TygojaDict
function parseJWT(token: string, verificationKey: string): _TygojaDict
}
// -------------------------------------------------------------------
@@ -846,6 +898,24 @@ declare namespace $filesystem {
let fileFromBytes: filesystem.newFileFromBytes
let fileFromMultipart: filesystem.newFileFromMultipart
/**
* Initializes a new S3-only filesystem instance
* (make sure to call ` + "`" + `close()` + "`" + ` after you are done working with it).
*
* Most users should prefer ` + "`" + `$app.newFilesystem()` + "`" + ` which will
* construct a local or S3 filesystem based on the configured application settings.
*/
let s3: filesystem.newS3
/**
* Initializes a new local-only filesystem instance
* (make sure to call ` + "`" + `close()` + "`" + ` after you are done working with it).
*
* Most users should prefer ` + "`" + `$app.newFilesystem()` + "`" + ` which will
* construct a local or S3 filesystem based on the configured application settings.
*/
let local: filesystem.newLocal
/**
* fileFromURL creates a new File from the provided url by
* downloading the resource and creating a BytesReader.
@@ -860,7 +930,7 @@ declare namespace $filesystem {
* const file2 = $filesystem.fileFromURL("https://...", 15)
* ` + "```" + `
*/
export function fileFromURL(url: string, secTimeout?: number): filesystem.File
function fileFromURL(url: string, secTimeout?: number): filesystem.File
}
// -------------------------------------------------------------------
@@ -874,21 +944,21 @@ declare namespace $filesystem {
* @group PocketBase
*/
declare namespace $filepath {
export let base: filepath.base
export let clean: filepath.clean
export let dir: filepath.dir
export let ext: filepath.ext
export let fromSlash: filepath.fromSlash
export let glob: filepath.glob
export let isAbs: filepath.isAbs
export let join: filepath.join
export let match: filepath.match
export let rel: filepath.rel
export let split: filepath.split
export let splitList: filepath.splitList
export let toSlash: filepath.toSlash
export let walk: filepath.walk
export let walkDir: filepath.walkDir
let base: filepath.base
let clean: filepath.clean
let dir: filepath.dir
let ext: filepath.ext
let fromSlash: filepath.fromSlash
let glob: filepath.glob
let isAbs: filepath.isAbs
let join: filepath.join
let match: filepath.match
let rel: filepath.rel
let split: filepath.split
let splitList: filepath.splitList
let toSlash: filepath.toSlash
let walk: filepath.walk
let walkDir: filepath.walkDir
}
// -------------------------------------------------------------------
@@ -905,7 +975,7 @@ declare namespace $os {
/**
* Legacy alias for $os.cmd().
*/
export let exec: exec.command
let exec: exec.command
/**
* Prepares an external OS command.
@@ -920,30 +990,30 @@ declare namespace $os {
* const output = toString(cmd.output());
* ` + "```" + `
*/
export let cmd: exec.command
let cmd: exec.command
/**
* Args hold the command-line arguments, starting with the program name.
*/
export let args: Array<string>
let args: Array<string>
export let exit: os.exit
export let getenv: os.getenv
export let dirFS: os.dirFS
export let readFile: os.readFile
export let writeFile: os.writeFile
export let stat: os.stat
export let readDir: os.readDir
export let tempDir: os.tempDir
export let truncate: os.truncate
export let getwd: os.getwd
export let mkdir: os.mkdir
export let mkdirAll: os.mkdirAll
export let rename: os.rename
export let remove: os.remove
export let removeAll: os.removeAll
export let openRoot: os.openRoot
export let openInRoot: os.openInRoot
let exit: os.exit
let getenv: os.getenv
let dirFS: os.dirFS
let readFile: os.readFile
let writeFile: os.writeFile
let stat: os.stat
let readDir: os.readDir
let tempDir: os.tempDir
let truncate: os.truncate
let getwd: os.getwd
let mkdir: os.mkdir
let mkdirAll: os.mkdirAll
let rename: os.rename
let remove: os.remove
let removeAll: os.removeAll
let openRoot: os.openRoot
let openInRoot: os.openInRoot
}
// -------------------------------------------------------------------
@@ -1072,7 +1142,7 @@ declare namespace $apis {
* If a file resource is missing and indexFallback is set, the request
* will be forwarded to the base index.html (useful for SPA).
*/
export function static(dir: string, indexFallback: boolean): (e: core.RequestEvent) => void
function static(dir: string, indexFallback: boolean): (e: core.RequestEvent) => void
let requireGuestOnly: apis.requireGuestOnly
let requireAuth: apis.requireAuth
@@ -1094,7 +1164,7 @@ declare namespace $apis {
* Set authMethod to empty string if you want to ignore the MFA checks and the login alerts
* (can be also adjusted additionally via the onRecordAuthRequest hook).
*/
export function recordAuthResponse(e: core.RequestEvent, authRecord: core.Record, authMethod: string, meta?: any): void
function recordAuthResponse(e: core.RequestEvent, authRecord: core.Record, authMethod: string, meta?: any): void
}
// -------------------------------------------------------------------
+1 -1
View File
@@ -377,7 +377,7 @@ func (p *plugin) watchHooks() error {
if hooksDirInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
watchDir, err = filepath.EvalSymlinks(p.config.HooksDir)
if err != nil {
return fmt.Errorf("failed to resolve hooksDir symink: %w", err)
return fmt.Errorf("failed to resolve hooksDir symlink: %w", err)
}
}
+4 -4
View File
@@ -29,7 +29,7 @@ migrate((app) => {
const collection = new Collection({
"authAlert": {
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location.</p>\n<p>If this was you, you may disregard this email.</p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location:</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>If this was you, you may disregard this email.</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Login from a new location"
},
"enabled": true
@@ -205,7 +205,7 @@ func init() {
jsonData := ` + "`" + `{
"authAlert": {
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location.</p>\n<p>If this was you, you may disregard this email.</p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location:</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>If this was you, you may disregard this email.</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Login from a new location"
},
"enabled": true
@@ -470,7 +470,7 @@ migrate((app) => {
const collection = new Collection({
"authAlert": {
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location.</p>\n<p>If this was you, you may disregard this email.</p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location:</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>If this was you, you may disregard this email.</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Login from a new location"
},
"enabled": true
@@ -649,7 +649,7 @@ func init() {
jsonData := ` + "`" + `{
"authAlert": {
"emailTemplate": {
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location.</p>\n<p>If this was you, you may disregard this email.</p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"body": "<p>Hello,</p>\n<p>We noticed a login to your {APP_NAME} account from a new location:</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>If this wasn't you, you should immediately change your {APP_NAME} account password to revoke access from all other locations.</strong></p>\n<p>If this was you, you may disregard this email.</p>\n<p>\n Thanks,<br/>\n {APP_NAME} team\n</p>",
"subject": "Login from a new location"
},
"enabled": true
+2
View File
@@ -205,6 +205,8 @@ func (pb *PocketBase) Execute() error {
<-done
// trigger cleanups
//
// @todo consider skipping and just call the finalizer in case OnTerminate was already invoked manually?
event := new(core.TerminateEvent)
event.App = pb
return pb.OnTerminate().Trigger(event, func(e *core.TerminateEvent) error {
+15 -2
View File
@@ -48,6 +48,14 @@ type ApiScenario struct {
// A zero or negative value means that there will be no timeout.
Timeout time.Duration
// DisableTestAppCleanup disables the builtin TestApp cleanup at
// the end of the ApiScenario execution.
//
// This option works only when explicit TestAppFactory is specified
// and means that the developer is responsible to do the necessary
// after test cleanup on their own (e.g. by manually calling testApp.Cleanup()).
DisableTestAppCleanup bool
// expectations
// ---------------------------------------------------------------
@@ -172,7 +180,11 @@ func (scenario *ApiScenario) test(t testing.TB) {
t.Fatalf("Failed to initialize the test app instance: %v", testAppErr)
}
}
defer testApp.Cleanup()
// https://github.com/pocketbase/pocketbase/discussions/7267
if scenario.TestAppFactory == nil || !scenario.DisableTestAppCleanup {
defer testApp.Cleanup()
}
baseRouter, err := apis.NewRouter(testApp)
if err != nil {
@@ -220,7 +232,8 @@ func (scenario *ApiScenario) test(t testing.TB) {
// set scenario headers
for k, v := range scenario.Headers {
req.Header.Set(k, v)
// trim whitespaces for consistency with the net/http request parsing
req.Header.Set(k, strings.TrimSpace(v))
}
// execute request
Binary file not shown.
+6 -5
View File
@@ -4,8 +4,10 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/golang-jwt/jwt/v5"
"github.com/pocketbase/pocketbase/tools/auth/internal/jwk"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
"golang.org/x/oauth2"
@@ -108,10 +110,10 @@ func (p *Apple) parseAndVerifyIdToken(idToken string) (jwt.MapClaims, error) {
return nil, errors.New("empty id_token")
}
// extract the token header params and claims
// extract the token claims
// ---
claims := jwt.MapClaims{}
t, _, err := jwt.NewParser().ParseUnverified(idToken, claims)
_, _, err := jwt.NewParser().ParseUnverified(idToken, claims)
if err != nil {
return nil, err
}
@@ -136,10 +138,9 @@ func (p *Apple) parseAndVerifyIdToken(idToken string) (jwt.MapClaims, error) {
// the token which is a result of direct TLS communication with the provider
// (see also https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation)
// ---
kid, _ := t.Header["kid"].(string)
err = validateIdTokenSignature(p.ctx, idToken, p.jwksURL, kid)
err = jwk.ValidateTokenSignature(p.ctx, idToken, p.jwksURL)
if err != nil {
return nil, err
return nil, fmt.Errorf("id_token validation failed: %w", err)
}
return claims, nil
+163
View File
@@ -0,0 +1,163 @@
// Package jwk implements some common utilities for interacting with JWKs
// (mostly used with OIDC providers).
package jwk
import (
"context"
"crypto/ed25519"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v5"
)
type JWK struct {
Kty string `json:"kty"`
Kid string `json:"kid"`
Use string `json:"use"`
Alg string `json:"alg"`
// RS256 (RSA)
E string `json:"e"`
N string `json:"n"`
// Ed25519 (OKP)
Crv string `json:"crv"`
X string `json:"x"`
}
// PublicKey reconstructs and returns the public key from the current JWK.
func (key *JWK) PublicKey() (any, error) {
switch key.Kty {
case "RSA":
// RFC 7518
// https://datatracker.ietf.org/doc/html/rfc7518#section-6.3
// https://datatracker.ietf.org/doc/html/rfc7517#appendix-A.1
exponent, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(key.E, "="))
if err != nil {
return nil, err
}
modulus, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(key.N, "="))
if err != nil {
return nil, err
}
return &rsa.PublicKey{
E: int(big.NewInt(0).SetBytes(exponent).Uint64()),
N: big.NewInt(0).SetBytes(modulus),
}, nil
case "OKP":
// RFC 8037
// https://datatracker.ietf.org/doc/html/rfc8037#section-2
// https://datatracker.ietf.org/doc/html/rfc8037#appendix-A
if key.Crv != "Ed25519" {
return nil, fmt.Errorf("unsupported OKP curve (must be Ed25519): %q", key.Crv)
}
x, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(key.X, "="))
if err != nil {
return nil, err
}
if l := len(x); l != ed25519.PublicKeySize {
return nil, fmt.Errorf("invalid Ed25519 key length: %d", l)
}
return ed25519.PublicKey(x), nil
default:
return nil, fmt.Errorf("unsupported kty (must be RSA or OKP): %q", key.Kty)
}
}
// Fetch retrieves the JSON Web Key Set located at jwksURL and returns
// the first key that matches the specified kid.
func Fetch(ctx context.Context, jwksURL string, kid string) (*JWK, error) {
req, err := http.NewRequestWithContext(ctx, "GET", jwksURL, nil)
if err != nil {
return nil, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
rawBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
// http.Client.Get doesn't treat non 2xx responses as error
if res.StatusCode >= 400 {
return nil, fmt.Errorf(
"failed to fetch JSON Web Key Set from %s (%d):\n%s",
jwksURL,
res.StatusCode,
string(rawBody),
)
}
jwks := struct {
Keys []*JWK
}{}
err = json.Unmarshal(rawBody, &jwks)
if err != nil {
return nil, err
}
for _, key := range jwks.Keys {
if key.Kid == kid {
return key, nil
}
}
return nil, fmt.Errorf("JWK with kid %q was not found", kid)
}
// ValidateTokenSignature validates the signature of a token with the
// public key retrievied from a remote JWKS.
func ValidateTokenSignature(ctx context.Context, token string, jwksURL string) error {
// extract the kid token header
// ---
t, _, err := jwt.NewParser().ParseUnverified(token, jwt.MapClaims{})
if err != nil {
return err
}
kid, _ := t.Header["kid"].(string)
if kid == "" {
return errors.New("missing kid header value")
}
// fetch the public key set
// ---
key, err := Fetch(ctx, jwksURL, kid)
if err != nil {
return err
}
// verify the signature
// ---
parser := jwt.NewParser(jwt.WithValidMethods([]string{key.Alg}))
parsedToken, err := parser.Parse(token, func(t *jwt.Token) (any, error) {
return key.PublicKey()
})
if err != nil {
return err
}
if !parsedToken.Valid {
return errors.New("the parsed token is invalid")
}
return nil
}
+314
View File
@@ -0,0 +1,314 @@
package jwk_test
import (
"context"
"crypto"
"crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"fmt"
"math/big"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/golang-jwt/jwt/v5"
"github.com/pocketbase/pocketbase/tools/auth/internal/jwk"
)
type publicKey interface {
Equal(x crypto.PublicKey) bool
}
func TestJWK_PublicKey(t *testing.T) {
t.Parallel()
rsaPrivate, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
t.Fatal(err)
}
scenarios := []struct {
name string
key *jwk.JWK
expectError bool
expectKey crypto.PublicKey
}{
{
"empty",
&jwk.JWK{},
true,
nil,
},
{
"invalid kty",
&jwk.JWK{
Kty: "invalid",
Alg: "RS256",
E: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(rsaPrivate.E)).Bytes()),
N: base64.RawURLEncoding.EncodeToString(rsaPrivate.N.Bytes()),
},
true,
nil,
},
{
"RSA",
&jwk.JWK{
Kty: "RSA",
Alg: "RS256",
E: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(rsaPrivate.E)).Bytes()),
N: base64.RawURLEncoding.EncodeToString(rsaPrivate.N.Bytes()),
},
false,
&rsaPrivate.PublicKey,
},
{
"OKP with unsupported curve",
&jwk.JWK{
Kty: "OKP",
Crv: "invalid",
X: base64.RawURLEncoding.EncodeToString([]byte(strings.Repeat("a", ed25519.PublicKeySize))),
},
true,
nil,
},
{
"OKP with invalid public key length",
&jwk.JWK{
Kty: "OKP",
Crv: "Ed25519",
X: base64.RawURLEncoding.EncodeToString([]byte(strings.Repeat("a", ed25519.PublicKeySize-1))),
},
true,
nil,
},
{
"valid OKP",
&jwk.JWK{
Kty: "OKP",
Crv: "Ed25519",
X: base64.RawURLEncoding.EncodeToString([]byte(strings.Repeat("a", ed25519.PublicKeySize))),
},
false,
ed25519.PublicKey([]byte(strings.Repeat("a", ed25519.PublicKeySize))),
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result, err := s.key.PublicKey()
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
if hasErr && result == nil {
return
}
k, ok := result.(publicKey)
if !ok {
t.Fatalf("The returned public key %T doesn't satisfy the expected common interface", k)
}
if !k.Equal(s.expectKey) {
t.Fatalf("The returned public key doesn't match with the expected one:\n%v\n%v", k, s.expectKey)
}
})
}
}
func TestFetch(t *testing.T) {
t.Parallel()
server := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.URL.Query().Has("error") {
res.WriteHeader(http.StatusBadRequest)
}
fmt.Fprintf(res, `{
"keys": [
{
"kid": "abc",
"kty": "OKP",
"crv": "Ed25519",
"x": "test_x"
},
{
"kid": "def",
"kty": "RSA",
"alg": "RS256",
"n": "test_n",
"e": "test_e"
}
]
}`)
}))
defer server.Close()
scenarios := []struct {
name string
kid string
expectError bool
contains []string
}{
{
"error response",
"def",
true,
nil,
},
{
"non-matching kid",
"missing",
true,
nil,
},
{
"matching kid",
"def",
false,
[]string{
`"kid":"def"`,
`"kty":"RSA"`,
`"alg":"RS256"`,
`"n":"test_n"`,
`"e":"test_e"`,
},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
url := server.URL
if s.expectError {
url += "?error"
}
key, err := jwk.Fetch(context.Background(), url, s.kid)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
raw, err := json.Marshal(key)
if err != nil {
t.Fatal(err)
}
rawStr := string(raw)
for _, substr := range s.contains {
if !strings.Contains(rawStr, substr) {
t.Fatalf("Missing expected substring\n%s\nin\n%s", substr, rawStr)
}
}
})
}
}
func TestValidateTokenSignature(t *testing.T) {
t.Parallel()
rsaPrivate, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
t.Fatal(err)
}
ed25519Public, ed25519Private, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
nonmatchingKidToken := jwt.New(&jwt.SigningMethodEd25519{})
nonmatchingKidToken.Header["kid"] = "missing"
nonmatchingKidTokenStr, err := nonmatchingKidToken.SignedString(ed25519Private)
if err != nil {
t.Fatal(err)
}
key1Token := jwt.New(&jwt.SigningMethodEd25519{})
key1Token.Header["kid"] = "key1"
key1TokenStr, err := key1Token.SignedString(ed25519Private)
if err != nil {
t.Fatal(err)
}
key2Token := jwt.New(jwt.SigningMethodRS256)
key2Token.Header["kid"] = "key2"
key2TokenStr, err := key2Token.SignedString(rsaPrivate)
if err != nil {
t.Fatal(err)
}
server := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
_ = json.NewEncoder(res).Encode(map[string]any{"keys": []*jwk.JWK{
{
Kid: "key1",
Kty: "OKP",
Alg: "EdDSA",
Crv: "Ed25519",
X: base64.RawURLEncoding.EncodeToString(ed25519Public),
},
{
Kid: "key2",
Kty: "RSA",
Alg: "RS256",
E: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(rsaPrivate.E)).Bytes()),
N: base64.RawURLEncoding.EncodeToString(rsaPrivate.N.Bytes()),
},
}})
}))
defer server.Close()
scenarios := []struct {
name string
token string
expectError bool
}{
{
"empty token",
"",
true,
},
{
"invlaid token",
"abc",
true,
},
{
"no matching kid",
nonmatchingKidTokenStr,
true,
},
{
"valid Ed25519 token",
key1TokenStr,
false,
},
{
"valid RSA token",
key2TokenStr,
false,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
err := jwk.ValidateTokenSignature(
context.Background(),
s.token,
server.URL,
)
hasErr := err != nil
if hasErr != s.expectError {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectError, hasErr, err)
}
})
}
}
+4 -110
View File
@@ -2,20 +2,15 @@ package auth
import (
"context"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/pocketbase/pocketbase/tools/auth/internal/jwk"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
@@ -140,7 +135,7 @@ func (p *OIDC) parseIdToken(token *oauth2.Token) (jwt.MapClaims, error) {
}
claims := jwt.MapClaims{}
t, _, err := jwt.NewParser().ParseUnverified(idToken, claims)
_, _, err := jwt.NewParser().ParseUnverified(idToken, claims)
if err != nil {
return nil, err
}
@@ -181,112 +176,11 @@ func (p *OIDC) parseIdToken(token *oauth2.Token) (jwt.MapClaims, error) {
// (see also https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation)
jwksURL := cast.ToString(p.Extra()["jwksURL"])
if jwksURL != "" {
kid, _ := t.Header["kid"].(string)
err = validateIdTokenSignature(p.ctx, idToken, jwksURL, kid)
err = jwk.ValidateTokenSignature(p.ctx, idToken, jwksURL)
if err != nil {
return nil, err
return nil, fmt.Errorf("id_token validation failed: %w", err)
}
}
return claims, nil
}
func validateIdTokenSignature(ctx context.Context, idToken string, jwksURL string, kid string) error {
// fetch the public key set
// ---
if kid == "" {
return errors.New("missing kid header value")
}
key, err := fetchJWK(ctx, jwksURL, kid)
if err != nil {
return err
}
// decode the key params per RFC 7518 (https://tools.ietf.org/html/rfc7518#section-6.3)
// and construct a valid publicKey from them
// ---
exponent, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(key.E, "="))
if err != nil {
return err
}
modulus, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(key.N, "="))
if err != nil {
return err
}
publicKey := &rsa.PublicKey{
// https://tools.ietf.org/html/rfc7517#appendix-A.1
E: int(big.NewInt(0).SetBytes(exponent).Uint64()),
N: big.NewInt(0).SetBytes(modulus),
}
// verify the signiture
// ---
parser := jwt.NewParser(jwt.WithValidMethods([]string{key.Alg}))
parsedToken, err := parser.Parse(idToken, func(t *jwt.Token) (any, error) {
return publicKey, nil
})
if err != nil {
return err
}
if !parsedToken.Valid {
return errors.New("the parsed id_token is invalid")
}
return nil
}
type jwk struct {
Kty string
Kid string
Use string
Alg string
N string
E string
}
func fetchJWK(ctx context.Context, jwksURL string, kid string) (*jwk, error) {
req, err := http.NewRequestWithContext(ctx, "GET", jwksURL, nil)
if err != nil {
return nil, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
rawBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
// http.Client.Get doesn't treat non 2xx responses as error
if res.StatusCode >= 400 {
return nil, fmt.Errorf(
"failed to verify the provided id_token (%d):\n%s",
res.StatusCode,
string(rawBody),
)
}
jwks := struct {
Keys []*jwk
}{}
if err := json.Unmarshal(rawBody, &jwks); err != nil {
return nil, err
}
for _, key := range jwks.Keys {
if key.Kid == kid {
return key, nil
}
}
return nil, fmt.Errorf("jwk with kid %q was not found", kid)
}
+17 -6
View File
@@ -3,6 +3,7 @@ package cron
import (
"encoding/json"
"slices"
"sync"
"testing"
"time"
)
@@ -253,53 +254,63 @@ func TestCronJobs(t *testing.T) {
func TestCronStartStop(t *testing.T) {
t.Parallel()
var mu sync.Mutex
test1 := 0
test2 := 0
c := New()
c.SetInterval(500 * time.Millisecond)
c.SetInterval(250 * time.Millisecond)
c.Add("test1", "* * * * *", func() {
mu.Lock()
defer mu.Unlock()
test1++
})
c.Add("test2", "* * * * *", func() {
mu.Lock()
defer mu.Unlock()
test2++
})
expectedCalls := 2
// call twice Start to check if the previous ticker will be reseted
c.Start()
c.Start()
time.Sleep(1 * time.Second)
time.Sleep(505 * time.Millisecond) // slightly larger to minimize flakiness
// call twice Stop to ensure that the second stop is no-op
c.Stop()
c.Stop()
expectedCalls := 2
mu.Lock()
if test1 != expectedCalls {
t.Fatalf("Expected %d test1, got %d", expectedCalls, test1)
}
if test2 != expectedCalls {
t.Fatalf("Expected %d test2, got %d", expectedCalls, test2)
}
mu.Unlock()
// resume for 2 seconds
// resume for 1 seconds
c.Start()
time.Sleep(2 * time.Second)
time.Sleep(1005 * time.Millisecond) // slightly larger to minimize flakiness
c.Stop()
expectedCalls += 4
mu.Lock()
if test1 != expectedCalls {
t.Fatalf("Expected %d test1, got %d", expectedCalls, test1)
}
if test2 != expectedCalls {
t.Fatalf("Expected %d test2, got %d", expectedCalls, test2)
}
mu.Unlock()
}
+18
View File
@@ -0,0 +1,18 @@
package dbutils
import "regexp"
// Regexp for columns and tables (the same as the one in dbx).
var selectRegex = regexp.MustCompile(`(?i:\s+as\s+|\s+)([\w\-_\.]+)$`)
// AliasOrIdentifier returns the alias from a column or table identifier.
// Returns the identifier unmodified if no alias was found.
func AliasOrIdentifier(columnOrTableIdentifier string) string {
matches := selectRegex.FindStringSubmatch(columnOrTableIdentifier)
if len(matches) > 0 && matches[1] != "" {
return matches[1]
}
return columnOrTableIdentifier
}
+38
View File
@@ -0,0 +1,38 @@
package dbutils_test
import (
"testing"
"github.com/pocketbase/pocketbase/tools/dbutils"
)
func TestAliasOrIdentifier(t *testing.T) {
scenarios := []struct {
value string
expected string
}{
{"", ""},
{"abc", "abc"},
{"abc ", "abc "}, // return unmodified
{"abc.def", "abc.def"},
{"abc.123 def", "def"},
{"abc.123 as def.456", "def.456"},
{"(abc) def", "def"},
{"(abc) as def", "def"},
{"abc def", "def"},
{"abc as def", "def"},
// technically invalid identifier but consistent with the dbx regex matching
{"a b c d", "d"},
{"a b c as d", "d"},
}
for _, s := range scenarios {
t.Run(s.value, func(t *testing.T) {
result := dbutils.AliasOrIdentifier(s.value)
if result != s.expected {
t.Fatalf("Expected\n%v\ngot\n%v", s.expected, result)
}
})
}
}
+14 -4
View File
@@ -193,22 +193,32 @@ var extInvalidCharsRegex = regexp.MustCompile(`[^\w\.\*\-\+\=\#]+`)
const randomAlphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
func normalizeName(fr FileReader, name string) string {
// cut the name even if it is not multibyte safe to avoid operating on too large strings
// ---
originalLength := len(name)
if originalLength > 300 {
name = name[originalLength-300:]
}
// extension
// ---
originalExt := extractExtension(name)
cleanExt := extInvalidCharsRegex.ReplaceAllString(originalExt, "")
if cleanExt == "" {
cleanExt := "." + strings.Trim(extInvalidCharsRegex.ReplaceAllString(originalExt, ""), ".")
if cleanExt == "." {
// try to detect the extension from the file content
cleanExt, _ = detectExtension(fr)
}
if extLength := len(cleanExt); extLength > 20 {
// keep only the last 20 characters (it is multibyte safe after the regex replace)
cleanExt = "." + cleanExt[extLength-20:]
cleanExt = "." + strings.Trim(cleanExt[extLength-20:], ".")
}
// name
//
// note: leading dot is trimmed to prevent various subtle issues with files
// sync programs as they sometimes have special handling for "invisible" files
// ---
cleanName := inflector.Snakecase(strings.TrimSuffix(name, originalExt))
cleanName := inflector.Snakecase(strings.Trim(strings.TrimSuffix(name, originalExt), "."))
if length := len(cleanName); length < 3 {
// the name is too short so we concatenate an additional random part
cleanName += security.RandomStringWithAlphabet(10, randomAlphabet)
+14 -9
View File
@@ -52,8 +52,8 @@ func TestNewFileFromPath(t *testing.T) {
}
// existing file
originalName := "image_! noext"
normalizedNamePattern := regexp.QuoteMeta("image_noext_") + `\w{10}` + regexp.QuoteMeta(".png")
originalName := "image_!@ special"
normalizedNamePattern := regexp.QuoteMeta("image_special_") + `\w{10}` + regexp.QuoteMeta(".png")
f, err := filesystem.NewFileFromPath(filepath.Join(testDir, originalName))
if err != nil {
t.Fatalf("Expected nil error, got %v", err)
@@ -83,8 +83,8 @@ func TestNewFileFromBytes(t *testing.T) {
t.Fatal("Expected error, got nil")
}
originalName := "image_! noext"
normalizedNamePattern := regexp.QuoteMeta("image_noext_") + `\w{10}` + regexp.QuoteMeta(".txt")
originalName := "image_!@ special"
normalizedNamePattern := regexp.QuoteMeta("image_special_") + `\w{10}` + regexp.QuoteMeta(".txt")
f, err := filesystem.NewFileFromBytes([]byte("text\n"), originalName)
if err != nil {
t.Fatal(err)
@@ -175,8 +175,8 @@ func TestNewFileFromURLTimeout(t *testing.T) {
// valid response
{
originalName := "image_! noext"
normalizedNamePattern := regexp.QuoteMeta("image_noext_") + `\w{10}` + regexp.QuoteMeta(".txt")
originalName := "image_!@ special"
normalizedNamePattern := regexp.QuoteMeta("image_special_") + `\w{10}` + regexp.QuoteMeta(".txt")
f, err := filesystem.NewFileFromURL(context.Background(), srv.URL+"/"+originalName)
if err != nil {
@@ -211,10 +211,14 @@ func TestFileNameNormalizations(t *testing.T) {
{".png", `^\w{10}_\w{10}\.png$`},
{".tar.gz", `^\w{10}_\w{10}\.tar\.gz$`},
{"a.tar.gz", `^a\w{10}_\w{10}\.tar\.gz$`},
{"....abc", `^\w{10}_\w{10}\.abc$`},
{"a.b.c.?.?.?.2", `^a_b_c_\w{10}\.2$`},
{"a.b.c.d.tar.gz", `^a_b_c_d_\w{10}\.tar\.gz$`},
{"abcd", `^abcd_\w{10}\.txt$`},
{"a b! c d . 456", `^a_b_c_d_\w{10}\.456$`}, // normalize spaces
{strings.Repeat("a", 101) + "." + strings.Repeat("b", 21), `^a{100}_\w{10}\.b{20}$`}, // name and extension length trim
{".abcd.123.", `^abcd_\w{10}\.123$`},
{"a b! c d . 456", `^a_b_c_d_\w{10}\.456$`}, // normalize spaces
{strings.Repeat("a", 101) + "." + strings.Repeat("b", 21), `^a{100}_\w{10}\.b{20}$`}, // name and extension length cut
{"abc" + strings.Repeat("d", 290) + "." + strings.Repeat("b", 9), `^d{100}_\w{10}\.b{9}$`}, // initial total length cut
}
for i, s := range scenarios {
@@ -223,7 +227,8 @@ func TestFileNameNormalizations(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if match, err := regexp.Match(s.pattern, []byte(f.Name)); !match {
match, err := regexp.Match(s.pattern, []byte(f.Name))
if !match {
t.Fatalf("Expected Name to match %v, got %q (%v)", s.pattern, f.Name, err)
}
})
+25 -12
View File
@@ -38,7 +38,7 @@ type System struct {
bucket *blob.Bucket
}
// NewS3 initializes an S3 filesystem instance.
// NewS3 initializes a new S3 filesystem instance.
//
// NB! Make sure to call `Close()` after you are done working with it.
func NewS3(
@@ -536,25 +536,38 @@ func (s *System) CreateThumb(originalKey string, thumbKey, thumbSize string) err
}
}
originalContentType := r.ContentType()
opts := &blob.WriterOptions{
ContentType: r.ContentType(),
ContentType: originalContentType,
}
// open a thumb storage writer (aka. prepare for upload)
w, writerErr := s.bucket.NewWriter(s.ctx, thumbKey, opts)
if writerErr != nil {
return writerErr
}
var format imaging.Format
// try to detect the thumb format based on the original file name
// (fallbacks to png on error)
format, err := imaging.FormatFromFilename(thumbKey)
if err != nil {
switch originalContentType {
case "image/jpeg":
format = imaging.JPEG
case "image/gif":
format = imaging.GIF
case "image/tiff":
format = imaging.TIFF
case "image/bmp":
format = imaging.BMP
default:
// fallback to PNG (this includes webp!)
opts.ContentType = "image/png"
format = imaging.PNG
}
// open a thumb storage writer (aka. prepare for upload)
w, err := s.bucket.NewWriter(s.ctx, thumbKey, opts)
if err != nil {
return err
}
// thumb encode (aka. upload)
if err := imaging.Encode(w, thumbImg, format); err != nil {
err = imaging.Encode(w, thumbImg, format)
if err != nil {
w.Close()
return err
}
+37 -8
View File
@@ -600,6 +600,7 @@ func TestFileSystemGetReuploadableFile(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer r.Close()
raw, err := io.ReadAll(r)
if err != nil {
@@ -677,12 +678,13 @@ func TestFileSystemCopy(t *testing.T) {
if err := fsys.Copy(src, dst); err != nil {
t.Fatalf("Failed to copy %q to %q: %v", src, dst, err)
}
f, err := fsys.GetReader(dst)
//nolint
defer f.Close()
if err != nil {
t.Fatalf("Missing copied file %q: %v", dst, err)
}
defer f.Close()
if f.Size() != 73 {
t.Fatalf("Expected file size %d, got %d", 73, f.Size())
}
@@ -709,7 +711,8 @@ func TestFileSystemList(t *testing.T) {
"image.jpg",
"image.svg",
"image.webp",
"image_! noext",
"image_!@ special",
"image_noext",
"style.css",
"main.js",
"main.mjs",
@@ -861,6 +864,8 @@ func TestFileSystemCreateThumb(t *testing.T) {
{"image.jpg", "thumb.jpg", "100x100", "image/jpeg"},
// webp (should produce png)
{"image.webp", "thumb.webp", "100x100", "image/png"},
// without extension (should extract the mimetype from its stored ContentType)
{"image_noext", "image_noext.jpeg", "100x100", "image/jpeg"},
}
for _, s := range scenarios {
@@ -884,13 +889,20 @@ func TestFileSystemCreateThumb(t *testing.T) {
}
defer f.Close()
attrsMimeType := f.ContentType()
mt, err := mimetype.DetectReader(f)
if err != nil {
t.Fatalf("Failed to detect thumb %s mimetype (%v)", s.thumb, err)
}
fileMimeType := mt.String()
if mtStr := mt.String(); mtStr != s.expectedMimeType {
t.Fatalf("Expected thumb %s MimeType %q, got %q", s.thumb, s.expectedMimeType, mtStr)
if fileMimeType != s.expectedMimeType {
t.Fatalf("Expected thumb file %s MimeType %q, got %q", s.thumb, s.expectedMimeType, fileMimeType)
}
if attrsMimeType != s.expectedMimeType {
t.Fatalf("Expected thumb attrs %s MimeType %q, got %q", s.thumb, s.expectedMimeType, attrsMimeType)
}
})
}
@@ -975,16 +987,33 @@ func createTestDir(t *testing.T) string {
}
}
// no extension and invalid characters
// invalid/special characters
{
file, err := os.OpenFile(filepath.Join(dir, "image_! noext"), os.O_WRONLY|os.O_CREATE, 0644)
file, err := os.OpenFile(filepath.Join(dir, "image_!@ special"), os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
t.Fatal(err)
}
_ = png.Encode(file, image.Rect(0, 0, 1, 1)) // tiny 1x1 png
imgRect := image.Rect(0, 0, 1, 1) // tiny 1x1 png
_ = png.Encode(file, imgRect)
file.Close()
}
// no extension
{
fullPath := filepath.Join(dir, "image_noext")
file, err := os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
t.Fatal(err)
}
imgRect := image.Rect(0, 0, 1, 1) // tiny 1x1 jpg
_ = jpeg.Encode(file, imgRect, nil)
file.Close()
err = os.WriteFile(fullPath+".attrs", []byte(`{"user.cache_control":"","user.content_disposition":"","user.content_encoding":"","user.content_language":"","user.content_type":"image/jpeg","user.metadata":null}`), 0644)
if err != nil {
t.Fatal(err)
}
}
// css
{
file, err := os.OpenFile(filepath.Join(dir, "style.css"), os.O_WRONLY|os.O_CREATE, 0644)
@@ -150,6 +150,12 @@ func (s3 *S3) SignAndSend(req *http.Request) (*http.Response, error) {
// https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html#create-signed-request-steps
func (s3 *S3) sign(req *http.Request) {
// explicitly set Accept-Encoding to avoid transparent decompression
// and Content-Length zeroing (https://github.com/pocketbase/pocketbase/issues/7523)
if req.Header.Get("Accept-Encoding") == "" {
req.Header.Set("Accept-Encoding", "identity")
}
// fallback to the Unsigned payload option
// (data integrity checks could be still applied via the content-md5 or x-amz-checksum-* headers)
if req.Header.Get("x-amz-content-sha256") == "" {
@@ -128,6 +128,7 @@ func TestS3SignAndSend(t *testing.T) {
return tests.ExpectHeaders(req.Header, map[string]string{
"Authorization": "AWS4-HMAC-SHA256 Credential=123/20250102/test_region/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=ea093662bc1deef08dfb4ac35453dfaad5ea89edf102e9dd3b7156c9a27e4c1f",
"Host": "test_bucket.example.com",
"Accept-Encoding": "identity",
"X-Amz-Content-Sha256": "UNSIGNED-PAYLOAD",
"X-Amz-Date": "20250102T150405Z",
})
@@ -155,6 +156,7 @@ func TestS3SignAndSend(t *testing.T) {
return tests.ExpectHeaders(req.Header, map[string]string{
"Authorization": "AWS4-HMAC-SHA256 Credential=456/20250102/test_region/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=17510fa1f724403dd0a563b61c9b31d1d718f877fcbd75455620d17a8afce5fb",
"Host": "test_bucket.example.com",
"Accept-Encoding": "identity",
"X-Amz-Content-Sha256": "UNSIGNED-PAYLOAD",
"X-Amz-Date": "20250102T150405Z",
})
@@ -182,6 +184,7 @@ func TestS3SignAndSend(t *testing.T) {
return tests.ExpectHeaders(req.Header, map[string]string{
"Authorization": "AWS4-HMAC-SHA256 Credential=456/20250102/test_region/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=9458a033554f52913801b3de16f54409b36ed25c6da3aed14e64439500e2c5e1",
"Host": "test_bucket.example.com",
"Accept-Encoding": "identity",
"X-Amz-Content-Sha256": "UNSIGNED-PAYLOAD",
"X-Amz-Date": "20250102T150405Z",
})
@@ -198,6 +201,7 @@ func TestS3SignAndSend(t *testing.T) {
req.Header.Set("x-amz-example", "123")
req.Header.Set("x-amz-meta-a", "456")
req.Header.Set("content-type", "image/png")
req.Header.Set("accept-encoding", "custom")
req.Header.Set("x-test", "789") // shouldn't be included in the signing headers
},
&s3.S3{
@@ -214,6 +218,7 @@ func TestS3SignAndSend(t *testing.T) {
return tests.ExpectHeaders(req.Header, map[string]string{
"authorization": "AWS4-HMAC-SHA256 Credential=123/20250102/test_region/s3/aws4_request, SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date;x-amz-example;x-amz-meta-a, Signature=86dccbcd012c33073dc99e9d0a9e0b717a4d8c11c37848cfa9a4a02716bc0db3",
"host": "test_bucket.example.com",
"accept-encoding": "custom",
"x-amz-date": "20250102T150405Z",
"x-amz-content-sha256": "test_sha256",
"x-amz-example": "123",
+1 -1
View File
@@ -46,7 +46,7 @@ import (
const defaultPageSize = 1000
// New creates a new instance of the S3 driver backed by the the internal S3 client.
// New creates a new instance of the S3 driver backed by the internal S3 client.
func New(s3Client *s3.S3) (blob.Driver, error) {
if s3Client.Bucket == "" {
return nil, errors.New("s3blob.New: missing bucket name")
+8 -8
View File
@@ -354,19 +354,19 @@ func TestEventString(t *testing.T) {
scenarios := []testResponseWriteScenario[string]{
{
name: "no explicit content-type",
status: 123,
status: 234,
headers: nil,
body: "test",
expectedStatus: 123,
expectedStatus: 234,
expectedHeaders: map[string]string{"content-type": "text/plain; charset=utf-8"},
expectedBody: "test",
},
{
name: "with explicit content-type",
status: 123,
status: 234,
headers: map[string]string{"content-type": "text/test"},
body: "test",
expectedStatus: 123,
expectedStatus: 234,
expectedHeaders: map[string]string{"content-type": "text/test"},
expectedBody: "test",
},
@@ -383,19 +383,19 @@ func TestEventHTML(t *testing.T) {
scenarios := []testResponseWriteScenario[string]{
{
name: "no explicit content-type",
status: 123,
status: 234,
headers: nil,
body: "test",
expectedStatus: 123,
expectedStatus: 234,
expectedHeaders: map[string]string{"content-type": "text/html; charset=utf-8"},
expectedBody: "test",
},
{
name: "with explicit content-type",
status: 123,
status: 234,
headers: map[string]string{"content-type": "text/test"},
body: "test",
expectedStatus: 123,
expectedStatus: 234,
expectedHeaders: map[string]string{"content-type": "text/test"},
expectedBody: "test",
},
+23 -15
View File
@@ -218,7 +218,7 @@ func buildResolversExpr(
expr = dbx.Enclose(dbx.And(expr, mm))
} else if left.MultiMatchSubQuery != nil {
mm := &manyVsOneExpr{
noCoalesce: left.NoCoalesce,
nullFallback: left.NullFallback,
subQuery: left.MultiMatchSubQuery,
op: op,
otherOperand: right,
@@ -227,7 +227,7 @@ func buildResolversExpr(
expr = dbx.Enclose(dbx.And(expr, mm))
} else if right.MultiMatchSubQuery != nil {
mm := &manyVsOneExpr{
noCoalesce: right.NoCoalesce,
nullFallback: right.NullFallback,
subQuery: right.MultiMatchSubQuery,
op: op,
otherOperand: left,
@@ -326,9 +326,6 @@ func resolveToken(token fexpr.Token, fieldResolver FieldResolver) (*ResolverResu
// `COALESCE(a, "") = ""` since the direct match can be accomplished
// with a seek while the COALESCE will induce a table scan.
func resolveEqualExpr(equal bool, left, right *ResolverResult) dbx.Expression {
isLeftEmpty := isEmptyIdentifier(left) || (len(left.Params) == 1 && hasEmptyParamValue(left))
isRightEmpty := isEmptyIdentifier(right) || (len(right.Params) == 1 && hasEmptyParamValue(right))
equalOp := "="
nullEqualOp := "IS"
concatOp := "OR"
@@ -343,16 +340,23 @@ func resolveEqualExpr(equal bool, left, right *ResolverResult) dbx.Expression {
nullExpr = "IS NOT NULL"
}
// no coalesce (eg. compare to a json field)
// no coalesce fallback (eg. compare to a json field)
// a IS b
// a IS NOT b
if left.NoCoalesce || right.NoCoalesce {
if left.NullFallback == NullFallbackDisabled ||
right.NullFallback == NullFallbackDisabled {
return dbx.NewExp(
fmt.Sprintf("%s %s %s", left.Identifier, nullEqualOp, right.Identifier),
mergeParams(left.Params, right.Params),
)
}
isLeftEmpty := isEmptyIdentifier(left) ||
(left.NullFallback == NullFallbackAuto && len(left.Params) == 1 && hasEmptyParamValue(left))
isRightEmpty := isEmptyIdentifier(right) ||
(right.NullFallback == NullFallbackAuto && len(right.Params) == 1 && hasEmptyParamValue(right))
// both operands are empty
if isLeftEmpty && isRightEmpty {
return dbx.NewExp(fmt.Sprintf("'' %s ''", equalOp), mergeParams(left.Params, right.Params))
@@ -421,6 +425,10 @@ func hasEmptyParamValue(result *ResolverResult) bool {
}
func isKnownNonEmptyIdentifier(result *ResolverResult) bool {
if result.NullFallback == NullFallbackEnforced {
return false
}
switch strings.ToLower(result.Identifier) {
case "1", "0", "false", `true`:
return true
@@ -631,13 +639,13 @@ func (e *manyVsManyExpr) Build(db *dbx.DB, params dbx.Params) string {
whereExpr, buildErr := buildResolversExpr(
&ResolverResult{
NoCoalesce: e.left.NoCoalesce,
Identifier: "[[" + lAlias + ".multiMatchValue]]",
NullFallback: e.left.NullFallback,
Identifier: "[[" + lAlias + ".multiMatchValue]]",
},
e.op,
&ResolverResult{
NoCoalesce: e.right.NoCoalesce,
Identifier: "[[" + rAlias + ".multiMatchValue]]",
NullFallback: e.right.NullFallback,
Identifier: "[[" + rAlias + ".multiMatchValue]]",
// note: the AfterBuild needs to be handled only once and it
// doesn't matter whether it is applied on the left or right subquery operand
AfterBuild: dbx.Not, // inverse for the not-exist expression
@@ -672,7 +680,7 @@ type manyVsOneExpr struct {
subQuery dbx.Expression
op fexpr.SignOp
inverse bool
noCoalesce bool
nullFallback NullFallbackPreference
}
// Build converts the expression into a SQL fragment.
@@ -686,9 +694,9 @@ func (e *manyVsOneExpr) Build(db *dbx.DB, params dbx.Params) string {
alias := "__sm" + security.PseudorandomString(8)
r1 := &ResolverResult{
NoCoalesce: e.noCoalesce,
Identifier: "[[" + alias + ".multiMatchValue]]",
AfterBuild: dbx.Not, // inverse for the not-exist expression
NullFallback: e.nullFallback,
Identifier: "[[" + alias + ".multiMatchValue]]",
AfterBuild: dbx.Not, // inverse for the not-exist expression
}
r2 := &ResolverResult{
+70
View File
@@ -0,0 +1,70 @@
package search
import (
"fmt"
"strings"
"github.com/pocketbase/dbx"
)
var _ dbx.Expression = (*MultiMatchSubquery)(nil)
// Join defines common fields required for a single SQL JOIN clause.
type Join struct {
TableName string
TableAlias string
On dbx.Expression
}
// MultiMatchSubquery defines a multi-match record subquery expression.
type MultiMatchSubquery struct {
TargetTableAlias string
FromTableName string
FromTableAlias string
ValueIdentifier string
Joins []*Join
Params dbx.Params
}
// Build converts the expression into a SQL fragment.
//
// Implements [dbx.Expression] interface.
func (m *MultiMatchSubquery) Build(db *dbx.DB, params dbx.Params) string {
if m.TargetTableAlias == "" || m.FromTableName == "" || m.FromTableAlias == "" {
return "0=1"
}
if params == nil {
params = m.Params
} else {
// merge by updating the parent params
for k, v := range m.Params {
params[k] = v
}
}
var mergedJoins strings.Builder
for i, j := range m.Joins {
if i > 0 {
mergedJoins.WriteString(" ")
}
mergedJoins.WriteString("LEFT JOIN ")
mergedJoins.WriteString(db.QuoteTableName(j.TableName))
mergedJoins.WriteString(" ")
mergedJoins.WriteString(db.QuoteTableName(j.TableAlias))
if j.On != nil {
mergedJoins.WriteString(" ON ")
mergedJoins.WriteString(j.On.Build(db, params))
}
}
return fmt.Sprintf(
`SELECT %s as [[multiMatchValue]] FROM %s %s %s WHERE %s = %s`,
db.QuoteColumnName(m.ValueIdentifier),
db.QuoteTableName(m.FromTableName),
db.QuoteTableName(m.FromTableAlias),
mergedJoins.String(),
db.QuoteColumnName(m.FromTableAlias+".id"),
db.QuoteColumnName(m.TargetTableAlias+".id"),
)
}
+52
View File
@@ -0,0 +1,52 @@
package search_test
import (
"bytes"
"database/sql"
"encoding/json"
"testing"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/search"
)
func TestMultiMatchSubqueryBuild(t *testing.T) {
// create a dummy db
sqlDB, err := sql.Open("sqlite", "file::memory:?cache=shared")
if err != nil {
t.Fatal(err)
}
db := dbx.NewFromDB(sqlDB, "sqlite")
mm := search.MultiMatchSubquery{
TargetTableAlias: "test_TargetTableAlias",
FromTableName: "test_FromTableName",
FromTableAlias: "test_FromTableAlias",
ValueIdentifier: "({:mm},{:external})",
Joins: []*search.Join{
{TableName: "join_table1", TableAlias: "join_alias1"},
{TableName: "join_table2", TableAlias: "join_alias2", On: dbx.NewExp("123={:join}", dbx.Params{"join": "test_join"})},
},
Params: dbx.Params{"mm": "test_mm"},
}
params := dbx.Params{"external": "test_external"}
result := mm.Build(db, params)
expectedResult := "SELECT ({:mm},{:external}) as [[multiMatchValue]] FROM `test_FromTableName` `test_FromTableAlias` LEFT JOIN `join_table1` `join_alias1` LEFT JOIN `join_table2` `join_alias2` ON 123={:join} WHERE `test_FromTableAlias`.`id` = `test_TargetTableAlias`.`id`"
if expectedResult != result {
t.Fatalf("Expected build result\n%v\ngot\n%v", expectedResult, result)
}
// the params from all expressions should be merged in the root
rawParams, err := json.Marshal(params)
if err != nil {
t.Fatal(err)
}
expectedParams := []byte(`{"external":"test_external","join":"test_join","mm":"test_mm"}`)
if !bytes.Equal(rawParams, expectedParams) {
t.Fatalf("Expected final params\n%s\ngot\n%s", expectedParams, rawParams)
}
}
+10 -2
View File
@@ -8,6 +8,7 @@ import (
"strings"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/dbutils"
"github.com/pocketbase/pocketbase/tools/inflector"
"golang.org/x/sync/errgroup"
)
@@ -298,13 +299,21 @@ func (s *Provider) Exec(items any) (*Result, error) {
countExec := func() error {
queryInfo := countQuery.Info()
countCol := s.countCol
if len(queryInfo.From) > 0 {
countCol = queryInfo.From[0] + "." + countCol
firstFrom := dbutils.AliasOrIdentifier(queryInfo.From[0])
countCol = firstFrom + "." + countCol
}
// @todo while currently there is no such use case, evaluate if
// wrapping as a subquery would be more suitable for the cases
// when there is "Group By" different from the default deduplication one
// added by RecordFieldResolver.UpdateQuery
// note: countQuery is shallow cloned and slice/map in-place modifications should be avoided
err := countQuery.Distinct(false).
Select("COUNT(DISTINCT [[" + countCol + "]])").
GroupBy( /* reset */ ).
OrderBy( /* reset */ ).
Row(&totalCount)
if err != nil {
@@ -327,7 +336,6 @@ func (s *Provider) Exec(items any) (*Result, error) {
if !s.skipTotal {
// execute the 2 queries concurrently
errg := new(errgroup.Group)
errg.SetLimit(2)
errg.Go(countExec)
errg.Go(modelsExec)
if err := errg.Wait(); err != nil {
+4
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"strconv"
"strings"
"sync"
"testing"
"time"
@@ -741,6 +742,7 @@ type testTableStruct struct {
type testDB struct {
*dbx.DB
mu sync.Mutex
CalledQueries []string
}
@@ -765,6 +767,8 @@ func createTestDB() (*testDB, error) {
db.Insert("test", dbx.Params{"id": 1, "test1": 1, "test2": "test2.1"}).Execute()
db.Insert("test", dbx.Params{"id": 2, "test1": 2, "test2": "test2.2"}).Execute()
db.QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) {
db.mu.Lock()
defer db.mu.Unlock()
db.CalledQueries = append(db.CalledQueries, sql)
}
+16 -5
View File
@@ -10,15 +10,26 @@ import (
"github.com/pocketbase/pocketbase/tools/list"
)
type NullFallbackPreference int
const (
NullFallbackAuto NullFallbackPreference = 0
NullFallbackDisabled NullFallbackPreference = 1
NullFallbackEnforced NullFallbackPreference = 2
)
// ResolverResult defines a single FieldResolver.Resolve() successfully parsed result.
type ResolverResult struct {
// Identifier is the plain SQL identifier/column that will be used
// in the final db expression as left or right operand.
Identifier string
// NoCoalesce instructs to not use COALESCE or NULL fallbacks
// when building the identifier expression.
NoCoalesce bool
// NullFallback specify the preference for how NULL or empty values
// should be resolved (default to "auto").
//
// Set to NullFallbackDisabled to prevent any COALESCE or NULL fallbacks.
// Set to NullFallbackEnforced to prefer COALESCE or NULL fallbacks when needed.
NullFallback NullFallbackPreference
// Params is a map with db placeholder->value pairs that will be added
// to the query when building both resolved operands/sides in a single expression.
@@ -26,7 +37,7 @@ type ResolverResult struct {
// MultiMatchSubQuery is an optional sub query expression that will be added
// in addition to the combined ResolverResult expression during build.
MultiMatchSubQuery dbx.Expression
MultiMatchSubQuery *MultiMatchSubquery
// AfterBuild is an optional function that will be called after building
// and combining the result of both resolved operands/sides in a single expression.
@@ -103,7 +114,7 @@ func (r *SimpleFieldResolver) Resolve(field string) (*ResolverResult, error) {
}
return &ResolverResult{
NoCoalesce: true,
NullFallback: NullFallbackDisabled,
Identifier: fmt.Sprintf(
"JSON_EXTRACT([[%s]], '%s')",
inflector.Columnify(parts[0]),
+140 -1
View File
@@ -1,9 +1,13 @@
package search
import (
"errors"
"fmt"
"slices"
"strings"
"github.com/ganigeorgiev/fexpr"
"github.com/pocketbase/dbx"
)
var TokenFunctions = map[string]func(
@@ -44,7 +48,7 @@ var TokenFunctions = map[string]func(
latB := resolvedArgs[3].Identifier
return &ResolverResult{
NoCoalesce: true,
NullFallback: NullFallbackDisabled,
Identifier: `(6371 * acos(` +
`cos(radians(` + latA + `)) * cos(radians(` + latB + `)) * ` +
`cos(radians(` + lonB + `) - radians(` + lonA + `)) + ` +
@@ -53,4 +57,139 @@ var TokenFunctions = map[string]func(
Params: mergeParams(resolvedArgs[0].Params, resolvedArgs[1].Params, resolvedArgs[2].Params, resolvedArgs[3].Params),
}, nil
},
// strftime(format, [timeValue, modifier1, modifier2, ...]) returns
// a date string formatted according to the specified format argument.
//
// It is similar to the builtin SQLite strftime function (https://sqlite.org/lang_datefunc.html)
// with the main difference that NULL results will be normalized for
// consistency with the non-nullable PocketBase "text" and "date" fields.
//
// The function accepts 1, 2 or 3+ arguments.
//
// (1) The first (format) argument must be always a formatting string
// with valid substitutions as listed in https://sqlite.org/lang_datefunc.html.
//
// (2) The second (time-value) argument is optional and must be either a date string, number or collection field identifier
// that matches one of the formats listed in https://sqlite.org/lang_datefunc.html#time_values.
//
// (3+) The remaining (modifiers) optional arguments are expected to be
// string literals matching the listed modifiers in https://sqlite.org/lang_datefunc.html#modifiers.
//
// A multi-match constraint will be also applied in case the time-value
// is an identifier as a result of a multi-value relation field.
"strftime": func(argTokenResolverFunc func(fexpr.Token) (*ResolverResult, error), args ...fexpr.Token) (*ResolverResult, error) {
totalArgs := len(args)
if totalArgs < 1 {
return nil, fmt.Errorf("[strftime] expected at least 1 arguments, got %d", len(args))
}
// limit the number of arguments to prevent abuse
if totalArgs > 10 {
return nil, fmt.Errorf("[strftime] too many arguments (max allowed 10, got %d)", totalArgs)
}
// format arg
// -----------------------------------------------------------
if args[0].Type != fexpr.TokenText {
return nil, errors.New("[strftime] expects the first argument to be a format string")
}
formatArgResult, err := argTokenResolverFunc(args[0])
if err != nil {
return nil, fmt.Errorf("[strftime] failed to resolve format argument: %w", err)
}
// no further arguments
if totalArgs == 1 {
formatArgResult.NullFallback = NullFallbackEnforced
formatArgResult.Identifier = "strftime(" + formatArgResult.Identifier + ")"
return formatArgResult, nil
}
// time-value arg
// -----------------------------------------------------------
allowedTimeValueTokens := []fexpr.TokenType{fexpr.TokenText, fexpr.TokenIdentifier, fexpr.TokenNumber}
if !slices.Contains(allowedTimeValueTokens, args[1].Type) {
return nil, errors.New("[strftime] expects the second argument to be of a valid time-value type")
}
timeValueArgResult, err := argTokenResolverFunc(args[1])
if err != nil {
return nil, fmt.Errorf("[strftime] failed to resolve time-value argument: %w", err)
}
// modifiers args
// -----------------------------------------------------------
resolvedModifierArgs := make([]*ResolverResult, totalArgs-2)
for i, arg := range args[2:] {
if arg.Type != fexpr.TokenText {
return nil, fmt.Errorf("[strftime] invalid modifier argument %d - can be only string", i)
}
resolved, err := argTokenResolverFunc(arg)
if err != nil {
return nil, fmt.Errorf("[strftime] failed to resolve modifier argument %d: %w", i, err)
}
resolvedModifierArgs[i] = resolved
}
// generating new ResolverResult
// -----------------------------------------------------------
result := &ResolverResult{
NullFallback: NullFallbackEnforced,
Params: dbx.Params{},
}
identifiers := make([]string, 0, totalArgs)
identifiers = append(identifiers, formatArgResult.Identifier)
if err = concatUniqueParams(result.Params, formatArgResult.Params); err != nil {
return nil, err
}
identifiers = append(identifiers, timeValueArgResult.Identifier)
if err = concatUniqueParams(result.Params, timeValueArgResult.Params); err != nil {
return nil, err
}
for _, m := range resolvedModifierArgs {
identifiers = append(identifiers, m.Identifier)
err = concatUniqueParams(result.Params, m.Params)
if err != nil {
return nil, err
}
}
result.Identifier = "strftime(" + strings.Join(identifiers, ",") + ")"
if timeValueArgResult.MultiMatchSubQuery != nil {
// replace the regular time-value identifier with the multi-match one
identifiers[1] = timeValueArgResult.MultiMatchSubQuery.ValueIdentifier
result.MultiMatchSubQuery = timeValueArgResult.MultiMatchSubQuery
result.MultiMatchSubQuery.ValueIdentifier = "strftime(" + strings.Join(identifiers, ",") + ")"
err = concatUniqueParams(result.MultiMatchSubQuery.Params, result.Params)
if err != nil {
return nil, err
}
}
return result, nil
},
}
func concatUniqueParams(destParams, newParams dbx.Params) error {
for k, v := range newParams {
found, ok := destParams[k]
if ok && v != found {
return fmt.Errorf("conflicting param key %s", k)
}
destParams[k] = v
}
return nil
}
+355 -6
View File
@@ -116,8 +116,8 @@ func TestTokenFunctionsGeoDistance(t *testing.T) {
},
baseTokenResolver,
&ResolverResult{
NoCoalesce: true,
Identifier: `(6371 * acos(cos(radians({:latA})) * cos(radians({:latB})) * cos(radians({:lonB}) - radians({:lonA})) + sin(radians({:latA})) * sin(radians({:latB}))))`,
NullFallback: NullFallbackDisabled,
Identifier: `(6371 * acos(cos(radians({:latA})) * cos(radians({:latB})) * cos(radians({:lonB}) - radians({:lonA})) + sin(radians({:latA})) * sin(radians({:latB}))))`,
Params: map[string]any{
"lonA": 1,
"latA": 2,
@@ -137,8 +137,8 @@ func TestTokenFunctionsGeoDistance(t *testing.T) {
},
baseTokenResolver,
&ResolverResult{
NoCoalesce: true,
Identifier: `(6371 * acos(cos(radians({:latA})) * cos(radians({:latB})) * cos(radians({:lonB}) - radians({:lonA})) + sin(radians({:latA})) * sin(radians({:latB}))))`,
NullFallback: NullFallbackDisabled,
Identifier: `(6371 * acos(cos(radians({:latA})) * cos(radians({:latB})) * cos(radians({:lonB}) - radians({:lonA})) + sin(radians({:latA})) * sin(radians({:latB}))))`,
Params: map[string]any{
"lonA": "null",
"latA": 2,
@@ -209,6 +209,351 @@ func TestTokenFunctionsGeoDistanceExec(t *testing.T) {
}
}
func TestTokenFunctionsStrftime(t *testing.T) {
t.Parallel()
testDB, err := createTestDB()
if err != nil {
t.Fatal(err)
}
defer testDB.Close()
fn, ok := TokenFunctions["strftime"]
if !ok {
t.Error("Expected strftime token function to be registered.")
}
baseTokenResolver := func(t fexpr.Token) (*ResolverResult, error) {
placeholder := "t" + security.PseudorandomString(5)
return &ResolverResult{Identifier: "{:" + placeholder + "}", Params: map[string]any{placeholder: t.Literal}}, nil
}
scenarios := []struct {
name string
args []fexpr.Token
resolver func(t fexpr.Token) (*ResolverResult, error)
result *ResolverResult
expectErr bool
}{
{
"no args",
nil,
baseTokenResolver,
nil,
true,
},
// format arg
// -----------------------------------------------------------
{
"(format arg) invalid token type function",
[]fexpr.Token{
{Literal: "abc", Type: fexpr.TokenFunction},
},
baseTokenResolver,
nil,
true,
},
{
"(format arg) invalid token type ws",
[]fexpr.Token{
{Literal: "abc", Type: fexpr.TokenWS},
},
baseTokenResolver,
nil,
true,
},
{
"(format arg) invalid token type number",
[]fexpr.Token{
{Literal: "abc", Type: fexpr.TokenNumber},
},
baseTokenResolver,
nil,
true,
},
{
"(format arg) invalid token type identifier",
[]fexpr.Token{
{Literal: "abc", Type: fexpr.TokenIdentifier},
},
baseTokenResolver,
nil,
true,
},
{
"(format arg) valid token type text",
[]fexpr.Token{
{Literal: "abc", Type: fexpr.TokenText},
},
baseTokenResolver,
&ResolverResult{
NullFallback: NullFallbackEnforced,
Identifier: `strftime({:format})`,
Params: map[string]any{"format": "abc"},
},
false,
},
// format + time-value args
// -----------------------------------------------------------
{
"(format arg) invalid token type function",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText},
{Literal: "2", Type: fexpr.TokenFunction},
},
baseTokenResolver,
nil,
true,
},
{
"(format arg) invalid token type ws",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText},
{Literal: "2", Type: fexpr.TokenWS},
},
baseTokenResolver,
nil,
true,
},
{
"(format arg) valid token type number",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText},
{Literal: "2", Type: fexpr.TokenNumber},
},
baseTokenResolver,
&ResolverResult{
NullFallback: NullFallbackEnforced,
Identifier: `strftime({:format},{:time})`,
Params: map[string]any{"format": "1", "time": "2"},
},
false,
},
{
"(format arg) valid token type identifier",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText},
{Literal: "2", Type: fexpr.TokenIdentifier},
},
baseTokenResolver,
&ResolverResult{
NullFallback: NullFallbackEnforced,
Identifier: `strftime({:format},{:time})`,
Params: map[string]any{"format": "1", "time": "2"},
},
false,
},
{
"(format arg) valid token type text",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText},
{Literal: "2", Type: fexpr.TokenText},
},
baseTokenResolver,
&ResolverResult{
NullFallback: NullFallbackEnforced,
Identifier: `strftime({:format},{:time})`,
Params: map[string]any{"format": "1", "time": "2"},
},
false,
},
// format + time-value + modifier args
// -----------------------------------------------------------
{
"(modifiers arg) invalid token type function",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText}, // valid format
{Literal: "2", Type: fexpr.TokenText}, // valid time-value
{Literal: "3", Type: fexpr.TokenText}, // valid modifier
{Literal: "4", Type: fexpr.TokenFunction},
},
baseTokenResolver,
nil,
true,
},
{
"(modifiers arg) invalid token type ws",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText}, // valid format
{Literal: "2", Type: fexpr.TokenText}, // valid time-value
{Literal: "3", Type: fexpr.TokenText}, // valid modifier
{Literal: "4", Type: fexpr.TokenWS},
},
baseTokenResolver,
nil,
true,
},
{
"(modifiers arg) valid token type number",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText}, // valid format
{Literal: "2", Type: fexpr.TokenText}, // valid time-value
{Literal: "3", Type: fexpr.TokenText}, // valid modifier
{Literal: "4", Type: fexpr.TokenNumber},
},
baseTokenResolver,
nil,
true,
},
{
"(modifiers arg) valid token type identifier",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText}, // valid format
{Literal: "2", Type: fexpr.TokenText}, // valid time-value
{Literal: "3", Type: fexpr.TokenText}, // valid modifier
{Literal: "4", Type: fexpr.TokenIdentifier},
},
baseTokenResolver,
nil,
true,
},
{
"(modifiers arg) valid token type text",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText}, // valid format
{Literal: "2", Type: fexpr.TokenText}, // valid time-value
{Literal: "3", Type: fexpr.TokenText}, // valid modifier
{Literal: "4", Type: fexpr.TokenText}, // valid modifier
},
baseTokenResolver,
&ResolverResult{
NullFallback: NullFallbackEnforced,
Identifier: `strftime({:format},{:time},{:m1},{:m2})`,
Params: map[string]any{"format": "1", "time": "2", "m1": "3", "m2": "4"},
},
false,
},
// -----------------------------------------------------------
{
"= 10 args limit",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText},
{Literal: "2", Type: fexpr.TokenText},
{Literal: "3", Type: fexpr.TokenText},
{Literal: "4", Type: fexpr.TokenText},
{Literal: "5", Type: fexpr.TokenText},
{Literal: "6", Type: fexpr.TokenText},
{Literal: "7", Type: fexpr.TokenText},
{Literal: "8", Type: fexpr.TokenText},
{Literal: "9", Type: fexpr.TokenText},
{Literal: "10", Type: fexpr.TokenText},
},
baseTokenResolver,
&ResolverResult{
NullFallback: NullFallbackEnforced,
Identifier: `strftime({:format},{:time},{:m1},{:m2},{:m3},{:m4},{:m5},{:m6},{:m7},{:m8})`,
Params: map[string]any{
"format": "1",
"time": "2",
"m1": "3",
"m2": "4",
"m3": "5",
"m4": "6",
"m5": "7",
"m6": "8",
"m7": "9",
"m8": "10",
},
},
false,
},
{
"> 10 args limit",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText},
{Literal: "2", Type: fexpr.TokenText},
{Literal: "3", Type: fexpr.TokenText},
{Literal: "4", Type: fexpr.TokenText},
{Literal: "5", Type: fexpr.TokenText},
{Literal: "6", Type: fexpr.TokenText},
{Literal: "7", Type: fexpr.TokenText},
{Literal: "8", Type: fexpr.TokenText},
{Literal: "9", Type: fexpr.TokenText},
{Literal: "10", Type: fexpr.TokenText},
{Literal: "11", Type: fexpr.TokenText},
},
baseTokenResolver,
nil,
true,
},
{
"valid arguments but with resolver error",
[]fexpr.Token{
{Literal: "1", Type: fexpr.TokenText},
{Literal: "2", Type: fexpr.TokenText},
{Literal: "3", Type: fexpr.TokenText},
},
func(t fexpr.Token) (*ResolverResult, error) {
return nil, errors.New("test")
},
nil,
true,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
result, err := fn(s.resolver, s.args...)
hasErr := err != nil
if hasErr != s.expectErr {
t.Fatalf("Expected hasErr %v, got %v (%v)", s.expectErr, hasErr, err)
}
testCompareResults(t, s.result, result)
})
}
}
func TestTokenFunctionsStrftimeExec(t *testing.T) {
t.Parallel()
testDB, err := createTestDB()
if err != nil {
t.Fatal(err)
}
defer testDB.Close()
fn, ok := TokenFunctions["strftime"]
if !ok {
t.Error("Expected strftime token function to be registered.")
}
result, err := fn(
func(t fexpr.Token) (*ResolverResult, error) {
placeholder := "t" + security.PseudorandomString(5)
return &ResolverResult{Identifier: "{:" + placeholder + "}", Params: map[string]any{placeholder: t.Literal}}, nil
},
fexpr.Token{Literal: "%Y-%m", Type: fexpr.TokenText},
fexpr.Token{Literal: "2026-01-02 01:02:03.456Z", Type: fexpr.TokenText},
fexpr.Token{Literal: "+1 years", Type: fexpr.TokenText},
fexpr.Token{Literal: "+5 months", Type: fexpr.TokenText},
)
if err != nil {
t.Fatal(err)
}
column := []string{}
err = testDB.NewQuery("select " + result.Identifier).Bind(result.Params).Column(&column)
if err != nil {
t.Fatal(err)
}
if len(column) != 1 {
t.Fatalf("Expected exactly 1 column value as result, got %v", column)
}
expected := "2027-06"
if column[0] != expected {
t.Fatalf("Expected date value %s, got %s", expected, column[0])
}
}
// -------------------------------------------------------------------
func testCompareResults(t *testing.T, a, b *ResolverResult) {
@@ -258,8 +603,12 @@ func testCompareResults(t *testing.T, a, b *ResolverResult) {
t.Fatalf("Expected bMultiMatchSubQuery and bMultiMatchSubQuery to be the same, got\n%s\nvs\n%s", aMultiMatchSubQuery, bMultiMatchSubQuery)
}
if a.NoCoalesce != b.NoCoalesce {
t.Fatalf("Expected NoCoalesce to match, got %v vs %v", a.NoCoalesce, b.NoCoalesce)
if a.NullFallback != b.NullFallback {
t.Fatalf("Expected NullFallback to match, got %v vs %v", a.NullFallback, b.NullFallback)
}
if len(a.Params) != len(b.Params) {
t.Fatalf("Expected equal number of params, got %v vs %v", len(a.Params), len(b.Params))
}
// loose placeholders replacement
+2 -2
View File
@@ -3,7 +3,7 @@ package security
import (
cryptoRand "crypto/rand"
"math/big"
mathRand "math/rand" // @todo replace with rand/v2?
mathRand "math/rand/v2"
)
const defaultRandomAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
@@ -52,7 +52,7 @@ func PseudorandomStringWithAlphabet(length int, alphabet string) string {
max := len(alphabet)
for i := range b {
b[i] = alphabet[mathRand.Intn(max)]
b[i] = alphabet[mathRand.IntN(max)]
}
return string(b)
+7
View File
@@ -3,6 +3,7 @@ package subscriptions_test
import (
"encoding/json"
"strings"
"sync"
"testing"
"time"
@@ -208,12 +209,16 @@ func TestDiscard(t *testing.T) {
}
func TestSend(t *testing.T) {
var mu sync.Mutex
c := subscriptions.NewDefaultClient()
received := []string{}
go func() {
for m := range c.Channel() {
mu.Lock()
received = append(received, m.Name)
mu.Unlock()
}
}()
@@ -226,6 +231,8 @@ func TestSend(t *testing.T) {
expected := []string{"m1", "m2"}
mu.Lock()
defer mu.Unlock()
if len(received) != len(expected) {
t.Fatalf("Expected %d messages, got %d", len(expected), len(received))
}
+1 -1
View File
@@ -9,4 +9,4 @@ PB_DOCS_URL = "https://pocketbase.io/docs"
PB_JS_SDK_URL = "https://github.com/pocketbase/js-sdk"
PB_DART_SDK_URL = "https://github.com/pocketbase/dart-sdk"
PB_RELEASES = "https://github.com/pocketbase/pocketbase/releases"
PB_VERSION = "v0.30.1"
PB_VERSION = "v0.36.4"
@@ -1,4 +1,4 @@
import{S as Ce,i as Be,s as Te,V as Le,X as J,h as u,d as ae,t as Q,a as G,I as N,Z as we,_ as Se,C as De,$ as Re,D as Ue,l as d,n as a,m as ne,u as c,A as y,v as k,c as ie,w as h,p as oe,J as je,k as O,o as qe,W as Ee}from"./index-B8H52oF4.js";import{F as Fe}from"./FieldsQueryParam-hUu_nMS2.js";function ye(n,s,l){const o=n.slice();return o[8]=s[l],o}function Me(n,s,l){const o=n.slice();return o[8]=s[l],o}function Ae(n,s){let l,o=s[8].code+"",p,b,i,f;function m(){return s[6](s[8])}return{key:n,first:null,c(){l=c("button"),p=y(o),b=k(),h(l,"class","tab-item"),O(l,"active",s[1]===s[8].code),this.first=l},m(v,$){d(v,l,$),a(l,p),a(l,b),i||(f=qe(l,"click",m),i=!0)},p(v,$){s=v,$&4&&o!==(o=s[8].code+"")&&N(p,o),$&6&&O(l,"active",s[1]===s[8].code)},d(v){v&&u(l),i=!1,f()}}}function Pe(n,s){let l,o,p,b;return o=new Ee({props:{content:s[8].body}}),{key:n,first:null,c(){l=c("div"),ie(o.$$.fragment),p=k(),h(l,"class","tab-item"),O(l,"active",s[1]===s[8].code),this.first=l},m(i,f){d(i,l,f),ne(o,l,null),a(l,p),b=!0},p(i,f){s=i;const m={};f&4&&(m.content=s[8].body),o.$set(m),(!b||f&6)&&O(l,"active",s[1]===s[8].code)},i(i){b||(G(o.$$.fragment,i),b=!0)},o(i){Q(o.$$.fragment,i),b=!1},d(i){i&&u(l),ae(o)}}}function He(n){var ke,ge;let s,l,o=n[0].name+"",p,b,i,f,m,v,$,g=n[0].name+"",V,ce,W,M,X,L,Z,A,E,re,F,S,ue,z,H=n[0].name+"",K,de,Y,D,x,P,ee,fe,te,T,le,R,se,C,U,w=[],me=new Map,pe,j,_=[],be=new Map,B;M=new Le({props:{js:`
import{S as Ce,i as Be,s as Te,V as Le,X as J,h as u,d as ae,t as Q,a as G,I as N,Z as we,_ as Se,C as De,$ as Re,D as Ue,l as d,n as a,m as ne,u as c,A as y,v as k,c as ie,w as h,p as oe,J as je,k as O,o as qe,W as Ee}from"./index-Bkv3H6ZP.js";import{F as Fe}from"./FieldsQueryParam-Y2XYzYJh.js";function ye(n,s,l){const o=n.slice();return o[8]=s[l],o}function Me(n,s,l){const o=n.slice();return o[8]=s[l],o}function Ae(n,s){let l,o=s[8].code+"",p,b,i,f;function m(){return s[6](s[8])}return{key:n,first:null,c(){l=c("button"),p=y(o),b=k(),h(l,"class","tab-item"),O(l,"active",s[1]===s[8].code),this.first=l},m(v,$){d(v,l,$),a(l,p),a(l,b),i||(f=qe(l,"click",m),i=!0)},p(v,$){s=v,$&4&&o!==(o=s[8].code+"")&&N(p,o),$&6&&O(l,"active",s[1]===s[8].code)},d(v){v&&u(l),i=!1,f()}}}function Pe(n,s){let l,o,p,b;return o=new Ee({props:{content:s[8].body}}),{key:n,first:null,c(){l=c("div"),ie(o.$$.fragment),p=k(),h(l,"class","tab-item"),O(l,"active",s[1]===s[8].code),this.first=l},m(i,f){d(i,l,f),ne(o,l,null),a(l,p),b=!0},p(i,f){s=i;const m={};f&4&&(m.content=s[8].body),o.$set(m),(!b||f&6)&&O(l,"active",s[1]===s[8].code)},i(i){b||(G(o.$$.fragment,i),b=!0)},o(i){Q(o.$$.fragment,i),b=!1},d(i){i&&u(l),ae(o)}}}function He(n){var ke,ge;let s,l,o=n[0].name+"",p,b,i,f,m,v,$,g=n[0].name+"",V,ce,W,M,X,L,Z,A,E,re,F,S,ue,z,H=n[0].name+"",K,de,Y,D,x,P,ee,fe,te,T,le,R,se,C,U,w=[],me=new Map,pe,j,_=[],be=new Map,B;M=new Le({props:{js:`
import PocketBase from 'pocketbase';
const pb = new PocketBase('${n[3]}');
@@ -1,4 +1,4 @@
import{S as je,i as xe,s as Ie,V as Ke,W as Ue,X as I,h as d,d as K,t as E,a as z,I as de,Z as Oe,_ as Qe,C as We,$ as Xe,D as Ze,l as u,n as o,m as Q,u as s,A as k,v as p,c as W,w as b,J as Ve,p as Ge,k as X,o as Ye}from"./index-B8H52oF4.js";import{F as et}from"./FieldsQueryParam-hUu_nMS2.js";function Ee(r,a,l){const n=r.slice();return n[5]=a[l],n}function ze(r,a,l){const n=r.slice();return n[5]=a[l],n}function Je(r,a){let l,n=a[5].code+"",m,_,i,h;function g(){return a[4](a[5])}return{key:r,first:null,c(){l=s("button"),m=k(n),_=p(),b(l,"class","tab-item"),X(l,"active",a[1]===a[5].code),this.first=l},m(v,w){u(v,l,w),o(l,m),o(l,_),i||(h=Ye(l,"click",g),i=!0)},p(v,w){a=v,w&4&&n!==(n=a[5].code+"")&&de(m,n),w&6&&X(l,"active",a[1]===a[5].code)},d(v){v&&d(l),i=!1,h()}}}function Ne(r,a){let l,n,m,_;return n=new Ue({props:{content:a[5].body}}),{key:r,first:null,c(){l=s("div"),W(n.$$.fragment),m=p(),b(l,"class","tab-item"),X(l,"active",a[1]===a[5].code),this.first=l},m(i,h){u(i,l,h),Q(n,l,null),o(l,m),_=!0},p(i,h){a=i;const g={};h&4&&(g.content=a[5].body),n.$set(g),(!_||h&6)&&X(l,"active",a[1]===a[5].code)},i(i){_||(z(n.$$.fragment,i),_=!0)},o(i){E(n.$$.fragment,i),_=!1},d(i){i&&d(l),K(n)}}}function tt(r){var qe,Fe;let a,l,n=r[0].name+"",m,_,i,h,g,v,w,D,Z,S,J,ue,N,M,pe,G,U=r[0].name+"",Y,he,fe,j,ee,q,te,T,oe,be,F,C,ae,me,le,_e,f,ke,P,ge,ve,$e,se,ye,ne,Se,we,Te,re,Ce,Re,A,ie,H,ce,R,L,y=[],Pe=new Map,Ae,O,$=[],Be=new Map,B;v=new Ke({props:{js:`
import{S as je,i as xe,s as Ie,V as Ke,W as Ue,X as I,h as d,d as K,t as E,a as z,I as de,Z as Oe,_ as Qe,C as We,$ as Xe,D as Ze,l as u,n as o,m as Q,u as s,A as k,v as p,c as W,w as b,J as Ve,p as Ge,k as X,o as Ye}from"./index-Bkv3H6ZP.js";import{F as et}from"./FieldsQueryParam-Y2XYzYJh.js";function Ee(r,a,l){const n=r.slice();return n[5]=a[l],n}function ze(r,a,l){const n=r.slice();return n[5]=a[l],n}function Je(r,a){let l,n=a[5].code+"",m,_,i,h;function g(){return a[4](a[5])}return{key:r,first:null,c(){l=s("button"),m=k(n),_=p(),b(l,"class","tab-item"),X(l,"active",a[1]===a[5].code),this.first=l},m(v,w){u(v,l,w),o(l,m),o(l,_),i||(h=Ye(l,"click",g),i=!0)},p(v,w){a=v,w&4&&n!==(n=a[5].code+"")&&de(m,n),w&6&&X(l,"active",a[1]===a[5].code)},d(v){v&&d(l),i=!1,h()}}}function Ne(r,a){let l,n,m,_;return n=new Ue({props:{content:a[5].body}}),{key:r,first:null,c(){l=s("div"),W(n.$$.fragment),m=p(),b(l,"class","tab-item"),X(l,"active",a[1]===a[5].code),this.first=l},m(i,h){u(i,l,h),Q(n,l,null),o(l,m),_=!0},p(i,h){a=i;const g={};h&4&&(g.content=a[5].body),n.$set(g),(!_||h&6)&&X(l,"active",a[1]===a[5].code)},i(i){_||(z(n.$$.fragment,i),_=!0)},o(i){E(n.$$.fragment,i),_=!1},d(i){i&&d(l),K(n)}}}function tt(r){var qe,Fe;let a,l,n=r[0].name+"",m,_,i,h,g,v,w,D,Z,S,J,ue,N,M,pe,G,U=r[0].name+"",Y,he,fe,j,ee,q,te,T,oe,be,F,C,ae,me,le,_e,f,ke,P,ge,ve,$e,se,ye,ne,Se,we,Te,re,Ce,Re,A,ie,H,ce,R,L,y=[],Pe=new Map,Ae,O,$=[],Be=new Map,B;v=new Ke({props:{js:`
import PocketBase from 'pocketbase';
const pb = new PocketBase('${r[3]}');
@@ -1,4 +1,4 @@
import{S as Je,i as xe,s as Ee,V as Ne,W as je,X as Q,h as r,d as Z,t as j,a as J,I as pe,Z as Ue,_ as Ie,C as Qe,$ as Ze,D as ze,l as c,n as a,m as z,u as o,A as _,v as h,c as K,w as p,J as Be,p as Ke,k as X,o as Xe}from"./index-B8H52oF4.js";import{F as Ge}from"./FieldsQueryParam-hUu_nMS2.js";function Fe(s,l,n){const i=s.slice();return i[5]=l[n],i}function Le(s,l,n){const i=s.slice();return i[5]=l[n],i}function He(s,l){let n,i=l[5].code+"",f,g,d,b;function k(){return l[4](l[5])}return{key:s,first:null,c(){n=o("button"),f=_(i),g=h(),p(n,"class","tab-item"),X(n,"active",l[1]===l[5].code),this.first=n},m(v,O){c(v,n,O),a(n,f),a(n,g),d||(b=Xe(n,"click",k),d=!0)},p(v,O){l=v,O&4&&i!==(i=l[5].code+"")&&pe(f,i),O&6&&X(n,"active",l[1]===l[5].code)},d(v){v&&r(n),d=!1,b()}}}function Ve(s,l){let n,i,f,g;return i=new je({props:{content:l[5].body}}),{key:s,first:null,c(){n=o("div"),K(i.$$.fragment),f=h(),p(n,"class","tab-item"),X(n,"active",l[1]===l[5].code),this.first=n},m(d,b){c(d,n,b),z(i,n,null),a(n,f),g=!0},p(d,b){l=d;const k={};b&4&&(k.content=l[5].body),i.$set(k),(!g||b&6)&&X(n,"active",l[1]===l[5].code)},i(d){g||(J(i.$$.fragment,d),g=!0)},o(d){j(i.$$.fragment,d),g=!1},d(d){d&&r(n),Z(i)}}}function Ye(s){let l,n,i=s[0].name+"",f,g,d,b,k,v,O,R,G,A,x,be,E,P,me,Y,N=s[0].name+"",ee,fe,te,M,ae,W,le,U,ne,y,oe,ge,B,S,se,_e,ie,ke,m,ve,C,we,$e,Oe,re,Ae,ce,ye,Se,Te,de,Ce,qe,q,ue,F,he,T,L,$=[],De=new Map,Re,H,w=[],Pe=new Map,D;v=new Ne({props:{js:`
import{S as Je,i as xe,s as Ee,V as Ne,W as je,X as Q,h as r,d as Z,t as j,a as J,I as pe,Z as Ue,_ as Ie,C as Qe,$ as Ze,D as ze,l as c,n as a,m as z,u as o,A as _,v as h,c as K,w as p,J as Be,p as Ke,k as X,o as Xe}from"./index-Bkv3H6ZP.js";import{F as Ge}from"./FieldsQueryParam-Y2XYzYJh.js";function Fe(s,l,n){const i=s.slice();return i[5]=l[n],i}function Le(s,l,n){const i=s.slice();return i[5]=l[n],i}function He(s,l){let n,i=l[5].code+"",f,g,d,b;function k(){return l[4](l[5])}return{key:s,first:null,c(){n=o("button"),f=_(i),g=h(),p(n,"class","tab-item"),X(n,"active",l[1]===l[5].code),this.first=n},m(v,O){c(v,n,O),a(n,f),a(n,g),d||(b=Xe(n,"click",k),d=!0)},p(v,O){l=v,O&4&&i!==(i=l[5].code+"")&&pe(f,i),O&6&&X(n,"active",l[1]===l[5].code)},d(v){v&&r(n),d=!1,b()}}}function Ve(s,l){let n,i,f,g;return i=new je({props:{content:l[5].body}}),{key:s,first:null,c(){n=o("div"),K(i.$$.fragment),f=h(),p(n,"class","tab-item"),X(n,"active",l[1]===l[5].code),this.first=n},m(d,b){c(d,n,b),z(i,n,null),a(n,f),g=!0},p(d,b){l=d;const k={};b&4&&(k.content=l[5].body),i.$set(k),(!g||b&6)&&X(n,"active",l[1]===l[5].code)},i(d){g||(J(i.$$.fragment,d),g=!0)},o(d){j(i.$$.fragment,d),g=!1},d(d){d&&r(n),Z(i)}}}function Ye(s){let l,n,i=s[0].name+"",f,g,d,b,k,v,O,R,G,A,x,be,E,P,me,Y,N=s[0].name+"",ee,fe,te,M,ae,W,le,U,ne,y,oe,ge,B,S,se,_e,ie,ke,m,ve,C,we,$e,Oe,re,Ae,ce,ye,Se,Te,de,Ce,qe,q,ue,F,he,T,L,$=[],De=new Map,Re,H,w=[],Pe=new Map,D;v=new Ne({props:{js:`
import PocketBase from 'pocketbase';
const pb = new PocketBase('${s[3]}');
@@ -1,4 +1,4 @@
import{S as be,i as _e,s as ve,W as ge,X as V,h as b,d as x,t as j,a as J,I as ce,Z as de,_ as je,C as ue,$ as Qe,D as he,l as _,n as s,m as ee,u as d,v as T,A as R,c as te,w as g,J as ke,k as N,o as $e,V as Ke,Y as De,p as Xe,a0 as Me}from"./index-B8H52oF4.js";import{F as Ze}from"./FieldsQueryParam-hUu_nMS2.js";function Be(a,t,e){const l=a.slice();return l[4]=t[e],l}function Ie(a,t,e){const l=a.slice();return l[4]=t[e],l}function We(a,t){let e,l=t[4].code+"",h,i,c,n;function m(){return t[3](t[4])}return{key:a,first:null,c(){e=d("button"),h=R(l),i=T(),g(e,"class","tab-item"),N(e,"active",t[1]===t[4].code),this.first=e},m(v,C){_(v,e,C),s(e,h),s(e,i),c||(n=$e(e,"click",m),c=!0)},p(v,C){t=v,C&4&&l!==(l=t[4].code+"")&&ce(h,l),C&6&&N(e,"active",t[1]===t[4].code)},d(v){v&&b(e),c=!1,n()}}}function Fe(a,t){let e,l,h,i;return l=new ge({props:{content:t[4].body}}),{key:a,first:null,c(){e=d("div"),te(l.$$.fragment),h=T(),g(e,"class","tab-item"),N(e,"active",t[1]===t[4].code),this.first=e},m(c,n){_(c,e,n),ee(l,e,null),s(e,h),i=!0},p(c,n){t=c;const m={};n&4&&(m.content=t[4].body),l.$set(m),(!i||n&6)&&N(e,"active",t[1]===t[4].code)},i(c){i||(J(l.$$.fragment,c),i=!0)},o(c){j(l.$$.fragment,c),i=!1},d(c){c&&b(e),x(l)}}}function ze(a){let t,e,l,h,i,c,n,m=a[0].name+"",v,C,F,B,I,D,Q,M,U,y,O,q,k,L,Y,A,X,E,o,$,P,z,u,p,S,w,Z,we,Te,Pe,pe,Oe,ye,le,fe,oe,me,G,ae,K=[],Se=new Map,qe,ne,H=[],Ce=new Map,se;P=new ge({props:{content:"?expand=relField1,relField2.subRelField"}}),le=new Ze({props:{prefix:"record."}});let re=V(a[2]);const Ae=r=>r[4].code;for(let r=0;r<re.length;r+=1){let f=Ie(a,re,r),W=Ae(f);Se.set(W,K[r]=We(W,f))}let ie=V(a[2]);const Re=r=>r[4].code;for(let r=0;r<ie.length;r+=1){let f=Be(a,ie,r),W=Re(f);Ce.set(W,H[r]=Fe(W,f))}return{c(){t=d("div"),e=d("strong"),e.textContent="POST",l=T(),h=d("div"),i=d("p"),c=R("/api/collections/"),n=d("strong"),v=R(m),C=R("/auth-with-otp"),F=T(),B=d("div"),B.textContent="Body Parameters",I=T(),D=d("table"),D.innerHTML='<thead><tr><th>Param</th> <th>Type</th> <th width="50%">Description</th></tr></thead> <tbody><tr><td><div class="inline-flex"><span class="label label-success">Required</span> <span>otpId</span></div></td> <td><span class="label">String</span></td> <td>The id of the OTP request.</td></tr> <tr><td><div class="inline-flex"><span class="label label-success">Required</span> <span>password</span></div></td> <td><span class="label">String</span></td> <td>The one-time password.</td></tr></tbody>',Q=T(),M=d("div"),M.textContent="Query parameters",U=T(),y=d("table"),O=d("thead"),O.innerHTML='<tr><th>Param</th> <th>Type</th> <th width="60%">Description</th></tr>',q=T(),k=d("tbody"),L=d("tr"),Y=d("td"),Y.textContent="expand",A=T(),X=d("td"),X.innerHTML='<span class="label">String</span>',E=T(),o=d("td"),$=R(`Auto expand record relations. Ex.:
import{S as be,i as _e,s as ve,W as ge,X as V,h as b,d as x,t as j,a as J,I as ce,Z as de,_ as je,C as ue,$ as Qe,D as he,l as _,n as s,m as ee,u as d,v as T,A as R,c as te,w as g,J as ke,k as N,o as $e,V as Ke,Y as De,p as Xe,a0 as Me}from"./index-Bkv3H6ZP.js";import{F as Ze}from"./FieldsQueryParam-Y2XYzYJh.js";function Be(a,t,e){const l=a.slice();return l[4]=t[e],l}function Ie(a,t,e){const l=a.slice();return l[4]=t[e],l}function We(a,t){let e,l=t[4].code+"",h,i,c,n;function m(){return t[3](t[4])}return{key:a,first:null,c(){e=d("button"),h=R(l),i=T(),g(e,"class","tab-item"),N(e,"active",t[1]===t[4].code),this.first=e},m(v,C){_(v,e,C),s(e,h),s(e,i),c||(n=$e(e,"click",m),c=!0)},p(v,C){t=v,C&4&&l!==(l=t[4].code+"")&&ce(h,l),C&6&&N(e,"active",t[1]===t[4].code)},d(v){v&&b(e),c=!1,n()}}}function Fe(a,t){let e,l,h,i;return l=new ge({props:{content:t[4].body}}),{key:a,first:null,c(){e=d("div"),te(l.$$.fragment),h=T(),g(e,"class","tab-item"),N(e,"active",t[1]===t[4].code),this.first=e},m(c,n){_(c,e,n),ee(l,e,null),s(e,h),i=!0},p(c,n){t=c;const m={};n&4&&(m.content=t[4].body),l.$set(m),(!i||n&6)&&N(e,"active",t[1]===t[4].code)},i(c){i||(J(l.$$.fragment,c),i=!0)},o(c){j(l.$$.fragment,c),i=!1},d(c){c&&b(e),x(l)}}}function ze(a){let t,e,l,h,i,c,n,m=a[0].name+"",v,C,F,B,I,D,Q,M,U,y,O,q,k,L,Y,A,X,E,o,$,P,z,u,p,S,w,Z,we,Te,Pe,pe,Oe,ye,le,fe,oe,me,G,ae,K=[],Se=new Map,qe,ne,H=[],Ce=new Map,se;P=new ge({props:{content:"?expand=relField1,relField2.subRelField"}}),le=new Ze({props:{prefix:"record."}});let re=V(a[2]);const Ae=r=>r[4].code;for(let r=0;r<re.length;r+=1){let f=Ie(a,re,r),W=Ae(f);Se.set(W,K[r]=We(W,f))}let ie=V(a[2]);const Re=r=>r[4].code;for(let r=0;r<ie.length;r+=1){let f=Be(a,ie,r),W=Re(f);Ce.set(W,H[r]=Fe(W,f))}return{c(){t=d("div"),e=d("strong"),e.textContent="POST",l=T(),h=d("div"),i=d("p"),c=R("/api/collections/"),n=d("strong"),v=R(m),C=R("/auth-with-otp"),F=T(),B=d("div"),B.textContent="Body Parameters",I=T(),D=d("table"),D.innerHTML='<thead><tr><th>Param</th> <th>Type</th> <th width="50%">Description</th></tr></thead> <tbody><tr><td><div class="inline-flex"><span class="label label-success">Required</span> <span>otpId</span></div></td> <td><span class="label">String</span></td> <td>The id of the OTP request.</td></tr> <tr><td><div class="inline-flex"><span class="label label-success">Required</span> <span>password</span></div></td> <td><span class="label">String</span></td> <td>The one-time password.</td></tr></tbody>',Q=T(),M=d("div"),M.textContent="Query parameters",U=T(),y=d("table"),O=d("thead"),O.innerHTML='<tr><th>Param</th> <th>Type</th> <th width="60%">Description</th></tr>',q=T(),k=d("tbody"),L=d("tr"),Y=d("td"),Y.textContent="expand",A=T(),X=d("td"),X.innerHTML='<span class="label">String</span>',E=T(),o=d("td"),$=R(`Auto expand record relations. Ex.:
`),te(P.$$.fragment),z=R(`
Supports up to 6-levels depth nested relations expansion. `),u=d("br"),p=R(`
The expanded relations will be appended to the record under the
@@ -1,4 +1,4 @@
import{S as kt,i as gt,s as vt,V as St,X as L,W as _t,h as c,d as ae,Y as wt,t as X,a as Z,I as z,Z as ct,_ as yt,C as $t,$ as Pt,D as Ct,l as d,n as t,m as oe,u as s,A as f,v as u,c as se,w as k,J as dt,p as Rt,k as ne,o as Ot}from"./index-B8H52oF4.js";import{F as Tt}from"./FieldsQueryParam-hUu_nMS2.js";function pt(i,o,a){const n=i.slice();return n[7]=o[a],n}function ut(i,o,a){const n=i.slice();return n[7]=o[a],n}function ht(i,o,a){const n=i.slice();return n[12]=o[a],n[14]=a,n}function At(i){let o;return{c(){o=f("or")},m(a,n){d(a,o,n)},d(a){a&&c(o)}}}function bt(i){let o,a,n=i[12]+"",m,b=i[14]>0&&At();return{c(){b&&b.c(),o=u(),a=s("strong"),m=f(n)},m(r,h){b&&b.m(r,h),d(r,o,h),d(r,a,h),t(a,m)},p(r,h){h&2&&n!==(n=r[12]+"")&&z(m,n)},d(r){r&&(c(o),c(a)),b&&b.d(r)}}}function ft(i,o){let a,n=o[7].code+"",m,b,r,h;function g(){return o[6](o[7])}return{key:i,first:null,c(){a=s("button"),m=f(n),b=u(),k(a,"class","tab-item"),ne(a,"active",o[2]===o[7].code),this.first=a},m($,_){d($,a,_),t(a,m),t(a,b),r||(h=Ot(a,"click",g),r=!0)},p($,_){o=$,_&8&&n!==(n=o[7].code+"")&&z(m,n),_&12&&ne(a,"active",o[2]===o[7].code)},d($){$&&c(a),r=!1,h()}}}function mt(i,o){let a,n,m,b;return n=new _t({props:{content:o[7].body}}),{key:i,first:null,c(){a=s("div"),se(n.$$.fragment),m=u(),k(a,"class","tab-item"),ne(a,"active",o[2]===o[7].code),this.first=a},m(r,h){d(r,a,h),oe(n,a,null),t(a,m),b=!0},p(r,h){o=r;const g={};h&8&&(g.content=o[7].body),n.$set(g),(!b||h&12)&&ne(a,"active",o[2]===o[7].code)},i(r){b||(Z(n.$$.fragment,r),b=!0)},o(r){X(n.$$.fragment,r),b=!1},d(r){r&&c(a),ae(n)}}}function Dt(i){var ot,st;let o,a,n=i[0].name+"",m,b,r,h,g,$,_,G=i[1].join("/")+"",ie,De,re,We,ce,C,de,q,pe,R,x,Fe,ee,H,Me,ue,te=i[0].name+"",he,Ue,be,Y,fe,O,me,Be,j,T,_e,Le,ke,qe,V,ge,He,ve,Se,E,we,A,ye,Ye,N,D,$e,je,Pe,Ve,v,Ee,M,Ne,Ie,Je,Ce,Qe,Re,Ke,Xe,Ze,Oe,ze,Ge,U,Te,I,Ae,W,J,P=[],xe=new Map,et,Q,w=[],tt=new Map,F;C=new St({props:{js:`
import{S as kt,i as gt,s as vt,V as St,X as L,W as _t,h as c,d as ae,Y as wt,t as X,a as Z,I as z,Z as ct,_ as yt,C as $t,$ as Pt,D as Ct,l as d,n as t,m as oe,u as s,A as f,v as u,c as se,w as k,J as dt,p as Rt,k as ne,o as Ot}from"./index-Bkv3H6ZP.js";import{F as Tt}from"./FieldsQueryParam-Y2XYzYJh.js";function pt(i,o,a){const n=i.slice();return n[7]=o[a],n}function ut(i,o,a){const n=i.slice();return n[7]=o[a],n}function ht(i,o,a){const n=i.slice();return n[12]=o[a],n[14]=a,n}function At(i){let o;return{c(){o=f("or")},m(a,n){d(a,o,n)},d(a){a&&c(o)}}}function bt(i){let o,a,n=i[12]+"",m,b=i[14]>0&&At();return{c(){b&&b.c(),o=u(),a=s("strong"),m=f(n)},m(r,h){b&&b.m(r,h),d(r,o,h),d(r,a,h),t(a,m)},p(r,h){h&2&&n!==(n=r[12]+"")&&z(m,n)},d(r){r&&(c(o),c(a)),b&&b.d(r)}}}function ft(i,o){let a,n=o[7].code+"",m,b,r,h;function g(){return o[6](o[7])}return{key:i,first:null,c(){a=s("button"),m=f(n),b=u(),k(a,"class","tab-item"),ne(a,"active",o[2]===o[7].code),this.first=a},m($,_){d($,a,_),t(a,m),t(a,b),r||(h=Ot(a,"click",g),r=!0)},p($,_){o=$,_&8&&n!==(n=o[7].code+"")&&z(m,n),_&12&&ne(a,"active",o[2]===o[7].code)},d($){$&&c(a),r=!1,h()}}}function mt(i,o){let a,n,m,b;return n=new _t({props:{content:o[7].body}}),{key:i,first:null,c(){a=s("div"),se(n.$$.fragment),m=u(),k(a,"class","tab-item"),ne(a,"active",o[2]===o[7].code),this.first=a},m(r,h){d(r,a,h),oe(n,a,null),t(a,m),b=!0},p(r,h){o=r;const g={};h&8&&(g.content=o[7].body),n.$set(g),(!b||h&12)&&ne(a,"active",o[2]===o[7].code)},i(r){b||(Z(n.$$.fragment,r),b=!0)},o(r){X(n.$$.fragment,r),b=!1},d(r){r&&c(a),ae(n)}}}function Dt(i){var ot,st;let o,a,n=i[0].name+"",m,b,r,h,g,$,_,G=i[1].join("/")+"",ie,De,re,We,ce,C,de,q,pe,R,x,Fe,ee,H,Me,ue,te=i[0].name+"",he,Ue,be,Y,fe,O,me,Be,j,T,_e,Le,ke,qe,V,ge,He,ve,Se,E,we,A,ye,Ye,N,D,$e,je,Pe,Ve,v,Ee,M,Ne,Ie,Je,Ce,Qe,Re,Ke,Xe,Ze,Oe,ze,Ge,U,Te,I,Ae,W,J,P=[],xe=new Map,et,Q,w=[],tt=new Map,F;C=new St({props:{js:`
import PocketBase from 'pocketbase';
const pb = new PocketBase('${i[5]}');
@@ -1,4 +1,4 @@
import{S as St,i as At,s as Lt,V as Mt,W as Ht,X as Q,h as d,d as Re,t as Y,a as x,I as jt,Z as Pt,_ as Nt,C as Ut,$ as Jt,D as zt,l as u,n as t,m as Te,E as Wt,G as Gt,u as o,A as _,v as i,c as Pe,w as b,J as Ft,p as Kt,k as ee,o as Vt}from"./index-B8H52oF4.js";function Bt(a,s,n){const c=a.slice();return c[6]=s[n],c}function Et(a,s,n){const c=a.slice();return c[6]=s[n],c}function Ot(a,s){let n,c,y;function f(){return s[5](s[6])}return{key:a,first:null,c(){n=o("button"),n.textContent=`${s[6].code} `,b(n,"class","tab-item"),ee(n,"active",s[1]===s[6].code),this.first=n},m(r,h){u(r,n,h),c||(y=Vt(n,"click",f),c=!0)},p(r,h){s=r,h&10&&ee(n,"active",s[1]===s[6].code)},d(r){r&&d(n),c=!1,y()}}}function It(a,s){let n,c,y,f;return c=new Ht({props:{content:s[6].body}}),{key:a,first:null,c(){n=o("div"),Pe(c.$$.fragment),y=i(),b(n,"class","tab-item"),ee(n,"active",s[1]===s[6].code),this.first=n},m(r,h){u(r,n,h),Te(c,n,null),t(n,y),f=!0},p(r,h){s=r,(!f||h&10)&&ee(n,"active",s[1]===s[6].code)},i(r){f||(x(c.$$.fragment,r),f=!0)},o(r){Y(c.$$.fragment,r),f=!1},d(r){r&&d(n),Re(c)}}}function Xt(a){var pt,mt,bt,ht,ft,_t,yt,kt;let s,n,c=a[0].name+"",y,f,r,h,F,g,U,Fe,P,B,Be,E,Ee,Oe,te,le,w,oe,O,ae,I,se,H,ne,J,ie,q,ce,Ie,re,S,z,He,k,W,Se,de,Ae,D,G,Le,ue,Me,K,je,pe,Ne,C,Ue,me,Je,ze,We,V,Ge,X,Ke,be,Ve,he,Xe,fe,Ze,p,_e,Qe,ye,Ye,ke,xe,$e,et,ge,tt,ve,lt,ot,at,De,st,R,Ce,A,we,T,L,v=[],nt=new Map,it,M,$=[],ct=new Map,j,qe,rt;w=new Mt({props:{js:`
import{S as St,i as At,s as Lt,V as Mt,W as Ht,X as Q,h as d,d as Re,t as Y,a as x,I as jt,Z as Pt,_ as Nt,C as Ut,$ as Jt,D as zt,l as u,n as t,m as Te,E as Wt,G as Gt,u as o,A as _,v as i,c as Pe,w as b,J as Ft,p as Kt,k as ee,o as Vt}from"./index-Bkv3H6ZP.js";function Bt(a,s,n){const c=a.slice();return c[6]=s[n],c}function Et(a,s,n){const c=a.slice();return c[6]=s[n],c}function Ot(a,s){let n,c,y;function f(){return s[5](s[6])}return{key:a,first:null,c(){n=o("button"),n.textContent=`${s[6].code} `,b(n,"class","tab-item"),ee(n,"active",s[1]===s[6].code),this.first=n},m(r,h){u(r,n,h),c||(y=Vt(n,"click",f),c=!0)},p(r,h){s=r,h&10&&ee(n,"active",s[1]===s[6].code)},d(r){r&&d(n),c=!1,y()}}}function It(a,s){let n,c,y,f;return c=new Ht({props:{content:s[6].body}}),{key:a,first:null,c(){n=o("div"),Pe(c.$$.fragment),y=i(),b(n,"class","tab-item"),ee(n,"active",s[1]===s[6].code),this.first=n},m(r,h){u(r,n,h),Te(c,n,null),t(n,y),f=!0},p(r,h){s=r,(!f||h&10)&&ee(n,"active",s[1]===s[6].code)},i(r){f||(x(c.$$.fragment,r),f=!0)},o(r){Y(c.$$.fragment,r),f=!1},d(r){r&&d(n),Re(c)}}}function Xt(a){var pt,mt,bt,ht,ft,_t,yt,kt;let s,n,c=a[0].name+"",y,f,r,h,F,g,U,Fe,P,B,Be,E,Ee,Oe,te,le,w,oe,O,ae,I,se,H,ne,J,ie,q,ce,Ie,re,S,z,He,k,W,Se,de,Ae,D,G,Le,ue,Me,K,je,pe,Ne,C,Ue,me,Je,ze,We,V,Ge,X,Ke,be,Ve,he,Xe,fe,Ze,p,_e,Qe,ye,Ye,ke,xe,$e,et,ge,tt,ve,lt,ot,at,De,st,R,Ce,A,we,T,L,v=[],nt=new Map,it,M,$=[],ct=new Map,j,qe,rt;w=new Mt({props:{js:`
import PocketBase from 'pocketbase';
const pb = new PocketBase('${a[2]}');
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,4 +1,4 @@
import{S as $t,i as qt,s as Tt,V as St,X as ce,W as Ct,h as o,d as $e,t as he,a as ve,I as ae,Z as Ne,_ as pt,C as Mt,$ as Pt,D as Lt,l as r,n as i,m as qe,u as a,A as b,v as p,c as Te,w,J as we,p as Ft,k as Se,o as Ht,L as Ot,H as fe}from"./index-B8H52oF4.js";import{F as Rt}from"./FieldsQueryParam-hUu_nMS2.js";function mt(s,e,t){const l=s.slice();return l[10]=e[t],l}function bt(s,e,t){const l=s.slice();return l[10]=e[t],l}function _t(s,e,t){const l=s.slice();return l[15]=e[t],l}function kt(s){let e;return{c(){e=a("p"),e.innerHTML="Requires superuser <code>Authorization:TOKEN</code> header",w(e,"class","txt-hint txt-sm txt-right")},m(t,l){r(t,e,l)},d(t){t&&o(e)}}}function yt(s){let e,t,l,c,f,u,_,m,q,y,g,B,S,$,R,P,I,D,M,W,L,T,k,F,ee,z,U,oe,K,X,Y;function ue(h,C){var N,x,O;return C&1&&(u=null),u==null&&(u=!!((O=(x=(N=h[0])==null?void 0:N.fields)==null?void 0:x.find(Yt))!=null&&O.required)),u?Bt:At}let te=ue(s,-1),E=te(s);function Z(h,C){var N,x,O;return C&1&&(I=null),I==null&&(I=!!((O=(x=(N=h[0])==null?void 0:N.fields)==null?void 0:x.find(Xt))!=null&&O.required)),I?Nt:Vt}let G=Z(s,-1),H=G(s);return{c(){e=a("tr"),e.innerHTML='<td colspan="3" class="txt-hint txt-bold">Auth specific fields</td>',t=p(),l=a("tr"),c=a("td"),f=a("div"),E.c(),_=p(),m=a("span"),m.textContent="email",q=p(),y=a("td"),y.innerHTML='<span class="label">String</span>',g=p(),B=a("td"),B.textContent="Auth record email address.",S=p(),$=a("tr"),R=a("td"),P=a("div"),H.c(),D=p(),M=a("span"),M.textContent="emailVisibility",W=p(),L=a("td"),L.innerHTML='<span class="label">Boolean</span>',T=p(),k=a("td"),k.textContent="Whether to show/hide the auth record email when fetching the record data.",F=p(),ee=a("tr"),ee.innerHTML='<td><div class="inline-flex"><span class="label label-success">Required</span> <span>password</span></div></td> <td><span class="label">String</span></td> <td>Auth record password.</td>',z=p(),U=a("tr"),U.innerHTML='<td><div class="inline-flex"><span class="label label-success">Required</span> <span>passwordConfirm</span></div></td> <td><span class="label">String</span></td> <td>Auth record password confirmation.</td>',oe=p(),K=a("tr"),K.innerHTML=`<td><div class="inline-flex"><span class="label label-warning">Optional</span> <span>verified</span></div></td> <td><span class="label">Boolean</span></td> <td>Indicates whether the auth record is verified or not.
import{S as $t,i as qt,s as Tt,V as St,X as ce,W as Ct,h as o,d as $e,t as he,a as ve,I as ae,Z as Ne,_ as pt,C as Mt,$ as Pt,D as Lt,l as r,n as i,m as qe,u as a,A as b,v as p,c as Te,w,J as we,p as Ft,k as Se,o as Ht,L as Ot,H as fe}from"./index-Bkv3H6ZP.js";import{F as Rt}from"./FieldsQueryParam-Y2XYzYJh.js";function mt(s,e,t){const l=s.slice();return l[10]=e[t],l}function bt(s,e,t){const l=s.slice();return l[10]=e[t],l}function _t(s,e,t){const l=s.slice();return l[15]=e[t],l}function kt(s){let e;return{c(){e=a("p"),e.innerHTML="Requires superuser <code>Authorization:TOKEN</code> header",w(e,"class","txt-hint txt-sm txt-right")},m(t,l){r(t,e,l)},d(t){t&&o(e)}}}function yt(s){let e,t,l,c,f,u,_,m,q,y,g,B,S,$,R,P,I,D,M,W,L,T,k,F,ee,z,U,oe,K,X,Y;function ue(h,C){var N,x,O;return C&1&&(u=null),u==null&&(u=!!((O=(x=(N=h[0])==null?void 0:N.fields)==null?void 0:x.find(Yt))!=null&&O.required)),u?Bt:At}let te=ue(s,-1),E=te(s);function Z(h,C){var N,x,O;return C&1&&(I=null),I==null&&(I=!!((O=(x=(N=h[0])==null?void 0:N.fields)==null?void 0:x.find(Xt))!=null&&O.required)),I?Nt:Vt}let G=Z(s,-1),H=G(s);return{c(){e=a("tr"),e.innerHTML='<td colspan="3" class="txt-hint txt-bold">Auth specific fields</td>',t=p(),l=a("tr"),c=a("td"),f=a("div"),E.c(),_=p(),m=a("span"),m.textContent="email",q=p(),y=a("td"),y.innerHTML='<span class="label">String</span>',g=p(),B=a("td"),B.textContent="Auth record email address.",S=p(),$=a("tr"),R=a("td"),P=a("div"),H.c(),D=p(),M=a("span"),M.textContent="emailVisibility",W=p(),L=a("td"),L.innerHTML='<span class="label">Boolean</span>',T=p(),k=a("td"),k.textContent="Whether to show/hide the auth record email when fetching the record data.",F=p(),ee=a("tr"),ee.innerHTML='<td><div class="inline-flex"><span class="label label-success">Required</span> <span>password</span></div></td> <td><span class="label">String</span></td> <td>Auth record password.</td>',z=p(),U=a("tr"),U.innerHTML='<td><div class="inline-flex"><span class="label label-success">Required</span> <span>passwordConfirm</span></div></td> <td><span class="label">String</span></td> <td>Auth record password confirmation.</td>',oe=p(),K=a("tr"),K.innerHTML=`<td><div class="inline-flex"><span class="label label-warning">Optional</span> <span>verified</span></div></td> <td><span class="label">Boolean</span></td> <td>Indicates whether the auth record is verified or not.
<br/>
This field can be set only by superusers or auth records with &quot;Manage&quot; access.</td>`,X=p(),Y=a("tr"),Y.innerHTML='<td colspan="3" class="txt-hint txt-bold">Other fields</td>',w(f,"class","inline-flex"),w(P,"class","inline-flex")},m(h,C){r(h,e,C),r(h,t,C),r(h,l,C),i(l,c),i(c,f),E.m(f,null),i(f,_),i(f,m),i(l,q),i(l,y),i(l,g),i(l,B),r(h,S,C),r(h,$,C),i($,R),i(R,P),H.m(P,null),i(P,D),i(P,M),i($,W),i($,L),i($,T),i($,k),r(h,F,C),r(h,ee,C),r(h,z,C),r(h,U,C),r(h,oe,C),r(h,K,C),r(h,X,C),r(h,Y,C)},p(h,C){te!==(te=ue(h,C))&&(E.d(1),E=te(h),E&&(E.c(),E.m(f,_))),G!==(G=Z(h,C))&&(H.d(1),H=G(h),H&&(H.c(),H.m(P,D)))},d(h){h&&(o(e),o(t),o(l),o(S),o($),o(F),o(ee),o(z),o(U),o(oe),o(K),o(X),o(Y)),E.d(),H.d()}}}function At(s){let e;return{c(){e=a("span"),e.textContent="Optional",w(e,"class","label label-warning")},m(t,l){r(t,e,l)},d(t){t&&o(e)}}}function Bt(s){let e;return{c(){e=a("span"),e.textContent="Required",w(e,"class","label label-success")},m(t,l){r(t,e,l)},d(t){t&&o(e)}}}function Vt(s){let e;return{c(){e=a("span"),e.textContent="Optional",w(e,"class","label label-warning")},m(t,l){r(t,e,l)},d(t){t&&o(e)}}}function Nt(s){let e;return{c(){e=a("span"),e.textContent="Required",w(e,"class","label label-success")},m(t,l){r(t,e,l)},d(t){t&&o(e)}}}function jt(s){let e;return{c(){e=a("span"),e.textContent="Required",w(e,"class","label label-success")},m(t,l){r(t,e,l)},d(t){t&&o(e)}}}function Jt(s){let e;return{c(){e=a("span"),e.textContent="Optional",w(e,"class","label label-warning")},m(t,l){r(t,e,l)},d(t){t&&o(e)}}}function Dt(s){let e,t=s[15].maxSelect===1?"id":"ids",l,c;return{c(){e=b("Relation record "),l=b(t),c=b(".")},m(f,u){r(f,e,u),r(f,l,u),r(f,c,u)},p(f,u){u&32&&t!==(t=f[15].maxSelect===1?"id":"ids")&&ae(l,t)},d(f){f&&(o(e),o(l),o(c))}}}function Et(s){let e,t,l,c,f,u,_,m,q;return{c(){e=b("File object."),t=a("br"),l=b(`
Set to empty value (`),c=a("code"),c.textContent="null",f=b(", "),u=a("code"),u.textContent='""',_=b(" or "),m=a("code"),m.textContent="[]",q=b(`) to delete
@@ -1,4 +1,4 @@
import{S as Re,i as Ee,s as Pe,V as Te,X as j,h as p,d as De,t as te,a as le,I as ee,Z as he,_ as Be,C as Ie,$ as Oe,D as Ae,l as f,n as i,m as Ce,u as c,A as $,v as k,c as we,w as m,J as Me,p as qe,k as z,o as Le,W as Se}from"./index-B8H52oF4.js";function ke(a,l,s){const n=a.slice();return n[6]=l[s],n}function ge(a,l,s){const n=a.slice();return n[6]=l[s],n}function ve(a){let l;return{c(){l=c("p"),l.innerHTML="Requires superuser <code>Authorization:TOKEN</code> header",m(l,"class","txt-hint txt-sm txt-right")},m(s,n){f(s,l,n)},d(s){s&&p(l)}}}function $e(a,l){let s,n,h;function r(){return l[5](l[6])}return{key:a,first:null,c(){s=c("button"),s.textContent=`${l[6].code} `,m(s,"class","tab-item"),z(s,"active",l[2]===l[6].code),this.first=s},m(o,d){f(o,s,d),n||(h=Le(s,"click",r),n=!0)},p(o,d){l=o,d&20&&z(s,"active",l[2]===l[6].code)},d(o){o&&p(s),n=!1,h()}}}function ye(a,l){let s,n,h,r;return n=new Se({props:{content:l[6].body}}),{key:a,first:null,c(){s=c("div"),we(n.$$.fragment),h=k(),m(s,"class","tab-item"),z(s,"active",l[2]===l[6].code),this.first=s},m(o,d){f(o,s,d),Ce(n,s,null),i(s,h),r=!0},p(o,d){l=o,(!r||d&20)&&z(s,"active",l[2]===l[6].code)},i(o){r||(le(n.$$.fragment,o),r=!0)},o(o){te(n.$$.fragment,o),r=!1},d(o){o&&p(s),De(n)}}}function He(a){var fe,me;let l,s,n=a[0].name+"",h,r,o,d,y,D,F,q=a[0].name+"",J,se,K,C,N,P,V,g,L,ae,S,E,ne,W,H=a[0].name+"",X,oe,Z,ie,G,T,Q,B,Y,I,x,w,O,v=[],ce=new Map,re,A,b=[],de=new Map,R;C=new Te({props:{js:`
import{S as Re,i as Ee,s as Pe,V as Te,X as j,h as p,d as De,t as te,a as le,I as ee,Z as he,_ as Be,C as Ie,$ as Oe,D as Ae,l as f,n as i,m as Ce,u as c,A as $,v as k,c as we,w as m,J as Me,p as qe,k as z,o as Le,W as Se}from"./index-Bkv3H6ZP.js";function ke(a,l,s){const n=a.slice();return n[6]=l[s],n}function ge(a,l,s){const n=a.slice();return n[6]=l[s],n}function ve(a){let l;return{c(){l=c("p"),l.innerHTML="Requires superuser <code>Authorization:TOKEN</code> header",m(l,"class","txt-hint txt-sm txt-right")},m(s,n){f(s,l,n)},d(s){s&&p(l)}}}function $e(a,l){let s,n,h;function r(){return l[5](l[6])}return{key:a,first:null,c(){s=c("button"),s.textContent=`${l[6].code} `,m(s,"class","tab-item"),z(s,"active",l[2]===l[6].code),this.first=s},m(o,d){f(o,s,d),n||(h=Le(s,"click",r),n=!0)},p(o,d){l=o,d&20&&z(s,"active",l[2]===l[6].code)},d(o){o&&p(s),n=!1,h()}}}function ye(a,l){let s,n,h,r;return n=new Se({props:{content:l[6].body}}),{key:a,first:null,c(){s=c("div"),we(n.$$.fragment),h=k(),m(s,"class","tab-item"),z(s,"active",l[2]===l[6].code),this.first=s},m(o,d){f(o,s,d),Ce(n,s,null),i(s,h),r=!0},p(o,d){l=o,(!r||d&20)&&z(s,"active",l[2]===l[6].code)},i(o){r||(le(n.$$.fragment,o),r=!0)},o(o){te(n.$$.fragment,o),r=!1},d(o){o&&p(s),De(n)}}}function He(a){var fe,me;let l,s,n=a[0].name+"",h,r,o,d,y,D,F,q=a[0].name+"",J,se,K,C,N,P,V,g,L,ae,S,E,ne,W,H=a[0].name+"",X,oe,Z,ie,G,T,Q,B,Y,I,x,w,O,v=[],ce=new Map,re,A,b=[],de=new Map,R;C=new Te({props:{js:`
import PocketBase from 'pocketbase';
const pb = new PocketBase('${a[3]}');
@@ -1,4 +1,4 @@
import{S as se,i as oe,s as ie,X as K,h as g,t as X,a as V,I as F,Z as le,_ as Re,C as ne,$ as Se,D as ae,l as v,n as u,u as p,v as y,A as U,w as b,k as Y,o as ce,W as Oe,d as x,m as ee,c as te,V as Me,Y as _e,J as Be,p as De,a0 as be}from"./index-B8H52oF4.js";function ge(n,e,t){const l=n.slice();return l[4]=e[t],l}function ve(n,e,t){const l=n.slice();return l[4]=e[t],l}function ke(n,e){let t,l=e[4].code+"",d,i,r,a;function m(){return e[3](e[4])}return{key:n,first:null,c(){t=p("button"),d=U(l),i=y(),b(t,"class","tab-item"),Y(t,"active",e[1]===e[4].code),this.first=t},m(k,q){v(k,t,q),u(t,d),u(t,i),r||(a=ce(t,"click",m),r=!0)},p(k,q){e=k,q&4&&l!==(l=e[4].code+"")&&F(d,l),q&6&&Y(t,"active",e[1]===e[4].code)},d(k){k&&g(t),r=!1,a()}}}function $e(n,e){let t,l,d,i;return l=new Oe({props:{content:e[4].body}}),{key:n,first:null,c(){t=p("div"),te(l.$$.fragment),d=y(),b(t,"class","tab-item"),Y(t,"active",e[1]===e[4].code),this.first=t},m(r,a){v(r,t,a),ee(l,t,null),u(t,d),i=!0},p(r,a){e=r;const m={};a&4&&(m.content=e[4].body),l.$set(m),(!i||a&6)&&Y(t,"active",e[1]===e[4].code)},i(r){i||(V(l.$$.fragment,r),i=!0)},o(r){X(l.$$.fragment,r),i=!1},d(r){r&&g(t),x(l)}}}function Ne(n){let e,t,l,d,i,r,a,m=n[0].name+"",k,q,G,H,J,L,z,B,D,S,N,A=[],O=new Map,P,j,T=[],W=new Map,w,E=K(n[2]);const M=c=>c[4].code;for(let c=0;c<E.length;c+=1){let f=ve(n,E,c),s=M(f);O.set(s,A[c]=ke(s,f))}let _=K(n[2]);const Z=c=>c[4].code;for(let c=0;c<_.length;c+=1){let f=ge(n,_,c),s=Z(f);W.set(s,T[c]=$e(s,f))}return{c(){e=p("div"),t=p("strong"),t.textContent="POST",l=y(),d=p("div"),i=p("p"),r=U("/api/collections/"),a=p("strong"),k=U(m),q=U("/confirm-email-change"),G=y(),H=p("div"),H.textContent="Body Parameters",J=y(),L=p("table"),L.innerHTML='<thead><tr><th>Param</th> <th>Type</th> <th width="50%">Description</th></tr></thead> <tbody><tr><td><div class="inline-flex"><span class="label label-success">Required</span> <span>token</span></div></td> <td><span class="label">String</span></td> <td>The token from the change email request email.</td></tr> <tr><td><div class="inline-flex"><span class="label label-success">Required</span> <span>password</span></div></td> <td><span class="label">String</span></td> <td>The account password to confirm the email change.</td></tr></tbody>',z=y(),B=p("div"),B.textContent="Responses",D=y(),S=p("div"),N=p("div");for(let c=0;c<A.length;c+=1)A[c].c();P=y(),j=p("div");for(let c=0;c<T.length;c+=1)T[c].c();b(t,"class","label label-primary"),b(d,"class","content"),b(e,"class","alert alert-success"),b(H,"class","section-title"),b(L,"class","table-compact table-border m-b-base"),b(B,"class","section-title"),b(N,"class","tabs-header compact combined left"),b(j,"class","tabs-content"),b(S,"class","tabs")},m(c,f){v(c,e,f),u(e,t),u(e,l),u(e,d),u(d,i),u(i,r),u(i,a),u(a,k),u(i,q),v(c,G,f),v(c,H,f),v(c,J,f),v(c,L,f),v(c,z,f),v(c,B,f),v(c,D,f),v(c,S,f),u(S,N);for(let s=0;s<A.length;s+=1)A[s]&&A[s].m(N,null);u(S,P),u(S,j);for(let s=0;s<T.length;s+=1)T[s]&&T[s].m(j,null);w=!0},p(c,[f]){(!w||f&1)&&m!==(m=c[0].name+"")&&F(k,m),f&6&&(E=K(c[2]),A=le(A,f,M,1,c,E,O,N,Re,ke,null,ve)),f&6&&(_=K(c[2]),ne(),T=le(T,f,Z,1,c,_,W,j,Se,$e,null,ge),ae())},i(c){if(!w){for(let f=0;f<_.length;f+=1)V(T[f]);w=!0}},o(c){for(let f=0;f<T.length;f+=1)X(T[f]);w=!1},d(c){c&&(g(e),g(G),g(H),g(J),g(L),g(z),g(B),g(D),g(S));for(let f=0;f<A.length;f+=1)A[f].d();for(let f=0;f<T.length;f+=1)T[f].d()}}}function We(n,e,t){let{collection:l}=e,d=204,i=[];const r=a=>t(1,d=a.code);return n.$$set=a=>{"collection"in a&&t(0,l=a.collection)},t(2,i=[{code:204,body:"null"},{code:400,body:`
import{S as se,i as oe,s as ie,X as K,h as g,t as X,a as V,I as F,Z as le,_ as Re,C as ne,$ as Se,D as ae,l as v,n as u,u as p,v as y,A as U,w as b,k as Y,o as ce,W as Oe,d as x,m as ee,c as te,V as Me,Y as _e,J as Be,p as De,a0 as be}from"./index-Bkv3H6ZP.js";function ge(n,e,t){const l=n.slice();return l[4]=e[t],l}function ve(n,e,t){const l=n.slice();return l[4]=e[t],l}function ke(n,e){let t,l=e[4].code+"",d,i,r,a;function m(){return e[3](e[4])}return{key:n,first:null,c(){t=p("button"),d=U(l),i=y(),b(t,"class","tab-item"),Y(t,"active",e[1]===e[4].code),this.first=t},m(k,q){v(k,t,q),u(t,d),u(t,i),r||(a=ce(t,"click",m),r=!0)},p(k,q){e=k,q&4&&l!==(l=e[4].code+"")&&F(d,l),q&6&&Y(t,"active",e[1]===e[4].code)},d(k){k&&g(t),r=!1,a()}}}function $e(n,e){let t,l,d,i;return l=new Oe({props:{content:e[4].body}}),{key:n,first:null,c(){t=p("div"),te(l.$$.fragment),d=y(),b(t,"class","tab-item"),Y(t,"active",e[1]===e[4].code),this.first=t},m(r,a){v(r,t,a),ee(l,t,null),u(t,d),i=!0},p(r,a){e=r;const m={};a&4&&(m.content=e[4].body),l.$set(m),(!i||a&6)&&Y(t,"active",e[1]===e[4].code)},i(r){i||(V(l.$$.fragment,r),i=!0)},o(r){X(l.$$.fragment,r),i=!1},d(r){r&&g(t),x(l)}}}function Ne(n){let e,t,l,d,i,r,a,m=n[0].name+"",k,q,G,H,J,L,z,B,D,S,N,A=[],O=new Map,P,j,T=[],W=new Map,w,E=K(n[2]);const M=c=>c[4].code;for(let c=0;c<E.length;c+=1){let f=ve(n,E,c),s=M(f);O.set(s,A[c]=ke(s,f))}let _=K(n[2]);const Z=c=>c[4].code;for(let c=0;c<_.length;c+=1){let f=ge(n,_,c),s=Z(f);W.set(s,T[c]=$e(s,f))}return{c(){e=p("div"),t=p("strong"),t.textContent="POST",l=y(),d=p("div"),i=p("p"),r=U("/api/collections/"),a=p("strong"),k=U(m),q=U("/confirm-email-change"),G=y(),H=p("div"),H.textContent="Body Parameters",J=y(),L=p("table"),L.innerHTML='<thead><tr><th>Param</th> <th>Type</th> <th width="50%">Description</th></tr></thead> <tbody><tr><td><div class="inline-flex"><span class="label label-success">Required</span> <span>token</span></div></td> <td><span class="label">String</span></td> <td>The token from the change email request email.</td></tr> <tr><td><div class="inline-flex"><span class="label label-success">Required</span> <span>password</span></div></td> <td><span class="label">String</span></td> <td>The account password to confirm the email change.</td></tr></tbody>',z=y(),B=p("div"),B.textContent="Responses",D=y(),S=p("div"),N=p("div");for(let c=0;c<A.length;c+=1)A[c].c();P=y(),j=p("div");for(let c=0;c<T.length;c+=1)T[c].c();b(t,"class","label label-primary"),b(d,"class","content"),b(e,"class","alert alert-success"),b(H,"class","section-title"),b(L,"class","table-compact table-border m-b-base"),b(B,"class","section-title"),b(N,"class","tabs-header compact combined left"),b(j,"class","tabs-content"),b(S,"class","tabs")},m(c,f){v(c,e,f),u(e,t),u(e,l),u(e,d),u(d,i),u(i,r),u(i,a),u(a,k),u(i,q),v(c,G,f),v(c,H,f),v(c,J,f),v(c,L,f),v(c,z,f),v(c,B,f),v(c,D,f),v(c,S,f),u(S,N);for(let s=0;s<A.length;s+=1)A[s]&&A[s].m(N,null);u(S,P),u(S,j);for(let s=0;s<T.length;s+=1)T[s]&&T[s].m(j,null);w=!0},p(c,[f]){(!w||f&1)&&m!==(m=c[0].name+"")&&F(k,m),f&6&&(E=K(c[2]),A=le(A,f,M,1,c,E,O,N,Re,ke,null,ve)),f&6&&(_=K(c[2]),ne(),T=le(T,f,Z,1,c,_,W,j,Se,$e,null,ge),ae())},i(c){if(!w){for(let f=0;f<_.length;f+=1)V(T[f]);w=!0}},o(c){for(let f=0;f<T.length;f+=1)X(T[f]);w=!1},d(c){c&&(g(e),g(G),g(H),g(J),g(L),g(z),g(B),g(D),g(S));for(let f=0;f<A.length;f+=1)A[f].d();for(let f=0;f<T.length;f+=1)T[f].d()}}}function We(n,e,t){let{collection:l}=e,d=204,i=[];const r=a=>t(1,d=a.code);return n.$$set=a=>{"collection"in a&&t(0,l=a.collection)},t(2,i=[{code:204,body:"null"},{code:400,body:`
{
"status": 400,
"message": "An error occurred while validating the submitted data.",
@@ -1,4 +1,4 @@
import{S as J,i as N,s as O,W as P,h as Q,d as R,t as W,a as j,I as z,l as D,n as e,m as G,u as t,v as c,A as i,c as K,w as U}from"./index-B8H52oF4.js";function V(f){let n,o,u,d,k,s,p,w,g,y,r,F,_,S,b,E,C,a,$,L,q,H,I,M,m,T,v,A,x;return r=new P({props:{content:"?fields=*,"+f[0]+"expand.relField.name"}}),{c(){n=t("tr"),o=t("td"),o.textContent="fields",u=c(),d=t("td"),d.innerHTML='<span class="label">String</span>',k=c(),s=t("td"),p=t("p"),w=i(`Comma separated string of the fields to return in the JSON response
import{S as J,i as N,s as O,W as P,h as Q,d as R,t as W,a as j,I as z,l as D,n as e,m as G,u as t,v as c,A as i,c as K,w as U}from"./index-Bkv3H6ZP.js";function V(f){let n,o,u,d,k,s,p,w,g,y,r,F,_,S,b,E,C,a,$,L,q,H,I,M,m,T,v,A,x;return r=new P({props:{content:"?fields=*,"+f[0]+"expand.relField.name"}}),{c(){n=t("tr"),o=t("td"),o.textContent="fields",u=c(),d=t("td"),d.innerHTML='<span class="label">String</span>',k=c(),s=t("td"),p=t("p"),w=i(`Comma separated string of the fields to return in the JSON response
`),g=t("em"),g.textContent="(by default returns all fields)",y=i(`. Ex.:
`),K(r.$$.fragment),F=c(),_=t("p"),_.innerHTML="<code>*</code> targets all keys from the specific depth level.",S=c(),b=t("p"),b.textContent="In addition, the following field modifiers are also supported:",E=c(),C=t("ul"),a=t("li"),$=t("code"),$.textContent=":excerpt(maxLength, withEllipsis?)",L=c(),q=t("br"),H=i(`
Returns a short plain text version of the field string value.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,4 +1,4 @@
import{S as el,i as ll,s as sl,H as ze,h as m,l as h,o as nl,u as e,v as s,L as ol,w as a,n as t,A as g,V as al,W as Le,X as ae,d as Kt,Y as il,t as Ct,a as kt,I as ve,Z as Je,_ as rl,C as cl,$ as dl,D as pl,m as Qt,c as Vt,J as Te,p as fl,k as Ae}from"./index-B8H52oF4.js";import{F as ul}from"./FieldsQueryParam-hUu_nMS2.js";function ml(r){let n,o,i;return{c(){n=e("span"),n.textContent="Show details",o=s(),i=e("i"),a(n,"class","txt"),a(i,"class","ri-arrow-down-s-line")},m(f,b){h(f,n,b),h(f,o,b),h(f,i,b)},d(f){f&&(m(n),m(o),m(i))}}}function hl(r){let n,o,i;return{c(){n=e("span"),n.textContent="Hide details",o=s(),i=e("i"),a(n,"class","txt"),a(i,"class","ri-arrow-up-s-line")},m(f,b){h(f,n,b),h(f,o,b),h(f,i,b)},d(f){f&&(m(n),m(o),m(i))}}}function Ke(r){let n,o,i,f,b,p,u,C,_,x,d,Y,yt,Wt,E,Xt,D,it,P,Z,ie,j,U,re,rt,vt,tt,Ft,ce,ct,dt,et,N,Yt,Lt,k,lt,At,Zt,Tt,z,st,Pt,te,Rt,v,pt,Ot,de,ft,pe,H,St,nt,Et,F,ut,fe,J,Nt,ee,qt,le,Dt,ue,L,mt,me,ht,he,M,be,T,Ht,ot,Mt,K,bt,ge,I,It,y,Bt,at,Gt,_e,Q,gt,we,_t,xe,jt,$e,B,Ut,Ce,G,ke,wt,se,R,xt,V,W,O,zt,ne,X;return{c(){n=e("p"),n.innerHTML=`The syntax basically follows the format
import{S as el,i as ll,s as sl,H as ze,h as m,l as h,o as nl,u as e,v as s,L as ol,w as a,n as t,A as g,V as al,W as Le,X as ae,d as Kt,Y as il,t as Ct,a as kt,I as ve,Z as Je,_ as rl,C as cl,$ as dl,D as pl,m as Qt,c as Vt,J as Te,p as fl,k as Ae}from"./index-Bkv3H6ZP.js";import{F as ul}from"./FieldsQueryParam-Y2XYzYJh.js";function ml(r){let n,o,i;return{c(){n=e("span"),n.textContent="Show details",o=s(),i=e("i"),a(n,"class","txt"),a(i,"class","ri-arrow-down-s-line")},m(f,b){h(f,n,b),h(f,o,b),h(f,i,b)},d(f){f&&(m(n),m(o),m(i))}}}function hl(r){let n,o,i;return{c(){n=e("span"),n.textContent="Hide details",o=s(),i=e("i"),a(n,"class","txt"),a(i,"class","ri-arrow-up-s-line")},m(f,b){h(f,n,b),h(f,o,b),h(f,i,b)},d(f){f&&(m(n),m(o),m(i))}}}function Ke(r){let n,o,i,f,b,p,u,C,_,x,d,Y,yt,Wt,E,Xt,D,it,P,Z,ie,j,U,re,rt,vt,tt,Ft,ce,ct,dt,et,N,Yt,Lt,k,lt,At,Zt,Tt,z,st,Pt,te,Rt,v,pt,Ot,de,ft,pe,H,St,nt,Et,F,ut,fe,J,Nt,ee,qt,le,Dt,ue,L,mt,me,ht,he,M,be,T,Ht,ot,Mt,K,bt,ge,I,It,y,Bt,at,Gt,_e,Q,gt,we,_t,xe,jt,$e,B,Ut,Ce,G,ke,wt,se,R,xt,V,W,O,zt,ne,X;return{c(){n=e("p"),n.innerHTML=`The syntax basically follows the format
<code><span class="txt-success">OPERAND</span> <span class="txt-danger">OPERATOR</span> <span class="txt-success">OPERAND</span></code>, where:`,o=s(),i=e("ul"),f=e("li"),f.innerHTML=`<code class="txt-success">OPERAND</code> - could be any of the above field literal, string (single
or double quoted), number, null, true, false`,b=s(),p=e("li"),u=e("code"),u.textContent="OPERATOR",C=g(` - is one of:
`),_=e("br"),x=s(),d=e("ul"),Y=e("li"),yt=e("code"),yt.textContent="=",Wt=s(),E=e("span"),E.textContent="Equal",Xt=s(),D=e("li"),it=e("code"),it.textContent="!=",P=s(),Z=e("span"),Z.textContent="NOT equal",ie=s(),j=e("li"),U=e("code"),U.textContent=">",re=s(),rt=e("span"),rt.textContent="Greater than",vt=s(),tt=e("li"),Ft=e("code"),Ft.textContent=">=",ce=s(),ct=e("span"),ct.textContent="Greater than or equal",dt=s(),et=e("li"),N=e("code"),N.textContent="<",Yt=s(),Lt=e("span"),Lt.textContent="Less than",k=s(),lt=e("li"),At=e("code"),At.textContent="<=",Zt=s(),Tt=e("span"),Tt.textContent="Less than or equal",z=s(),st=e("li"),Pt=e("code"),Pt.textContent="~",te=s(),Rt=e("span"),Rt.textContent=`Like/Contains (if not specified auto wraps the right string OPERAND in a "%" for
File diff suppressed because one or more lines are too long
@@ -1 +1 @@
import{S as r,i as c,s as l,H as n,h as u,l as h,u as p,w as d,O as f,P as m,Q as g,R as o}from"./index-B8H52oF4.js";function _(s){let t;return{c(){t=p("div"),t.innerHTML='<h3 class="m-b-sm">Auth failed.</h3> <h5>You can close this window and go back to the app to try again.</h5>',d(t,"class","content txt-hint txt-center p-base")},m(e,a){h(e,t,a)},p:n,i:n,o:n,d(e){e&&u(t)}}}function b(s,t,e){let a;return f(s,o,i=>e(0,a=i)),m(o,a="OAuth2 auth failed",a),g(()=>{window.close()}),[]}class x extends r{constructor(t){super(),c(this,t,b,_,l,{})}}export{x as default};
import{S as r,i as c,s as l,H as n,h as u,l as h,u as p,w as d,O as f,P as m,Q as g,R as o}from"./index-Bkv3H6ZP.js";function _(s){let t;return{c(){t=p("div"),t.innerHTML='<h3 class="m-b-sm">Auth failed.</h3> <h5>You can close this window and go back to the app to try again.</h5>',d(t,"class","content txt-hint txt-center p-base")},m(e,a){h(e,t,a)},p:n,i:n,o:n,d(e){e&&u(t)}}}function b(s,t,e){let a;return f(s,o,i=>e(0,a=i)),m(o,a="OAuth2 auth failed",a),g(()=>{window.close()}),[]}class x extends r{constructor(t){super(),c(this,t,b,_,l,{})}}export{x as default};
@@ -1 +1 @@
import{S as i,i as r,s as u,H as n,h as l,l as p,u as h,w as d,O as m,P as f,Q as _,R as o}from"./index-B8H52oF4.js";function b(a){let t;return{c(){t=h("div"),t.innerHTML='<h3 class="m-b-sm">Auth completed.</h3> <h5>You can close this window and go back to the app.</h5>',d(t,"class","content txt-hint txt-center p-base")},m(e,s){p(e,t,s)},p:n,i:n,o:n,d(e){e&&l(t)}}}function g(a,t,e){let s;return m(a,o,c=>e(0,s=c)),f(o,s="OAuth2 auth completed",s),_(()=>{window.close()}),[]}class x extends i{constructor(t){super(),r(this,t,g,b,u,{})}}export{x as default};
import{S as i,i as r,s as u,H as n,h as l,l as p,u as h,w as d,O as m,P as f,Q as _,R as o}from"./index-Bkv3H6ZP.js";function b(a){let t;return{c(){t=h("div"),t.innerHTML='<h3 class="m-b-sm">Auth completed.</h3> <h5>You can close this window and go back to the app.</h5>',d(t,"class","content txt-hint txt-center p-base")},m(e,s){p(e,t,s)},p:n,i:n,o:n,d(e){e&&l(t)}}}function g(a,t,e){let s;return m(a,o,c=>e(0,s=c)),f(o,s="OAuth2 auth completed",s),_(()=>{window.close()}),[]}class x extends i{constructor(t){super(),r(this,t,g,b,u,{})}}export{x as default};
@@ -1,2 +1,2 @@
import{S as J,i as M,s as z,F as A,d as L,t as h,a as v,m as S,c as I,J as D,h as _,D as N,l as b,L as R,M as W,g as Y,p as j,H as P,o as q,u as m,v as y,w as p,f as B,k as T,n as g,q as G,A as C,I as K,z as F,C as O}from"./index-B8H52oF4.js";function Q(i){let e,t,n,l,s,o,f,a,r,u,k,$,d=i[3]&&H(i);return o=new B({props:{class:"form-field required",name:"password",$$slots:{default:[V,({uniqueId:c})=>({8:c}),({uniqueId:c})=>c?256:0]},$$scope:{ctx:i}}}),{c(){e=m("form"),t=m("div"),n=m("h5"),l=C(`Type your password to confirm changing your email address
import{S as J,i as M,s as z,F as A,d as L,t as h,a as v,m as S,c as I,J as D,h as _,D as N,l as b,L as R,M as W,g as Y,p as j,H as P,o as q,u as m,v as y,w as p,f as B,k as T,n as g,q as G,A as C,I as K,z as F,C as O}from"./index-Bkv3H6ZP.js";function Q(i){let e,t,n,l,s,o,f,a,r,u,k,$,d=i[3]&&H(i);return o=new B({props:{class:"form-field required",name:"password",$$slots:{default:[V,({uniqueId:c})=>({8:c}),({uniqueId:c})=>c?256:0]},$$scope:{ctx:i}}}),{c(){e=m("form"),t=m("div"),n=m("h5"),l=C(`Type your password to confirm changing your email address
`),d&&d.c(),s=y(),I(o.$$.fragment),f=y(),a=m("button"),r=m("span"),r.textContent="Confirm new email",p(t,"class","content txt-center m-b-base"),p(r,"class","txt"),p(a,"type","submit"),p(a,"class","btn btn-lg btn-block"),a.disabled=i[1],T(a,"btn-loading",i[1])},m(c,w){b(c,e,w),g(e,t),g(t,n),g(n,l),d&&d.m(n,null),g(e,s),S(o,e,null),g(e,f),g(e,a),g(a,r),u=!0,k||($=q(e,"submit",G(i[4])),k=!0)},p(c,w){c[3]?d?d.p(c,w):(d=H(c),d.c(),d.m(n,null)):d&&(d.d(1),d=null);const E={};w&769&&(E.$$scope={dirty:w,ctx:c}),o.$set(E),(!u||w&2)&&(a.disabled=c[1]),(!u||w&2)&&T(a,"btn-loading",c[1])},i(c){u||(v(o.$$.fragment,c),u=!0)},o(c){h(o.$$.fragment,c),u=!1},d(c){c&&_(e),d&&d.d(),L(o),k=!1,$()}}}function U(i){let e,t,n,l,s;return{c(){e=m("div"),e.innerHTML='<div class="icon"><i class="ri-checkbox-circle-line"></i></div> <div class="content txt-bold"><p>Successfully changed the user email address.</p> <p>You can now sign in with your new email address.</p></div>',t=y(),n=m("button"),n.textContent="Close",p(e,"class","alert alert-success"),p(n,"type","button"),p(n,"class","btn btn-transparent btn-block")},m(o,f){b(o,e,f),b(o,t,f),b(o,n,f),l||(s=q(n,"click",i[6]),l=!0)},p:P,i:P,o:P,d(o){o&&(_(e),_(t),_(n)),l=!1,s()}}}function H(i){let e,t,n;return{c(){e=C("to "),t=m("strong"),n=C(i[3]),p(t,"class","txt-nowrap")},m(l,s){b(l,e,s),b(l,t,s),g(t,n)},p(l,s){s&8&&K(n,l[3])},d(l){l&&(_(e),_(t))}}}function V(i){let e,t,n,l,s,o,f,a;return{c(){e=m("label"),t=C("Password"),l=y(),s=m("input"),p(e,"for",n=i[8]),p(s,"type","password"),p(s,"id",o=i[8]),s.required=!0,s.autofocus=!0},m(r,u){b(r,e,u),g(e,t),b(r,l,u),b(r,s,u),F(s,i[0]),s.focus(),f||(a=q(s,"input",i[7]),f=!0)},p(r,u){u&256&&n!==(n=r[8])&&p(e,"for",n),u&256&&o!==(o=r[8])&&p(s,"id",o),u&1&&s.value!==r[0]&&F(s,r[0])},d(r){r&&(_(e),_(l),_(s)),f=!1,a()}}}function X(i){let e,t,n,l;const s=[U,Q],o=[];function f(a,r){return a[2]?0:1}return e=f(i),t=o[e]=s[e](i),{c(){t.c(),n=R()},m(a,r){o[e].m(a,r),b(a,n,r),l=!0},p(a,r){let u=e;e=f(a),e===u?o[e].p(a,r):(O(),h(o[u],1,1,()=>{o[u]=null}),N(),t=o[e],t?t.p(a,r):(t=o[e]=s[e](a),t.c()),v(t,1),t.m(n.parentNode,n))},i(a){l||(v(t),l=!0)},o(a){h(t),l=!1},d(a){a&&_(n),o[e].d(a)}}}function Z(i){let e,t;return e=new A({props:{nobranding:!0,$$slots:{default:[X]},$$scope:{ctx:i}}}),{c(){I(e.$$.fragment)},m(n,l){S(e,n,l),t=!0},p(n,[l]){const s={};l&527&&(s.$$scope={dirty:l,ctx:n}),e.$set(s)},i(n){t||(v(e.$$.fragment,n),t=!0)},o(n){h(e.$$.fragment,n),t=!1},d(n){L(e,n)}}}function x(i,e,t){let n,{params:l}=e,s="",o=!1,f=!1;async function a(){if(o)return;t(1,o=!0);const k=new W("../");try{const $=Y(l==null?void 0:l.token);await k.collection($.collectionId).confirmEmailChange(l==null?void 0:l.token,s),t(2,f=!0)}catch($){j.error($)}t(1,o=!1)}const r=()=>window.close();function u(){s=this.value,t(0,s)}return i.$$set=k=>{"params"in k&&t(5,l=k.params)},i.$$.update=()=>{i.$$.dirty&32&&t(3,n=D.getJWTPayload(l==null?void 0:l.token).newEmail||"")},[s,o,f,n,a,l,r,u]}class te extends J{constructor(e){super(),M(this,e,x,Z,z,{params:5})}}export{te as default};
@@ -1,2 +1,2 @@
import{S as A,i as D,s as W,F as Y,d as H,t as P,a as q,m as L,c as N,J as j,h as _,C as B,D as E,l as m,L as G,M as K,g as O,p as Q,H as F,o as S,u as b,v as C,w as p,f as J,k as M,n as w,q as U,A as y,I as V,z as R}from"./index-B8H52oF4.js";function X(a){let e,l,s,n,t,o,c,r,i,u,v,g,k,h,d=a[4]&&z(a);return o=new J({props:{class:"form-field required",name:"password",$$slots:{default:[x,({uniqueId:f})=>({10:f}),({uniqueId:f})=>f?1024:0]},$$scope:{ctx:a}}}),r=new J({props:{class:"form-field required",name:"passwordConfirm",$$slots:{default:[ee,({uniqueId:f})=>({10:f}),({uniqueId:f})=>f?1024:0]},$$scope:{ctx:a}}}),{c(){e=b("form"),l=b("div"),s=b("h5"),n=y(`Reset your user password
import{S as A,i as D,s as W,F as Y,d as H,t as P,a as q,m as L,c as N,J as j,h as _,C as B,D as E,l as m,L as G,M as K,g as O,p as Q,H as F,o as S,u as b,v as C,w as p,f as J,k as M,n as w,q as U,A as y,I as V,z as R}from"./index-Bkv3H6ZP.js";function X(a){let e,l,s,n,t,o,c,r,i,u,v,g,k,h,d=a[4]&&z(a);return o=new J({props:{class:"form-field required",name:"password",$$slots:{default:[x,({uniqueId:f})=>({10:f}),({uniqueId:f})=>f?1024:0]},$$scope:{ctx:a}}}),r=new J({props:{class:"form-field required",name:"passwordConfirm",$$slots:{default:[ee,({uniqueId:f})=>({10:f}),({uniqueId:f})=>f?1024:0]},$$scope:{ctx:a}}}),{c(){e=b("form"),l=b("div"),s=b("h5"),n=y(`Reset your user password
`),d&&d.c(),t=C(),N(o.$$.fragment),c=C(),N(r.$$.fragment),i=C(),u=b("button"),v=b("span"),v.textContent="Set new password",p(l,"class","content txt-center m-b-base"),p(v,"class","txt"),p(u,"type","submit"),p(u,"class","btn btn-lg btn-block"),u.disabled=a[2],M(u,"btn-loading",a[2])},m(f,$){m(f,e,$),w(e,l),w(l,s),w(s,n),d&&d.m(s,null),w(e,t),L(o,e,null),w(e,c),L(r,e,null),w(e,i),w(e,u),w(u,v),g=!0,k||(h=S(e,"submit",U(a[5])),k=!0)},p(f,$){f[4]?d?d.p(f,$):(d=z(f),d.c(),d.m(s,null)):d&&(d.d(1),d=null);const T={};$&3073&&(T.$$scope={dirty:$,ctx:f}),o.$set(T);const I={};$&3074&&(I.$$scope={dirty:$,ctx:f}),r.$set(I),(!g||$&4)&&(u.disabled=f[2]),(!g||$&4)&&M(u,"btn-loading",f[2])},i(f){g||(q(o.$$.fragment,f),q(r.$$.fragment,f),g=!0)},o(f){P(o.$$.fragment,f),P(r.$$.fragment,f),g=!1},d(f){f&&_(e),d&&d.d(),H(o),H(r),k=!1,h()}}}function Z(a){let e,l,s,n,t;return{c(){e=b("div"),e.innerHTML='<div class="icon"><i class="ri-checkbox-circle-line"></i></div> <div class="content txt-bold"><p>Successfully changed the user password.</p> <p>You can now sign in with your new password.</p></div>',l=C(),s=b("button"),s.textContent="Close",p(e,"class","alert alert-success"),p(s,"type","button"),p(s,"class","btn btn-transparent btn-block")},m(o,c){m(o,e,c),m(o,l,c),m(o,s,c),n||(t=S(s,"click",a[7]),n=!0)},p:F,i:F,o:F,d(o){o&&(_(e),_(l),_(s)),n=!1,t()}}}function z(a){let e,l,s;return{c(){e=y("for "),l=b("strong"),s=y(a[4])},m(n,t){m(n,e,t),m(n,l,t),w(l,s)},p(n,t){t&16&&V(s,n[4])},d(n){n&&(_(e),_(l))}}}function x(a){let e,l,s,n,t,o,c,r;return{c(){e=b("label"),l=y("New password"),n=C(),t=b("input"),p(e,"for",s=a[10]),p(t,"type","password"),p(t,"id",o=a[10]),t.required=!0,t.autofocus=!0},m(i,u){m(i,e,u),w(e,l),m(i,n,u),m(i,t,u),R(t,a[0]),t.focus(),c||(r=S(t,"input",a[8]),c=!0)},p(i,u){u&1024&&s!==(s=i[10])&&p(e,"for",s),u&1024&&o!==(o=i[10])&&p(t,"id",o),u&1&&t.value!==i[0]&&R(t,i[0])},d(i){i&&(_(e),_(n),_(t)),c=!1,r()}}}function ee(a){let e,l,s,n,t,o,c,r;return{c(){e=b("label"),l=y("New password confirm"),n=C(),t=b("input"),p(e,"for",s=a[10]),p(t,"type","password"),p(t,"id",o=a[10]),t.required=!0},m(i,u){m(i,e,u),w(e,l),m(i,n,u),m(i,t,u),R(t,a[1]),c||(r=S(t,"input",a[9]),c=!0)},p(i,u){u&1024&&s!==(s=i[10])&&p(e,"for",s),u&1024&&o!==(o=i[10])&&p(t,"id",o),u&2&&t.value!==i[1]&&R(t,i[1])},d(i){i&&(_(e),_(n),_(t)),c=!1,r()}}}function te(a){let e,l,s,n;const t=[Z,X],o=[];function c(r,i){return r[3]?0:1}return e=c(a),l=o[e]=t[e](a),{c(){l.c(),s=G()},m(r,i){o[e].m(r,i),m(r,s,i),n=!0},p(r,i){let u=e;e=c(r),e===u?o[e].p(r,i):(B(),P(o[u],1,1,()=>{o[u]=null}),E(),l=o[e],l?l.p(r,i):(l=o[e]=t[e](r),l.c()),q(l,1),l.m(s.parentNode,s))},i(r){n||(q(l),n=!0)},o(r){P(l),n=!1},d(r){r&&_(s),o[e].d(r)}}}function se(a){let e,l;return e=new Y({props:{nobranding:!0,$$slots:{default:[te]},$$scope:{ctx:a}}}),{c(){N(e.$$.fragment)},m(s,n){L(e,s,n),l=!0},p(s,[n]){const t={};n&2079&&(t.$$scope={dirty:n,ctx:s}),e.$set(t)},i(s){l||(q(e.$$.fragment,s),l=!0)},o(s){P(e.$$.fragment,s),l=!1},d(s){H(e,s)}}}function le(a,e,l){let s,{params:n}=e,t="",o="",c=!1,r=!1;async function i(){if(c)return;l(2,c=!0);const k=new K("../");try{const h=O(n==null?void 0:n.token);await k.collection(h.collectionId).confirmPasswordReset(n==null?void 0:n.token,t,o),l(3,r=!0)}catch(h){Q.error(h)}l(2,c=!1)}const u=()=>window.close();function v(){t=this.value,l(0,t)}function g(){o=this.value,l(1,o)}return a.$$set=k=>{"params"in k&&l(6,n=k.params)},a.$$.update=()=>{a.$$.dirty&64&&l(4,s=j.getJWTPayload(n==null?void 0:n.token).email||"")},[t,o,c,r,s,i,n,u,v,g]}class oe extends A{constructor(e){super(),D(this,e,le,se,W,{params:6})}}export{oe as default};

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