Compare commits

..
Author SHA1 Message Date
loks0nandClaude Sonnet 4.6 4a43969da9 fix: use consistent dot notation for all storage span attribute names
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 19:53:20 +01:00
loks0nandClaude Sonnet 4.6 6fa4122910 fix: rename storage span attributes to use dot notation for ids
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 19:52:25 +01:00
loks0nandClaude Sonnet 4.6 1d27101770 feat: add tracing spans for storage file preview timing and cache state
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 19:49:57 +01:00
Luke B. SilverandGitHub 9214decc8d Merge pull request #11843 from appwrite/fix/session-mails
fix: set project on mail queue in session mails listener
2026-04-09 18:30:24 +01:00
loks0nandClaude Sonnet 4.6 ee4ae3bd47 fix: set project on mail queue in session mails listener
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 18:26:07 +01:00
Luke B. SilverandGitHub 53a114e7e4 Merge pull request #11842 from appwrite/fix/storage-cache
fix: storage preview cache misses and stale cache eviction
2026-04-09 17:27:27 +01:00
loks0nandClaude Sonnet 4.6 f2df9cb93a fix: storage preview cache misses and stale cache eviction
Three bugs causing storage preview cache to be ineffective:

1. Cache keys included the `token` auth parameter, so requests using
   resource tokens always generated unique keys and never hit cache.
   Introduced `cache.params` label for routes to opt-in specific params
   into the cache key; preview now declares only the transform params.

2. Cache hits never refreshed `accessedAt` in the DB or the filesystem
   file mtime, because `$response->send()` in the init hook skips the
   shutdown hook. After 30 days the maintenance job evicted still-active
   cache entries, and after the original 30-day filesystem TTL the cache
   file expired — causing periodic full re-renders. The cache-hit path
   now updates both on the APP_CACHE_UPDATE (24h) interval.

3. `updateDocument` in the preview action passed the full file document
   instead of a sparse one when updating `transformedAt`.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 17:05:14 +01:00
Luke B. SilverandGitHub f371237fd5 Merge pull request #11642 from appwrite/feat/mails-listener
feat: extract session alert email into Mails listener
2026-04-09 15:29:16 +01:00
Harsh MahajanandGitHub 9548d18a3e Merge pull request #11838 from appwrite/ix-missing-worker-executions-template
fix(installer): add missing worker-executions service to compose template
2026-04-09 19:06:42 +05:30
Harsh MahajanandGitHub 7928175387 Merge branch '1.9.x' into ix-missing-worker-executions-template 2026-04-09 18:53:39 +05:30
loks0nandClaude Sonnet 4.6 dd29967e99 refactor: tighten Mails listener with guard clauses and lean event
- SessionCreated event now carries only domain data (no isFirstSession)
- Mails listener uses ordered guard clauses, deferring the DB query
  until cheaper checks pass
- Drop $user Document allocation in favour of direct array access
- Inline FileName validator and $smtpEnabled into their use sites
- Extract $isBranded to eliminate duplicate APP_BRANDED_EMAIL_BASE_TEMPLATE check

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:01:13 +01:00
loks0nandClaude Sonnet 4.6 e7f5ae9306 fix: remove stale @param platform from SessionCreated docblock
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:01:13 +01:00
loks0nandClaude Sonnet 4.6 4133ec99ae feat: extract session alert email into Mails listener
Moves session alert email side effect out of the account controller
into a dedicated `Mails` listener that reacts to a new `SessionCreated`
bus event. The event is now always dispatched on session creation; the
listener owns all conditional logic (first session, sessionAlerts flag,
email-link sessions, user email presence).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:01:13 +01:00
Matej BačoandGitHub 6dd63ee152 Merge pull request #11655 from appwrite/copilot/add-test-for-deleting-partially-uploaded-file
Fix deletion of partially-uploaded (pending) files
2026-04-09 14:58:57 +02:00
Harsh MahajanandGitHub 386fc995e6 Update compose.phtml 2026-04-09 17:36:07 +05:30
Matej Bačo d6451b8fad Merge branch '1.9.x' into copilot/add-test-for-deleting-partially-uploaded-file 2026-04-09 14:02:06 +02:00
Harsh MahajanGitHubgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
ff9334ab78 Update app/views/install/compose.phtml
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-04-09 17:20:55 +05:30
Harsh MahajanandGitHub c494e96f79 Merge branch '1.9.x' into ix-missing-worker-executions-template 2026-04-09 17:18:22 +05:30
harsh mahajan fd78f0f7df fix(installer): add missing worker-executions service to compose template 2026-04-09 17:13:54 +05:30
Chirag AggarwalandGitHub 4ff10dcacc Merge pull request #11837 from appwrite/fix-11795-revert-project-variableid
Revert "fix: make variableId optional in createProjectVariable endpoint"
2026-04-09 16:53:10 +05:30
Chirag Aggarwal 7a995fe759 Revert "Merge pull request #11795 from rathi-yash/fix-11765-global-variable-creation"
This reverts commit 597b20a6cb, reversing
changes made to 20f80ac067.
2026-04-09 16:25:59 +05:30
Damodar LohaniandGitHub 227606baef Merge pull request #11835 from appwrite/fix/map-deprecated-platform-types-in-project-response
fix: map deprecated platform types in project response
2026-04-09 14:23:31 +05:45
Damodar LohaniandClaude Opus 4.6 f315e759f3 fix: map deprecated platform types in subQueryPlatforms filter
The subQueryPlatforms database filter loads platforms as a sub-attribute
when project documents are fetched. Old platform type values stored in
the database (e.g. flutter-android, flutter-ios) were not being mapped
to the new consolidated types before being included in the project
response sent to the frontend/console.

This adds Platform::mapDeprecatedType() to the filter so all platforms
returned as part of a project document have their types mapped
consistently, complementing the existing mapping in the dedicated
platform Get and List endpoints.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 08:31:39 +00:00
Damodar LohaniandGitHub 8a6fba75a5 Merge pull request #11833 from appwrite/fix/deprecated-platform-origin-validation
fix: Add backwards-compat origin validation for deprecated platform types
2026-04-09 13:41:30 +05:45
Damodar LohaniandClaude Opus 4.6 196c76ac70 fix: map deprecated platform types in read endpoints for backwards compatibility
Old platform types stored in the database (e.g. flutter-web, apple-ios,
react-native-android) are now mapped to the new consolidated types (web,
apple, android, windows, linux) before being sent in API responses. This
ensures the response models' $conditions correctly select the right model
for each platform document.

Adds Platform::mapDeprecatedType() as a reusable static method and applies
the mapping in both Get and XList platform endpoints.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 07:47:42 +00:00
Damodar LohaniandClaude Opus 4.6 7f82484436 remove migration changes from V24.php
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 07:36:58 +00:00
Damodar LohaniandClaude Opus 4.6 db18caf739 fix: add backwards-compatible origin validation for deprecated platform types
Platform::getHostnames() and Platform::getSchemes() only handled the new
consolidated type names, causing "invalid origin" errors for projects still
using old granular types (flutter-*, apple-*, react-native-*, unity) stored
in the database. Add switch fall-through cases for all deprecated type values
and a V24 migration to convert old types to their new equivalents.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 07:31:58 +00:00
Chirag AggarwalandGitHub 6693e28c93 Merge pull request #11830 from appwrite/feat/specs-task-no-http
remove HTTP server bootstrap from specs task
2026-04-09 11:46:37 +05:30
Chirag Aggarwal eec72a915a inline specs container setup 2026-04-09 10:45:24 +05:30
Chirag Aggarwal ae29e4c424 drop specs task format test 2026-04-09 10:43:39 +05:30
Chirag Aggarwal 05dc264df9 remove specs task HTTP bootstrap 2026-04-09 10:41:04 +05:30
Chirag AggarwalandGitHub 597b20a6cb Merge pull request #11795 from rathi-yash/fix-11765-global-variable-creation
fix: make variableId optional in createProjectVariable endpoint
2026-04-09 09:34:39 +05:30
Chirag AggarwalandGitHub 6b7d9853f9 Merge branch '1.9.x' into fix-11765-global-variable-creation 2026-04-09 09:24:52 +05:30
Damodar LohaniandGitHub 20f80ac067 Merge pull request #11580 from appwrite/feat-audit-user-type-distinction
feat: distinguish user types in audit logs
2026-04-09 06:55:43 +05:45
My Name 8bfa659120 test: add test case for createProjectVariable without variableId 2026-04-08 15:18:13 -04:00
Yash RathiandGitHub 65e44d76a1 Merge branch '1.9.x' into fix-11765-global-variable-creation 2026-04-08 14:50:58 -04:00
Jake BarnbyandGitHub bb07808661 Merge pull request #11820 from appwrite/fix-ttl-message 2026-04-09 03:39:48 +12:00
Luke B. SilverandGitHub d18550ff54 Merge pull request #11826 from appwrite/fix/cookie-test-hack
fix: use cURL cookie engine for RFC 6265 compliant cookie handling in e2e client
2026-04-08 16:17:04 +01:00
loks0nandClaude Sonnet 4.6 84dc921d41 fix: replace utopia-php/framework with http, fix RFC 6265 cookie handling
utopia-php/framework was the old name for utopia-php/http. Replacing it
with utopia-php/http 0.34.19 which fixes getCookie() to use Swoole's
native cookie store (populated via php_raw_url_decode) instead of
re-parsing the raw Cookie header without URL-decoding.

This fixes a production auth bug where Swoole's setcookie() URL-encodes
base64 session values (+ → %2B, / → %2F, = → %3D) in Set-Cookie headers.
RFC 6265 clients (Dart, Swift) reflect these verbatim; the old getCookie()
returned %2B/%2F/%3D to base64_decode() which produced corrupted output,
rejecting valid sessions.

Also updates the e2e test client to use cURL's built-in RFC 6265 cookie
engine (CURLOPT_COOKIEFILE) instead of parse_str() which silently
URL-decoded values, masking the bug in tests. Adds a cookie roundtrip
assertion to testCreateAccountSession.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 15:07:46 +01:00
loks0nandClaude Sonnet 4.6 e2d7dd837d fix: use cURL cookie engine instead of parse_str for RFC 6265 compliance
parse_str() URL-decodes cookie values, causing the test client to behave
differently from real clients (Dart, Swift) which store values verbatim
per RFC 6265. This masked a production bug where base64 session values
containing %3D%3D would fail to decode on real devices.

Replaces the manual Set-Cookie header parsing with cURL's built-in cookie
engine (CURLOPT_COOKIEFILE='') and reads cookies via CURLINFO_COOKIELIST,
which stores and returns values verbatim without any decoding.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 15:07:46 +01:00
Jake BarnbyandGitHub 9feb204fd5 Merge pull request #11611 from appwrite/feat-x-oauth2-provider 2026-04-09 01:32:31 +12:00
Jake Barnby 3880f181b3 fix(databases): propagate purge parameter to documentsdb updateCollection 2026-04-09 01:19:18 +12:00
Harsh Mahajan 44a37e9e20 Use Exception for X OAuth2 PKCE encryption errors
Align with other OAuth2 adapters that throw base Exception for
configuration and crypto failures instead of RuntimeException.

Made-with: Cursor
2026-04-08 18:41:42 +05:30
Harsh Mahajan e6cfedd340 addressed greptile comment 2026-04-08 18:27:36 +05:30
Harsh Mahajan e4d1178e71 simplified code 2026-04-08 17:56:37 +05:30
Harsh Mahajan 929bdcef25 Merge branch '1.9.x' into feat-x-oauth2-provider 2026-04-08 17:55:00 +05:30
Harsh Mahajan 3f725c6be9 changes 2026-04-08 17:44:49 +05:30
Jake BarnbyGitHubgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
990a32dd9e Update src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-04-08 23:31:55 +12:00
Jake Barnby c5b8ed9cc1 feat(databases): cache list responses without requiring a select query 2026-04-08 23:02:34 +12:00
Matej BačoandGitHub fec573d23b Merge pull request #11821 from appwrite/chore-public-project-api
Chore: Mark project response format sub-formats as public
2026-04-08 12:32:58 +02:00
Matej Bačo a144968d70 Fix formatting 2026-04-08 12:08:32 +02:00
Matej Bačo 6fa0724404 Mark project response format sub-formats as public 2026-04-08 11:52:12 +02:00
Jake Barnby b1ce71e6b0 (chore): fmt 2026-04-08 21:35:49 +12:00
Jake Barnby 939092726c test(databases): add regression for purge=true list cache invalidation 2026-04-08 21:31:42 +12:00
Jake Barnby c6f8599c75 feat(databases): add purge parameter to updateCollection and updateTable 2026-04-08 21:31:38 +12:00
Jake Barnby 91d8519940 refactor(databases): restructure list response cache and clarify ttl description 2026-04-08 21:31:34 +12:00
Matej BačoandGitHub a90f79f1c1 Merge pull request #11650 from appwrite/feat-public-project-keys
Feat: Public keys API
2026-04-08 11:15:04 +02:00
Matej Bačo f880b6e8c3 Fix failing tests 2026-04-08 10:52:20 +02:00
Matej Bačo b8d65326e6 Fix failing tests 2026-04-08 10:34:18 +02:00
Matej Bačo a9fd82e406 New tests 2026-04-08 10:32:20 +02:00
Matej Bačo a8c2491fbb Fix platform scopes 2026-04-08 10:17:48 +02:00
Jake BarnbyandGitHub 7f6486ec80 Merge pull request #11762 from bhardwajparth51/fix-10923-realtime-atomic-payload 2026-04-08 20:16:55 +12:00
Matej Bačo 388cec1737 Merge branch '1.9.x' into feat-public-project-keys 2026-04-08 10:16:22 +02:00
Parth BhardwajandGitHub 2f5a49a37d Merge branch '1.9.x' into fix-10923-realtime-atomic-payload 2026-04-08 13:39:54 +05:30
Matej BačoandGitHub 1f93184c42 Merge pull request #11615 from appwrite/feat-public-platform-api
Feat: public platform API
2026-04-08 10:08:10 +02:00
Jake BarnbyandGitHub 7d9cf48ca3 Merge pull request #11750 from appwrite/bump-database-version2 2026-04-08 20:04:25 +12:00
Matej Bačo eef2a7abdf Fix scopes 2026-04-08 10:01:52 +02:00
Matej Bačo c7a022ba43 Simplify after discussions 2026-04-08 09:54:57 +02:00
Matej Bačo 96a84a8fd7 Merge branch '1.9.x' into feat-public-project-keys 2026-04-08 09:45:15 +02:00
Matej Bačo cea242c66f Merge branch '1.9.x' into feat-public-platform-api 2026-04-08 09:29:54 +02:00
Matej Bačo ce4eb563b3 AI review fixes 2026-04-08 09:29:12 +02:00
Matej Bačo 2307d637fb Revert new patch version 2026-04-08 09:10:02 +02:00
premtsd-codeandGitHub 0aa72aafae Merge branch '1.9.x' into bump-database-version2 2026-04-08 11:32:22 +05:30
Chirag AggarwalandGitHub 6e1f0d57af Merge pull request #11817 from appwrite/fix/specs-unresolved-model
fix: throw RuntimeException for unresolved response models in spec generation
2026-04-08 11:08:30 +05:30
Chirag Aggarwal 62b6ef06e6 fix: add swoole extension to specs CI job 2026-04-08 10:49:50 +05:30
Chirag Aggarwal f5ab593261 fix: make Project model public for server SDK spec generation
The project.updateLabels route uses AuthType::KEY which makes it
available on the server platform, but the Project model had public=false
causing it to be filtered out during spec generation.
2026-04-08 10:47:37 +05:30
Chirag Aggarwal dd4a43b78c fix: throw RuntimeException for unresolved response models in spec generation
Spec generation silently produced a fatal error when a response model
string could not be resolved to a registered model object. Now throws a
clear RuntimeException in both Swagger2 and OpenAPI3 formats, for both
single and array model responses.

Also adds a CI job to run spec generation on every PR so unresolved
models are caught before merge.
2026-04-08 10:41:43 +05:30
premtsd-codeandGitHub c4c56283e5 Merge branch '1.9.x' into bump-database-version2 2026-04-08 10:33:58 +05:30
Chirag AggarwalandGitHub f71a98a527 Merge pull request #11816 from appwrite/fix/email-session-cache-purge
fix: persist session before purging user cache in email/password login
2026-04-08 10:25:19 +05:30
premtsd-codeandGitHub 2258668769 Merge branch '1.9.x' into bump-database-version2 2026-04-08 10:15:53 +05:30
Chirag Aggarwal 6dba407aed test: add E2E test for email/password session cache race condition
Adds testEmailPasswordSessionNotCorruptedByConcurrentRequests which
reproduces the cross-worker Redis cache race that caused 401s after
login. The test fires a login request, waits for it to reach the cache
purge point, then injects concurrent GET /v1/account requests that
re-cache a stale user document. Verifies the new session is immediately
usable.

Fails against the old ordering (purge before create), passes with the
fix (create before purge).
2026-04-08 10:10:16 +05:30
Luke B. SilverandGitHub 7eef845556 Merge pull request #11794 from blueberry-adii/doc-11793-fix-readme-auth-link
fix appwrite auth broken link in readme
2026-04-07 22:15:29 +01:00
loks0nandClaude Sonnet 4.6 7781d377ae fix: persist session before purging user cache in email/password login
Swap the order of createDocument('sessions') and purgeCachedDocument('users')
in the email/password session creation flow. Previously, the cache was purged
before the session was written, opening a race window in Swoole's async
environment where a concurrent account.get() could re-cache the user with no
sessions, causing sessionVerify to fail with a 401. This matches the correct
ordering already used by the token-based flows (magic URL, OTP, phone).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 21:44:24 +01:00
Chirag AggarwalandGitHub 59bf4663ca Merge pull request #11808 from appwrite/fix/sdk-dev-branch-sync
fix: reset SDK dev branch to base branch before pushing
2026-04-08 00:40:56 +05:30
premtsd-codeandGitHub 6653dbbb92 Merge branch '1.9.x' into bump-database-version2 2026-04-07 20:47:13 +05:30
Prem Palanisamy d7d20ccb29 Remove (int) cast from setTenant in getDatabasesDB same-pool branch 2026-04-07 15:35:20 +01:00
Yash RathiandGitHub 2d54986b09 Merge branch '1.9.x' into fix-11765-global-variable-creation 2026-04-07 10:25:08 -04:00
Matej Bačo 9ea0b2bc2f formatting fix 2026-04-07 15:56:54 +02:00
Matej Bačo 715727853b Fix unit test 2026-04-07 15:56:42 +02:00
Matej Bačo 43d4f709d5 Revert composer changes 2026-04-07 15:00:03 +02:00
Matej Bačo f40050fe6f Revert lockfile changes (failing tests) 2026-04-07 14:51:40 +02:00
Prem Palanisamy 308a534d98 Merge branch 'bump-database-version2' of https://github.com/appwrite/appwrite into bump-database-version2 2026-04-07 13:16:56 +01:00
Prem Palanisamy 35a72c4f08 Remove (int) cast from setTenant in separate-pool branches 2026-04-07 13:10:16 +01:00
Matej Bačo 34dfcba45c Linter fix 2026-04-07 14:08:16 +02:00
Chirag AggarwalandGitHub cb1e31bcd4 Merge pull request #11814 from appwrite/codex/bump-utopia-framework-0-34-18
[codex] Bump utopia-php/framework to 0.34.18
2026-04-07 17:38:06 +05:30
Matej Bačo 3e4e7fc0cd Merge branch '1.9.x' into feat-public-platform-api 2026-04-07 14:08:00 +02:00
Chirag Aggarwal 9403e4d65d Bump utopia-php/framework to 0.34.18 2026-04-07 17:35:32 +05:30
Matej BačoandGitHub 07a49835a6 Merge pull request #11812 from appwrite/chore-migrate-labels-api
Chore: Migrat elabels API
2026-04-07 14:05:31 +02:00
Matej Bačo 23fcb284a1 Fix backwards QA 2026-04-07 12:46:25 +02:00
premtsd-codeandGitHub ffdd0815a7 Merge branch '1.9.x' into bump-database-version2 2026-04-07 15:56:47 +05:30
Prem Palanisamy 4260324153 Merge branch '1.9.x' into bump-database-version2
Resolve merge conflicts in app/init/resources.php and app/worker.php
caused by the DI container migration (Http::setResource/Server::setResource
to $container->set). Port separate-pool shared tables logic for
getDatabasesDB to the new file locations (request.php and message.php)
with the correct $databaseDSN->getParam('namespace') fix.
2026-04-07 11:25:06 +01:00
Matej Bačo d66813d3cf Fix tests + QA fixes 2026-04-07 12:07:21 +02:00
Matej Bačo f3acadd53c Fix linter 2026-04-07 10:43:57 +02:00
Matej Bačo 331fcee710 Merge branch '1.9.x' into feat-public-platform-api 2026-04-07 10:43:11 +02:00
Damodar LohaniandGitHub ed1680837d Merge branch '1.9.x' into feat-audit-user-type-distinction 2026-04-07 14:11:22 +05:45
Chirag Aggarwal 7864a5b9d1 fix: use --force-with-lease on SDK dev branch push
After resetting dev to the base branch, the remote dev may have
diverged history from squash merges. A plain push would be rejected
as non-fast-forward. Using --force-with-lease safely overwrites
the remote since we just fetched.
2026-04-07 12:52:09 +05:30
Chirag Aggarwal f11bd7ce0e fix: reset SDK dev branch to base branch before pushing
The dev branch was being reset to origin/dev, which retains stale
commits after squash merges. This caused recurring merge conflicts
and inflated PR diffs. Using `checkout -B dev <baseBranch>` ensures
dev always starts fresh from the default branch.
2026-04-07 12:50:18 +05:30
Parth BhardwajandGitHub fffc6795a7 Merge branch '1.9.x' into fix-10923-realtime-atomic-payload 2026-04-07 08:49:25 +05:30
premtsd-codeandGitHub 77ceb15d7d Merge branch '1.9.x' into bump-database-version2 2026-04-06 15:44:40 +05:30
My Name 2cd91f509b fix: make variableId optional in createProjectVariable endpoint 2026-04-05 18:23:58 -04:00
Aditya a06ba57384 fix appwrite auth broken link in readme 2026-04-05 23:39:13 +05:30
Damodar LohaniandGitHub f6484294da Merge branch '1.9.x' into feat-audit-user-type-distinction 2026-04-05 08:04:38 +05:45
bhardwajparth51 2c1813198d Simplify comments in Realtime E2E test 2026-04-03 22:12:24 +05:30
bhardwajparth51 912ea37af6 Address review feedback: Remove redundant Realtime triggers, correctly reorder hydration, and add E2E tests 2026-04-03 22:07:24 +05:30
Parth BhardwajandGitHub ccc74dea74 Merge branch '1.9.x' into fix-10923-realtime-atomic-payload 2026-04-03 20:28:49 +05:30
bhardwajparth51 a6c6a5624a fix: ensure realtime event payload is populated for all atomic subclasses 2026-04-02 21:04:01 +05:30
bhardwajparth51 ee5bb6d73d fix: ensure realtime event payload is populated for atomic operations 2026-04-02 20:47:23 +05:30
Prem Palanisamy a071c715bc Merge remote-tracking branch 'origin/1.9.x' into bump-database-version2 2026-04-02 10:10:03 +02:00
Prem Palanisamy 52981e0164 fix: restore full CI matrix and revert test/endpoint changes to 1.9.x 2026-04-02 10:09:36 +02:00
Prem Palanisamy cb9d3869f0 Merge remote-tracking branch 'origin/1.9.x' into bump-database-version2
# Conflicts:
#	src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Create.php
2026-04-02 06:53:05 +02:00
Prem Palanisamy d17ae517d3 fix: replace exists+create with try/catch for vectorsdb metadata init 2026-04-02 06:26:55 +02:00
Prem Palanisamy 25d9891f2b fix: use email probe in JSON export test, format fixes, add requireAdapter skips to Databases VectorsDB/DocumentsDB tests 2026-04-02 04:39:56 +02:00
Damodar LohaniandGitHub a928fcd40f Merge pull request #11754 from appwrite/claude/sync-1.9.x-fix-tests-VoCBt
Fix PHPStan baseline and code quality issues
2026-04-02 08:17:54 +05:45
Claude 2d34301834 fix: add missing userType field to legacy log endpoints
The users.php and messaging.php legacy controllers were missing the
userType field in their log output, creating an inconsistency with the
new audit user type distinction feature. Also adds missing mode field
to users.php logs endpoint.

https://claude.ai/code/session_01J9gKXwbHoLggsGwJi6KUnM
2026-04-02 01:13:01 +00:00
Claude cf7259e060 Merge remote-tracking branch 'origin/1.9.x' into claude/sync-1.9.x-fix-tests-VoCBt 2026-04-02 01:05:56 +00:00
Prem Palanisamy 8c9f9c6f58 fix: inherit project shared tables for separate pools, skip cross-engine migration tests 2026-04-02 02:05:10 +02:00
Prem Palanisamy c322cc3ffe Merge remote-tracking branch 'origin/1.9.x' into bump-database-version
# Conflicts:
#	src/Appwrite/Event/Message/Usage.php
2026-04-01 17:34:13 +02:00
Matej Bačo b554243447 Merge branch '1.9.x' into feat-public-platform-api 2026-04-01 13:35:46 +02:00
Prem Palanisamy d9eb69aa47 Merge remote-tracking branch 'origin/1.9.x' into bump-database-version 2026-04-01 10:41:39 +02:00
Damodar LohaniandGitHub e250b413f0 Merge branch '1.9.x' into feat-audit-user-type-distinction 2026-04-01 12:58:09 +05:45
Harsh MahajanandGitHub 8ccfb1aebb Merge branch '1.9.x' into feat-x-oauth2-provider 2026-04-01 12:17:05 +05:30
Harsh Mahajan 9da4f19d4f fix: pkce flow 2026-04-01 12:11:40 +05:30
Prem Palanisamy 7f9ce1ca85 Merge remote-tracking branch 'origin/1.9.x' into bump-database-version 2026-04-01 07:37:57 +02:00
Prem Palanisamy 168166b9c1 bump utopia-php/database to 5.3.19 and fix shared-mode CI failures
- Bump utopia-php/database from 5.3.17 to 5.3.19

- Remove invalid (int) cast on tenant sequence in shared tables mode

- Fix DSN construction for documentsdb/vectorsdb: filter empty strings
  from explode(), skip pool filtering when shared tables env vars unset,
  fail fast when no pool found

- Use dedicated mode for separate database pools in getDatabasesDB
  since shared tables can't work across engines (PostgreSQL integer
  _tenant vs MongoDB UUID tenant). Auto-init schema on first use.

- Add documentsdb/vectorsdb shared tables env vars to CI workflow

- Fix testChannelTablesDBRowUpdate race condition with deterministic
  event drain loop
2026-03-31 21:24:22 +02:00
Harsh Mahajan fe99470374 revert test env change 2026-03-30 16:09:42 +05:30
Matej Bačo d9a75c5938 Improved backwards compatibility 2026-03-27 15:34:34 +01:00
Matej Bačo bb80e50d01 Self review after refactor 2026-03-27 14:00:44 +01:00
Matej Bačo 644840ec66 Refactor to new platforms interfaces 2026-03-27 13:45:58 +01:00
Matej Bačo 71e714c66b Remove extra logging 2026-03-27 12:49:16 +01:00
Matej Bačo b2b187c57d review fixes 2026-03-27 12:35:48 +01:00
copilot-swe-agent[bot]andMeldiron ecc76c7520 fix: address review feedback - log abort exception, fix test cleanup
Agent-Logs-Url: https://github.com/appwrite/appwrite/sessions/045e63f6-9a81-447b-ba79-7391ab97fb01

Co-authored-by: Meldiron <19310830+Meldiron@users.noreply.github.com>
2026-03-26 18:34:19 +00:00
copilot-swe-agent[bot]andMeldiron 898e8e214b fix: allow deletion of partially-uploaded (pending) files and add test
Agent-Logs-Url: https://github.com/appwrite/appwrite/sessions/8d14b17a-78d8-48c6-b6d8-51d9697adde0

Co-authored-by: Meldiron <19310830+Meldiron@users.noreply.github.com>
2026-03-26 18:04:41 +00:00
Matej Bačo 43db2ddf6e Fix default null 2026-03-26 16:24:28 +01:00
Matej Bačo 7371b68418 Fix tests compatibility 2026-03-26 15:51:03 +01:00
Matej Bačo 7f4d5f692d Fix non-expiry key actions 2026-03-26 15:44:50 +01:00
Matej Bačo 8113854a89 AI review fixes 2026-03-26 15:37:57 +01:00
Matej Bačo eb097a037b Finish security todos 2026-03-26 15:35:40 +01:00
Matej Bačo cbfdd27834 Public keys Apis 2026-03-26 15:00:20 +01:00
Matej Bačo 113c266881 Fix audit resource ID missing 2026-03-26 14:43:38 +01:00
Harsh Mahajan 614db7388e fix: push 2026-03-26 17:59:30 +05:30
Harsh MahajanandGitHub cbc5259db3 Merge branch '1.9.x' into feat-x-oauth2-provider 2026-03-25 23:29:04 +05:30
Matej Bačo 0d6d6a0a35 Make tests pass 2026-03-25 16:11:01 +01:00
Matej Bačo e8d4065af5 Improve tests human review 2026-03-25 15:54:10 +01:00
Matej Bačo 008110b3f7 Platform API tests 2026-03-25 15:47:11 +01:00
Harsh MahajanandGitHub efb0cae4e0 Merge branch '1.9.x' into feat-x-oauth2-provider 2026-03-25 16:49:54 +05:30
Matej Bačo ae99d59aba CodeQL review 2026-03-24 14:52:58 +01:00
Matej Bačo a06aaaf9ca Remove Db schema changes 2026-03-24 13:55:54 +01:00
Matej Bačo 094cd180b5 Remove leftover 2026-03-24 13:41:12 +01:00
Matej Bačo a8f43f3486 Update DB schema 2026-03-24 13:36:11 +01:00
Matej Bačo 038f4b5992 More backwards compatibility fixes 2026-03-24 13:33:15 +01:00
Matej Bačo c903fb87ac Fix backwards compatibility 2026-03-24 12:53:25 +01:00
Matej Bačo e5841c4cc0 Fix syntax error 2026-03-24 11:29:24 +01:00
Matej Bačo bb7815bd57 Merge branch '1.9.x' into feat-public-platform-api 2026-03-24 11:18:18 +01:00
Matej Bačo 8ccf5094f8 fix multi-model conditions 2026-03-23 16:42:14 +01:00
Matej Bačo 39f2d24907 AI code review fixes 2026-03-23 16:10:12 +01:00
Matej Bačo d3c5a425e7 Implement public platform API 2026-03-23 15:46:11 +01:00
Harsh Mahajan 85703d29e1 addressed greptile suggestions 2026-03-23 19:08:12 +05:30
Harsh MahajanandGitHub d3c11b5c93 Merge branch '1.9.x' into feat-x-oauth2-provider 2026-03-23 18:51:10 +05:30
Harsh MahajanandGitHub 6f177a0a7a Merge branch '1.9.x' into feat-x-oauth2-provider 2026-03-23 17:50:29 +05:30
Harsh Mahajan dc48bb35ef added pkce to base 2026-03-23 17:49:42 +05:30
Harsh Mahajan 8218f36d34 code rabbit comment 2026-03-23 13:32:06 +05:30
Harsh Mahajan 0fe906c538 feat: Add X OAuth 2.0 provider 2026-03-23 13:21:04 +05:30
Damodar LohaniandGitHub 31410879a7 Merge branch '1.9.x' into feat-audit-user-type-distinction 2026-03-22 08:36:13 +05:45
Damodar Lohani 343e352b17 fix: prevent overwriting user type in audit queue if already set 2026-03-22 02:31:46 +00:00
Damodar LohaniandGitHub b38ea72407 Merge branch '1.8.x' into feat-audit-user-type-distinction 2026-03-22 08:05:29 +05:45
Damodar LohaniandGitHub 92b7760e94 Merge branch '1.8.x' into feat-audit-user-type-distinction 2026-03-19 17:44:50 +05:45
Damodar LohaniGitHubgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
fe988f4489 Update app/controllers/shared/api.php
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-19 17:44:35 +05:45
Damodar LohaniandClaude Opus 4.6 8b3d3c6f8b feat: distinguish user types in audit logs
Introduce granular audit user types to differentiate between regular
users, console admins, guests, and the various API key scopes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 03:55:22 +00:00
112 changed files with 7126 additions and 1284 deletions
+33
View File
@@ -161,6 +161,27 @@ jobs:
- name: Run PHPStan
run: composer analyze -- --no-progress
specs:
name: Checks / Specs
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v6
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: swoole
tools: composer:v2
coverage: none
- name: Install dependencies
run: composer install --prefer-dist --no-progress --ignore-platform-reqs
- name: Generate specs
run: _APP_STORAGE_LIMIT=5368709120 php app/cli.php specs --version=latest --git=no
locale:
name: Checks / Locale
runs-on: ubuntu-latest
@@ -459,6 +480,10 @@ jobs:
_APP_BROWSER_HOST: http://invalid-browser/v1
_APP_DATABASE_SHARED_TABLES: ${{ matrix.mode != 'dedicated' && 'database_db_main' || '' }}
_APP_DATABASE_SHARED_TABLES_V1: ${{ matrix.mode == 'shared_v1' && 'database_db_main' || '' }}
_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES: ${{ matrix.mode != 'dedicated' && 'documentsdb_db_main' || '' }}
_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES_V1: ${{ matrix.mode == 'shared_v1' && 'documentsdb_db_main' || '' }}
_APP_DATABASE_VECTORSDB_SHARED_TABLES: ${{ matrix.mode != 'dedicated' && 'vectorsdb_db_main' || '' }}
_APP_DATABASE_VECTORSDB_SHARED_TABLES_V1: ${{ matrix.mode == 'shared_v1' && 'vectorsdb_db_main' || '' }}
run: |
docker load --input /tmp/${{ env.IMAGE }}.tar
docker compose pull --quiet --ignore-buildable
@@ -533,6 +558,10 @@ jobs:
_APP_OPTIONS_ABUSE: enabled
_APP_DATABASE_SHARED_TABLES: ${{ matrix.mode != 'dedicated' && 'database_db_main' || '' }}
_APP_DATABASE_SHARED_TABLES_V1: ${{ matrix.mode == 'shared_v1' && 'database_db_main' || '' }}
_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES: ${{ matrix.mode != 'dedicated' && 'documentsdb_db_main' || '' }}
_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES_V1: ${{ matrix.mode == 'shared_v1' && 'documentsdb_db_main' || '' }}
_APP_DATABASE_VECTORSDB_SHARED_TABLES: ${{ matrix.mode != 'dedicated' && 'vectorsdb_db_main' || '' }}
_APP_DATABASE_VECTORSDB_SHARED_TABLES_V1: ${{ matrix.mode == 'shared_v1' && 'vectorsdb_db_main' || '' }}
run: |
docker load --input /tmp/${{ env.IMAGE }}.tar
docker compose pull --quiet --ignore-buildable
@@ -590,6 +619,10 @@ jobs:
env:
_APP_DATABASE_SHARED_TABLES: ${{ matrix.mode != 'dedicated' && 'database_db_main' || '' }}
_APP_DATABASE_SHARED_TABLES_V1: ${{ matrix.mode == 'shared_v1' && 'database_db_main' || '' }}
_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES: ${{ matrix.mode != 'dedicated' && 'documentsdb_db_main' || '' }}
_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES_V1: ${{ matrix.mode == 'shared_v1' && 'documentsdb_db_main' || '' }}
_APP_DATABASE_VECTORSDB_SHARED_TABLES: ${{ matrix.mode != 'dedicated' && 'vectorsdb_db_main' || '' }}
_APP_DATABASE_VECTORSDB_SHARED_TABLES_V1: ${{ matrix.mode == 'shared_v1' && 'vectorsdb_db_main' || '' }}
run: |
docker load --input /tmp/${{ env.IMAGE }}.tar
docker compose pull --quiet --ignore-buildable
+1 -1
View File
@@ -44,7 +44,7 @@ Table of Contents:
## Products
- **[Appwrite Auth](https://appwrite.io/docs/products/authentication)** - Secure user authentication with multiple login methods including email/password, SMS, OAuth, anonymous sessions, and magic links. Includes session management, multi-factor authentication, and user verification flows.
- **[Appwrite Auth](https://appwrite.io/docs/products/auth)** - Secure user authentication with multiple login methods including email/password, SMS, OAuth, anonymous sessions, and magic links. Includes session management, multi-factor authentication, and user verification flows.
- **[Appwrite Databases](https://appwrite.io/docs/products/databases)** - Scalable structured data storage with support for databases, tables, and rows. Includes querying, pagination, indexing, and relationships to model complex application data.
+3 -3
View File
@@ -594,7 +594,7 @@ $platformCollections = [
'filters' => [],
],
[
'$id' => ID::custom('key'),
'$id' => ID::custom('key'), // For app platforms
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
@@ -605,7 +605,7 @@ $platformCollections = [
'filters' => [],
],
[
'$id' => ID::custom('store'),
'$id' => ID::custom('store'), // Unused at the moment
'type' => Database::VAR_STRING,
'format' => '',
'size' => 256,
@@ -616,7 +616,7 @@ $platformCollections = [
'filters' => [],
],
[
'$id' => ID::custom('hostname'),
'$id' => ID::custom('hostname'), // For web platforms
'type' => Database::VAR_STRING,
'format' => '',
'size' => 256,
+10
View File
@@ -1179,6 +1179,16 @@ return [
'description' => 'Platform with the requested ID could not be found.',
'code' => 404,
],
Exception::PLATFORM_METHOD_UNSUPPORTED => [
'name' => Exception::PLATFORM_METHOD_UNSUPPORTED,
'description' => 'The requested platform has invalid type. Please use corresponding update method for the platform type.',
'code' => 400,
],
Exception::PLATFORM_ALREADY_EXISTS => [
'name' => Exception::PLATFORM_ALREADY_EXISTS,
'description' => 'Platform with the same ID already exists in this project. Try again with a different ID.',
'code' => 409,
],
Exception::VARIABLE_NOT_FOUND => [
'name' => Exception::VARIABLE_NOT_FOUND,
'description' => 'Variable with the requested ID could not be found.',
+11
View File
@@ -376,6 +376,17 @@ return [
'mock' => false,
'class' => 'Appwrite\\Auth\\OAuth2\\Wordpress',
],
'x' => [
'name' => 'X',
'developers' => 'https://docs.x.com/fundamentals/authentication/oauth-2-0/authorization-code',
'icon' => 'icon-twitter',
'enabled' => true,
'sandbox' => false,
'form' => false,
'beta' => false,
'mock' => false,
'class' => 'Appwrite\\Auth\\OAuth2\\X',
],
'yahoo' => [
'name' => 'Yahoo',
'developers' => 'https://developer.yahoo.com/oauth2/guide/flows_authcode/',
-14
View File
@@ -3,13 +3,6 @@
// List of scopes for organization (teams) API keys
return [
"platforms.read" => [
"description" => 'Access to read project\'s platforms',
],
"platforms.write" => [
"description" =>
'Access to create, update, and delete project\'s platforms',
],
"projects.read" => [
"description" => 'Access to read organization\'s projects',
],
@@ -17,13 +10,6 @@ return [
"description" =>
"Access to create, update, and delete projects in organization",
],
"keys.read" => [
"description" => 'Access to read project\'s API keys',
],
"keys.write" => [
"description" =>
"Access to create, update, and delete project\'s API keys",
],
"devKeys.read" => [
"description" => 'Access to read project\'s development keys',
],
+16
View File
@@ -188,4 +188,20 @@ return [ // List of publicly visible scopes
"description" =>
"Access to update project\'s information",
],
"keys.read" => [
"description" =>
"Access to read project\'s keys",
],
"keys.write" => [
"description" =>
"Access to create, update, and delete project\'s keys",
],
"platforms.read" => [
"description" =>
"Access to read project\'s platforms",
],
"platforms.write" => [
"description" =>
"Access to create, update, and delete project\'s platforms",
],
];
+28 -169
View File
@@ -9,6 +9,7 @@ use Appwrite\Auth\Validator\PasswordDictionary;
use Appwrite\Auth\Validator\PasswordHistory;
use Appwrite\Auth\Validator\PersonalData;
use Appwrite\Auth\Validator\Phone;
use Appwrite\Bus\Events\SessionCreated;
use Appwrite\Detector\Detector;
use Appwrite\Event\Delete;
use Appwrite\Event\Event;
@@ -41,6 +42,7 @@ use Utopia\Auth\Proofs\Code as ProofsCode;
use Utopia\Auth\Proofs\Password as ProofsPassword;
use Utopia\Auth\Proofs\Token as ProofsToken;
use Utopia\Auth\Store;
use Utopia\Bus\Bus;
use Utopia\Config\Config;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
@@ -75,139 +77,8 @@ use Utopia\Validator\WhiteList;
$oauthDefaultSuccess = '/console/auth/oauth2/success';
$oauthDefaultFailure = '/console/auth/oauth2/failure';
function sendSessionAlert(Locale $locale, Document $user, Document $project, array $platform, Document $session, Mail $queueForMails)
{
$subject = $locale->getText("emails.sessionAlert.subject");
$preview = $locale->getText("emails.sessionAlert.preview");
$customTemplate = $project->getAttribute('templates', [])['email.sessionAlert-' . $locale->default] ?? [];
$smtpBaseTemplate = $project->getAttribute('smtpBaseTemplate', 'email-base');
$validator = new FileName();
if (!$validator->isValid($smtpBaseTemplate)) {
throw new Exception(Exception::GENERAL_BAD_REQUEST, 'Invalid template path');
}
$bodyTemplate = __DIR__ . '/../../config/locale/templates/' . $smtpBaseTemplate . '.tpl';
$message = Template::fromFile(__DIR__ . '/../../config/locale/templates/email-session-alert.tpl');
$message
->setParam('{{hello}}', $locale->getText("emails.sessionAlert.hello"))
->setParam('{{body}}', $locale->getText("emails.sessionAlert.body"))
->setParam('{{listDevice}}', $locale->getText("emails.sessionAlert.listDevice"))
->setParam('{{listIpAddress}}', $locale->getText("emails.sessionAlert.listIpAddress"))
->setParam('{{listCountry}}', $locale->getText("emails.sessionAlert.listCountry"))
->setParam('{{footer}}', $locale->getText("emails.sessionAlert.footer"))
->setParam('{{thanks}}', $locale->getText("emails.sessionAlert.thanks"))
->setParam('{{signature}}', $locale->getText("emails.sessionAlert.signature"));
$body = $message->render();
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
$senderEmail = System::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$senderName = System::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server');
$replyTo = "";
if ($smtpEnabled) {
if (!empty($smtp['senderEmail'])) {
$senderEmail = $smtp['senderEmail'];
}
if (!empty($smtp['senderName'])) {
$senderName = $smtp['senderName'];
}
if (!empty($smtp['replyTo'])) {
$replyTo = $smtp['replyTo'];
}
$queueForMails
->setSmtpHost($smtp['host'] ?? '')
->setSmtpPort($smtp['port'] ?? '')
->setSmtpUsername($smtp['username'] ?? '')
->setSmtpPassword($smtp['password'] ?? '')
->setSmtpSecure($smtp['secure'] ?? '');
if (!empty($customTemplate)) {
if (!empty($customTemplate['senderEmail'])) {
$senderEmail = $customTemplate['senderEmail'];
}
if (!empty($customTemplate['senderName'])) {
$senderName = $customTemplate['senderName'];
}
if (!empty($customTemplate['replyTo'])) {
$replyTo = $customTemplate['replyTo'];
}
$body = $customTemplate['message'] ?? '';
$subject = $customTemplate['subject'] ?? $subject;
}
$queueForMails
->setSmtpReplyTo($replyTo)
->setSmtpSenderEmail($senderEmail)
->setSmtpSenderName($senderName);
}
// session alerts should always have a client name!
$clientName = $session->getAttribute('clientName');
if (empty($clientName)) {
// fallback to the user agent and then unknown!
$userAgent = $session->getAttribute('userAgent');
$clientName = !empty($userAgent) ? $userAgent : 'UNKNOWN';
$session->setAttribute('clientName', $clientName);
}
$projectName = $project->getAttribute('name');
if ($project->getId() === 'console') {
$projectName = $platform['platformName'];
}
$emailVariables = [
'direction' => $locale->getText('settings.direction'),
'date' => (new \DateTime())->format('F j'),
'year' => (new \DateTime())->format('YYYY'),
'time' => (new \DateTime())->format('H:i:s'),
'user' => $user->getAttribute('name'),
'project' => $projectName,
'device' => $session->getAttribute('clientName'),
'ipAddress' => $session->getAttribute('ip'),
'country' => $locale->getText('countries.' . $session->getAttribute('countryCode'), $locale->getText('locale.country.unknown')),
];
if ($smtpBaseTemplate === APP_BRANDED_EMAIL_BASE_TEMPLATE) {
$emailVariables = array_merge($emailVariables, [
'accentColor' => $platform['accentColor'],
'logoUrl' => $platform['logoUrl'],
'twitter' => $platform['twitterUrl'],
'discord' => $platform['discordUrl'],
'github' => $platform['githubUrl'],
'terms' => $platform['termsUrl'],
'privacy' => $platform['privacyUrl'],
'platform' => $platform['platformName'],
]);
}
$email = $user->getAttribute('email');
$queueForMails
->setSubject($subject)
->setPreview($preview)
->setBody($body)
->setBodyTemplate($bodyTemplate)
->appendVariables($emailVariables)
->setRecipient($email);
// since this is console project, set email sender name!
if ($smtpBaseTemplate === APP_BRANDED_EMAIL_BASE_TEMPLATE) {
$queueForMails->setSenderName($platform['emailSenderName']);
}
$queueForMails->trigger();
}
$createSession = function (string $userId, string $secret, Request $request, Response $response, User $user, Database $dbForProject, Document $project, array $platform, Locale $locale, Reader $geodb, Event $queueForEvents, Mail $queueForMails, Store $store, ProofsToken $proofForToken, ProofsCode $proofForCode, bool $domainVerification, ?string $cookieDomain, Authorization $authorization) {
$createSession = function (string $userId, string $secret, Request $request, Response $response, User $user, Database $dbForProject, Document $project, array $platform, Locale $locale, Reader $geodb, Event $queueForEvents, Bus $bus, Store $store, ProofsToken $proofForToken, ProofsCode $proofForCode, bool $domainVerification, ?string $cookieDomain, Authorization $authorization) {
// Attempt to decode secret as a JWT (used by OAuth2 token flow to carry provider info)
$oauthProvider = null;
@@ -318,23 +189,12 @@ $createSession = function (string $userId, string $secret, Request $request, Res
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed saving user to DB');
}
$isAllowedTokenType = match ($verifiedToken->getAttribute('type')) {
TOKEN_TYPE_MAGIC_URL,
TOKEN_TYPE_EMAIL => false,
default => true
};
$hasUserEmail = $user->getAttribute('email', false) !== false;
$isSessionAlertsEnabled = $project->getAttribute('auths', [])['sessionAlerts'] ?? false;
$isNotFirstSession = $dbForProject->count('sessions', [
Query::equal('userId', [$user->getId()]),
]) !== 1;
if ($isAllowedTokenType && $hasUserEmail && $isSessionAlertsEnabled && $isNotFirstSession) {
sendSessionAlert($locale, $user, $project, $platform, $session, $queueForMails);
}
$bus->dispatch(new SessionCreated(
user: $user->getArrayCopy(),
project: $project->getArrayCopy(),
session: $session->getArrayCopy(),
locale: $locale->default,
));
$queueForEvents
->setParam('userId', $user->getId())
@@ -1034,7 +894,7 @@ Http::post('/v1/account/sessions/email')
->inject('locale')
->inject('geodb')
->inject('queueForEvents')
->inject('queueForMails')
->inject('bus')
->inject('hooks')
->inject('store')
->inject('proofForPassword')
@@ -1042,7 +902,7 @@ Http::post('/v1/account/sessions/email')
->inject('domainVerification')
->inject('cookieDomain')
->inject('authorization')
->action(function (string $email, string $password, Request $request, Response $response, User $user, Database $dbForProject, Document $project, array $platform, Locale $locale, Reader $geodb, Event $queueForEvents, Mail $queueForMails, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, bool $domainVerification, ?string $cookieDomain, Authorization $authorization) {
->action(function (string $email, string $password, Request $request, Response $response, User $user, Database $dbForProject, Document $project, array $platform, Locale $locale, Reader $geodb, Event $queueForEvents, Bus $bus, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, bool $domainVerification, ?string $cookieDomain, Authorization $authorization) {
$email = \strtolower($email);
$protocol = $request->getProtocol();
@@ -1103,14 +963,14 @@ Http::post('/v1/account/sessions/email')
]));
}
$dbForProject->purgeCachedDocument('users', $user->getId());
$session = $dbForProject->createDocument('sessions', $session->setAttribute('$permissions', [
Permission::read(Role::user($user->getId())),
Permission::update(Role::user($user->getId())),
Permission::delete(Role::user($user->getId())),
]));
$dbForProject->purgeCachedDocument('users', $user->getId());
$encoded = $store
->setProperty('id', $user->getId())
->setProperty('secret', $secret)
@@ -1141,15 +1001,12 @@ Http::post('/v1/account/sessions/email')
->setParam('sessionId', $session->getId())
;
if ($project->getAttribute('auths', [])['sessionAlerts'] ?? false) {
if (
$dbForProject->count('sessions', [
Query::equal('userId', [$user->getId()]),
]) !== 1
) {
sendSessionAlert($locale, $user, $project, $platform, $session, $queueForMails);
}
}
$bus->dispatch(new SessionCreated(
user: $user->getArrayCopy(),
project: $project->getArrayCopy(),
session: $session->getArrayCopy(),
locale: $locale->default,
));
$response->dynamic($session, Response::MODEL_SESSION);
});
@@ -1343,7 +1200,7 @@ Http::post('/v1/account/sessions/token')
->inject('locale')
->inject('geodb')
->inject('queueForEvents')
->inject('queueForMails')
->inject('bus')
->inject('store')
->inject('proofForToken')
->inject('proofForCode')
@@ -2185,7 +2042,7 @@ Http::get('/v1/account/tokens/oauth2/:provider')
}
$host = $platform['consoleHostname'] ?? '';
$protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') == 'disabled' ? 'http' : 'https';
$protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https';
$port = $request->getPort();
$redirectBase = $protocol . '://' . $host;
if ($protocol === 'https' && $port !== '443') {
@@ -2208,10 +2065,12 @@ Http::get('/v1/account/tokens/oauth2/:provider')
'token' => true,
], $scopes);
$loginURL = $oauth2->getLoginURL();
$response
->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->addHeader('Pragma', 'no-cache')
->redirect($oauth2->getLoginURL());
->redirect($loginURL);
});
Http::post('/v1/account/tokens/magic-url')
@@ -2895,16 +2754,16 @@ Http::put('/v1/account/sessions/magic-url')
->inject('locale')
->inject('geodb')
->inject('queueForEvents')
->inject('queueForMails')
->inject('bus')
->inject('store')
->inject('proofForCode')
->inject('domainVerification')
->inject('cookieDomain')
->inject('authorization')
->action(function ($userId, $secret, $request, $response, $user, $dbForProject, $project, $platform, $locale, $geodb, $queueForEvents, $queueForMails, $store, $proofForCode, $domainVerification, $cookieDomain, $authorization) use ($createSession) {
->action(function ($userId, $secret, $request, $response, $user, $dbForProject, $project, $platform, $locale, $geodb, $queueForEvents, $bus, $store, $proofForCode, $domainVerification, $cookieDomain, $authorization) use ($createSession) {
$proofForToken = new ProofsToken(TOKEN_LENGTH_MAGIC_URL);
$proofForToken->setHash(new Sha());
$createSession($userId, $secret, $request, $response, $user, $dbForProject, $project, $platform, $locale, $geodb, $queueForEvents, $queueForMails, $store, $proofForToken, $proofForCode, $domainVerification, $cookieDomain, $authorization);
$createSession($userId, $secret, $request, $response, $user, $dbForProject, $project, $platform, $locale, $geodb, $queueForEvents, $bus, $store, $proofForToken, $proofForCode, $domainVerification, $cookieDomain, $authorization);
});
Http::put('/v1/account/sessions/phone')
@@ -2946,7 +2805,7 @@ Http::put('/v1/account/sessions/phone')
->inject('locale')
->inject('geodb')
->inject('queueForEvents')
->inject('queueForMails')
->inject('bus')
->inject('store')
->inject('proofForToken')
->inject('proofForCode')
+4
View File
@@ -1180,6 +1180,7 @@ Http::get('/v1/messaging/providers/:providerId/logs')
'userEmail' => $log['data']['userEmail'] ?? null,
'userName' => $log['data']['userName'] ?? null,
'mode' => $log['data']['mode'] ?? null,
'userType' => $log['data']['userType'] ?? null,
'ip' => $log['ip'],
'time' => $log['time'],
'osCode' => $os['osCode'],
@@ -2585,6 +2586,7 @@ Http::get('/v1/messaging/topics/:topicId/logs')
'userEmail' => $log['data']['userEmail'] ?? null,
'userName' => $log['data']['userName'] ?? null,
'mode' => $log['data']['mode'] ?? null,
'userType' => $log['data']['userType'] ?? null,
'ip' => $log['ip'],
'time' => $log['time'],
'osCode' => $os['osCode'],
@@ -3000,6 +3002,7 @@ Http::get('/v1/messaging/subscribers/:subscriberId/logs')
'userEmail' => $log['data']['userEmail'] ?? null,
'userName' => $log['data']['userName'] ?? null,
'mode' => $log['data']['mode'] ?? null,
'userType' => $log['data']['userType'] ?? null,
'ip' => $log['ip'],
'time' => $log['time'],
'osCode' => $os['osCode'],
@@ -3813,6 +3816,7 @@ Http::get('/v1/messaging/messages/:messageId/logs')
'userEmail' => $log['data']['userEmail'] ?? null,
'userName' => $log['data']['userName'] ?? null,
'mode' => $log['data']['mode'] ?? null,
'userType' => $log['data']['userType'] ?? null,
'ip' => $log['ip'],
'time' => $log['time'],
'osCode' => $os['osCode'],
-558
View File
@@ -5,28 +5,18 @@ use Appwrite\Auth\Validator\MockNumber;
use Appwrite\Event\Delete;
use Appwrite\Event\Mail;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Deprecated;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Template\Template;
use Appwrite\Utopia\Database\Validator\CustomId;
use Appwrite\Utopia\Database\Validator\Queries\Keys;
use Appwrite\Utopia\Response;
use PHPMailer\PHPMailer\PHPMailer;
use Utopia\Config\Config;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Utopia\Database\Exception\Query as QueryException;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Helpers\Permission;
use Utopia\Database\Helpers\Role;
use Utopia\Database\Query;
use Utopia\Database\Validator\Datetime as DatetimeValidator;
use Utopia\Database\Validator\Query\Cursor;
use Utopia\Database\Validator\UID;
use Utopia\Emails\Validator\Email;
use Utopia\Http\Http;
@@ -769,288 +759,6 @@ Http::delete('/v1/projects/:projectId')
$response->noContent();
});
// Keys
Http::post('/v1/projects/:projectId/keys')
->desc('Create key')
->groups(['api', 'projects'])
->label('scope', 'keys.write')
->label('sdk', new Method(
namespace: 'projects',
group: 'keys',
name: 'createKey',
description: '/docs/references/projects/create-key.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_CREATED,
model: Response::MODEL_KEY,
)
]
))
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
// TODO: When migrating to Platform API, mark keyId required for consistency
->param('keyId', 'unique()', fn (Database $dbForPlatform) => new CustomId($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', true, ['dbForPlatform'])->param('name', null, new Text(128), 'Key name. Max length: 128 chars.')
->param('scopes', null, new Nullable(new ArrayList(new WhiteList(array_keys(Config::getParam('projectScopes')), true), APP_LIMIT_ARRAY_PARAMS_SIZE)), 'Key scopes list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' scopes are allowed.')
->param('expire', null, new Nullable(new DatetimeValidator()), 'Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Use null for unlimited expiration.', true)
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $keyId, string $name, array $scopes, ?string $expire, Response $response, Database $dbForPlatform) {
$keyId = $keyId == 'unique()' ? ID::unique() : $keyId;
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$key = new Document([
'$id' => $keyId,
'$permissions' => [
Permission::read(Role::any()),
Permission::update(Role::any()),
Permission::delete(Role::any()),
],
'resourceInternalId' => $project->getSequence(),
'resourceId' => $project->getId(),
'resourceType' => 'projects',
'name' => $name,
'scopes' => $scopes,
'expire' => $expire,
'sdks' => [],
'accessedAt' => null,
'secret' => API_KEY_STANDARD . '_' . \bin2hex(\random_bytes(128)),
]);
try {
$key = $dbForPlatform->createDocument('keys', $key);
} catch (Duplicate) {
throw new Exception(Exception::KEY_ALREADY_EXISTS);
}
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($key, Response::MODEL_KEY);
});
Http::get('/v1/projects/:projectId/keys')
->desc('List keys')
->groups(['api', 'projects'])
->label('scope', 'keys.read')
->label('sdk', new Method(
namespace: 'projects',
group: 'keys',
name: 'listKeys',
description: '/docs/references/projects/list-keys.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_KEY_LIST,
)
]
))
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('queries', [], new Keys(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Keys::ALLOWED_ATTRIBUTES), true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, array $queries, bool $includeTotal, Response $response, Database $dbForPlatform) {
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
try {
$queries = Query::parseQueries($queries);
} catch (QueryException $e) {
throw new Exception(Exception::GENERAL_QUERY_INVALID, $e->getMessage());
}
// Backwards compatibility
if (\count(Query::getByType($queries, [Query::TYPE_LIMIT])) === 0) {
$queries[] = Query::limit(5000);
}
$queries[] = Query::equal('resourceType', ['projects']);
$queries[] = Query::equal('resourceInternalId', [$project->getSequence()]);
$cursor = Query::getCursorQueries($queries, false);
$cursor = \reset($cursor);
if ($cursor !== false) {
$validator = new Cursor();
if (!$validator->isValid($cursor)) {
throw new Exception(Exception::GENERAL_QUERY_INVALID, $validator->getDescription());
}
$keyId = $cursor->getValue();
$cursorDocument = $dbForPlatform->getDocument('keys', $keyId);
if ($cursorDocument->isEmpty()) {
throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, "Key '{$keyId}' for the 'cursor' value not found.");
}
$cursor->setValue($cursorDocument);
}
$filterQueries = Query::groupByType($queries)['filters'];
$keys = $dbForPlatform->find('keys', $queries);
$response->dynamic(new Document([
'keys' => $keys,
'total' => $includeTotal ? $dbForPlatform->count('keys', $filterQueries, APP_LIMIT_COUNT) : 0,
]), Response::MODEL_KEY_LIST);
});
Http::get('/v1/projects/:projectId/keys/:keyId')
->desc('Get key')
->groups(['api', 'projects'])
->label('scope', 'keys.read')
->label('sdk', new Method(
namespace: 'projects',
group: 'keys',
name: 'getKey',
description: '/docs/references/projects/get-key.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_KEY,
)
]
))
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $keyId, Response $response, Database $dbForPlatform) {
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$key = $dbForPlatform->findOne('keys', [
Query::equal('$id', [$keyId]),
Query::equal('resourceType', ['projects']),
Query::equal('resourceInternalId', [$project->getSequence()]),
]);
if ($key->isEmpty()) {
throw new Exception(Exception::KEY_NOT_FOUND);
}
$response->dynamic($key, Response::MODEL_KEY);
});
Http::put('/v1/projects/:projectId/keys/:keyId')
->desc('Update key')
->groups(['api', 'projects'])
->label('scope', 'keys.write')
->label('sdk', new Method(
namespace: 'projects',
group: 'keys',
name: 'updateKey',
description: '/docs/references/projects/update-key.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_KEY,
)
]
))
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key unique ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Key name. Max length: 128 chars.')
->param('scopes', null, new Nullable(new ArrayList(new WhiteList(array_keys(Config::getParam('projectScopes')), true), APP_LIMIT_ARRAY_PARAMS_SIZE)), 'Key scopes list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.')
->param('expire', null, new Nullable(new DatetimeValidator()), 'Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Use null for unlimited expiration.', true)
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $keyId, string $name, array $scopes, ?string $expire, Response $response, Database $dbForPlatform) {
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$key = $dbForPlatform->findOne('keys', [
Query::equal('$id', [$keyId]),
Query::equal('resourceType', ['projects']),
Query::equal('resourceInternalId', [$project->getSequence()]),
]);
if ($key->isEmpty()) {
throw new Exception(Exception::KEY_NOT_FOUND);
}
$key
->setAttribute('name', $name)
->setAttribute('scopes', $scopes)
->setAttribute('expire', $expire);
$dbForPlatform->updateDocument('keys', $key->getId(), $key);
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
$response->dynamic($key, Response::MODEL_KEY);
});
Http::delete('/v1/projects/:projectId/keys/:keyId')
->desc('Delete key')
->groups(['api', 'projects'])
->label('scope', 'keys.write')
->label('sdk', new Method(
namespace: 'projects',
group: 'keys',
name: 'deleteKey',
description: '/docs/references/projects/delete-key.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_NOCONTENT,
model: Response::MODEL_NONE,
)
],
contentType: ContentType::NONE
))
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $keyId, Response $response, Database $dbForPlatform) {
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$key = $dbForPlatform->findOne('keys', [
Query::equal('$id', [$keyId]),
Query::equal('resourceType', ['projects']),
Query::equal('resourceInternalId', [$project->getSequence()]),
]);
if ($key->isEmpty()) {
throw new Exception(Exception::KEY_NOT_FOUND);
}
$dbForPlatform->deleteDocument('keys', $key->getId());
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
$response->noContent();
});
// JWT Keys
Http::post('/v1/projects/:projectId/jwts')
@@ -1093,272 +801,6 @@ Http::post('/v1/projects/:projectId/jwts')
])]), Response::MODEL_JWT);
});
// Platforms
Http::post('/v1/projects/:projectId/platforms')
->desc('Create platform')
->groups(['api', 'projects'])
->label('audits.event', 'platforms.create')
->label('audits.resource', 'project/{request.projectId}')
->label('scope', 'platforms.write')
->label('sdk', new Method(
namespace: 'projects',
group: 'platforms',
name: 'createPlatform',
description: '/docs/references/projects/create-platform.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_CREATED,
model: Response::MODEL_PLATFORM,
)
]
))
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param(
'type',
null,
new WhiteList([
Platform::TYPE_WEB,
Platform::TYPE_FLUTTER_WEB,
Platform::TYPE_FLUTTER_IOS,
Platform::TYPE_FLUTTER_ANDROID,
Platform::TYPE_FLUTTER_LINUX,
Platform::TYPE_FLUTTER_MACOS,
Platform::TYPE_FLUTTER_WINDOWS,
Platform::TYPE_APPLE_IOS,
Platform::TYPE_APPLE_MACOS,
Platform::TYPE_APPLE_WATCHOS,
Platform::TYPE_APPLE_TVOS,
Platform::TYPE_ANDROID,
Platform::TYPE_UNITY,
Platform::TYPE_REACT_NATIVE_IOS,
Platform::TYPE_REACT_NATIVE_ANDROID,
], true),
'Platform type. Possible values are: web, flutter-web, flutter-ios, flutter-android, flutter-linux, flutter-macos, flutter-windows, apple-ios, apple-macos, apple-watchos, apple-tvos, android, unity, react-native-ios, react-native-android.'
)
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('key', '', new Text(256), 'Package name for Android or bundle ID for iOS or macOS. Max length: 256 chars.', true)
->param('store', '', new Text(256), 'App store or Google Play store ID. Max length: 256 chars.', true)
->param('hostname', '', new Hostname(), 'Platform client hostname. Max length: 256 chars.', true)
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $type, string $name, string $key, string $store, string $hostname, Response $response, Database $dbForPlatform) {
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$platform = new Document([
'$id' => ID::unique(),
'$permissions' => [
Permission::read(Role::any()),
Permission::update(Role::any()),
Permission::delete(Role::any()),
],
'projectInternalId' => $project->getSequence(),
'projectId' => $project->getId(),
'type' => $type,
'name' => $name,
'key' => $key,
'store' => $store,
'hostname' => $hostname
]);
$platform = $dbForPlatform->createDocument('platforms', $platform);
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($platform, Response::MODEL_PLATFORM);
});
Http::get('/v1/projects/:projectId/platforms')
->desc('List platforms')
->groups(['api', 'projects'])
->label('scope', 'platforms.read')
->label('sdk', new Method(
namespace: 'projects',
group: 'platforms',
name: 'listPlatforms',
description: '/docs/references/projects/list-platforms.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_PLATFORM_LIST,
)
]
))
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, bool $includeTotal, Response $response, Database $dbForPlatform) {
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$platforms = $dbForPlatform->find('platforms', [
Query::equal('projectInternalId', [$project->getSequence()]),
Query::limit(5000),
]);
$response->dynamic(new Document([
'platforms' => $platforms,
'total' => $includeTotal ? count($platforms) : 0,
]), Response::MODEL_PLATFORM_LIST);
});
Http::get('/v1/projects/:projectId/platforms/:platformId')
->desc('Get platform')
->groups(['api', 'projects'])
->label('scope', 'platforms.read')
->label('sdk', new Method(
namespace: 'projects',
group: 'platforms',
name: 'getPlatform',
description: '/docs/references/projects/get-platform.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_PLATFORM,
)
]
))
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $platformId, Response $response, Database $dbForPlatform) {
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$platform = $dbForPlatform->findOne('platforms', [
Query::equal('$id', [$platformId]),
Query::equal('projectInternalId', [$project->getSequence()]),
]);
if ($platform->isEmpty()) {
throw new Exception(Exception::PLATFORM_NOT_FOUND);
}
$response->dynamic($platform, Response::MODEL_PLATFORM);
});
Http::put('/v1/projects/:projectId/platforms/:platformId')
->desc('Update platform')
->groups(['api', 'projects'])
->label('scope', 'platforms.write')
->label('sdk', new Method(
namespace: 'projects',
group: 'platforms',
name: 'updatePlatform',
description: '/docs/references/projects/update-platform.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_PLATFORM,
)
]
))
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform unique ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('key', '', new Text(256), 'Package name for android or bundle ID for iOS. Max length: 256 chars.', true)
->param('store', '', new Text(256), 'App store or Google Play store ID. Max length: 256 chars.', true)
->param('hostname', '', new Hostname(), 'Platform client URL. Max length: 256 chars.', true)
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $platformId, string $name, string $key, string $store, string $hostname, Response $response, Database $dbForPlatform) {
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$platform = $dbForPlatform->findOne('platforms', [
Query::equal('$id', [$platformId]),
Query::equal('projectInternalId', [$project->getSequence()]),
]);
if ($platform->isEmpty()) {
throw new Exception(Exception::PLATFORM_NOT_FOUND);
}
$platform
->setAttribute('name', $name)
->setAttribute('key', $key)
->setAttribute('store', $store)
->setAttribute('hostname', $hostname);
$dbForPlatform->updateDocument('platforms', $platform->getId(), $platform);
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
$response->dynamic($platform, Response::MODEL_PLATFORM);
});
Http::delete('/v1/projects/:projectId/platforms/:platformId')
->desc('Delete platform')
->groups(['api', 'projects'])
->label('audits.event', 'platforms.delete')
->label('audits.resource', 'project/{request.projectId}/platform/${request.platformId}')
->label('scope', 'platforms.write')
->label('sdk', new Method(
namespace: 'projects',
group: 'platforms',
name: 'deletePlatform',
description: '/docs/references/projects/delete-platform.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_NOCONTENT,
model: Response::MODEL_NONE,
)
],
contentType: ContentType::NONE
))
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform unique ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->action(function (string $projectId, string $platformId, Response $response, Database $dbForPlatform) {
$project = $dbForPlatform->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$platform = $dbForPlatform->findOne('platforms', [
Query::equal('$id', [$platformId]),
Query::equal('projectInternalId', [$project->getSequence()]),
]);
if ($platform->isEmpty()) {
throw new Exception(Exception::PLATFORM_NOT_FOUND);
}
$dbForPlatform->deleteDocument('platforms', $platformId);
$dbForPlatform->purgeCachedDocument('projects', $project->getId());
$response->noContent();
});
// CUSTOM SMTP and Templates
Http::patch('/v1/projects/:projectId/smtp')
->desc('Update SMTP')
+2
View File
@@ -1008,6 +1008,8 @@ Http::get('/v1/users/:userId/logs')
'userId' => ID::custom($log['data']['userId']),
'userEmail' => $log['data']['userEmail'] ?? null,
'userName' => $log['data']['userName'] ?? null,
'mode' => $log['data']['mode'] ?? null,
'userType' => $log['data']['userType'] ?? null,
'ip' => $log['ip'],
'time' => $log['time'],
'osCode' => $os['osCode'],
+32 -5
View File
@@ -37,6 +37,7 @@ use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\Authorization\Input;
use Utopia\Database\Validator\Roles;
use Utopia\Http\Http;
use Utopia\Span\Span;
use Utopia\System\System;
use Utopia\Telemetry\Adapter as Telemetry;
use Utopia\Validator\WhiteList;
@@ -186,7 +187,7 @@ Http::init()
$user = new User([
'$id' => '',
'status' => true,
'type' => ACTIVITY_TYPE_APP,
'type' => ACTIVITY_TYPE_KEY_PROJECT,
'email' => 'app.' . $project->getId() . '@service.' . $request->getHostname(),
'password' => '',
'name' => $apiKey->getName(),
@@ -256,7 +257,14 @@ Http::init()
}
}
$queueForAudits->setUser($user);
$userClone = clone $user;
$userClone->setAttribute('type', match ($apiKey->getType()) {
API_KEY_STANDARD => ACTIVITY_TYPE_KEY_PROJECT,
API_KEY_ACCOUNT => ACTIVITY_TYPE_KEY_ACCOUNT,
API_KEY_ORGANIZATION => ACTIVITY_TYPE_KEY_ORGANIZATION,
default => ACTIVITY_TYPE_KEY_PROJECT,
});
$queueForAudits->setUser($userClone);
}
// Apply permission
@@ -599,7 +607,9 @@ Http::init()
if (! $user->isEmpty()) {
$userClone = clone $user;
// $user doesn't support `type` and can cause unintended effects.
$userClone->setAttribute('type', ACTIVITY_TYPE_USER);
if (empty($user->getAttribute('type'))) {
$userClone->setAttribute('type', $mode === APP_MODE_ADMIN ? ACTIVITY_TYPE_ADMIN : ACTIVITY_TYPE_USER);
}
$queueForAudits->setUser($userClone);
}
@@ -624,6 +634,7 @@ Http::init()
$isDisabled = isset($plan['imageTransformations']) && $plan['imageTransformations'] === -1 && ! $user->isPrivileged($authorization->getRoles());
$key = $request->cacheIdentifier();
Span::add('storage.cache.key', $key);
$cacheLog = $authorization->skip(fn () => $dbForProject->getDocument('cache', $key));
$cache = new Cache(
new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $project->getId())
@@ -672,6 +683,8 @@ Http::init()
if ($file->isEmpty()) {
throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);
}
Span::add('storage.bucket.id', $bucketId);
Span::add('storage.file.id', $fileId);
// Do not update transformedAt if it's a console user
if (! $user->isPrivileged($authorization->getRoles())) {
$transformedAt = $file->getAttribute('transformedAt', '');
@@ -684,16 +697,27 @@ Http::init()
}
}
$accessedAt = $cacheLog->getAttribute('accessedAt', '');
if (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_CACHE_UPDATE)) > $accessedAt) {
$authorization->skip(fn () => $dbForProject->updateDocument('cache', $cacheLog->getId(), new Document([
'accessedAt' => DateTime::now(),
])));
// Refresh the filesystem file's mtime so TTL-based expiry in cache->load() stays valid
$cache->save($key, $data);
}
$response
->addHeader('Cache-Control', sprintf('private, max-age=%d', $timestamp))
->addHeader('X-Appwrite-Cache', 'hit')
->setContentType($cacheLog->getAttribute('mimeType'));
$storageCacheOperationsCounter->add(1, ['result' => 'hit']);
if (! $isImageTransformation || ! $isDisabled) {
Span::add('storage.cache.hit', true);
$response->send($data);
}
} else {
$storageCacheOperationsCounter->add(1, ['result' => 'miss']);
Span::add('storage.cache.hit', false);
$response
->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
->addHeader('Pragma', 'no-cache')
@@ -781,7 +805,8 @@ Http::shutdown()
->inject('eventProcessor')
->inject('bus')
->inject('apiKey')
->action(function (Http $utopia, Request $request, Response $response, Document $project, User $user, Event $queueForEvents, Audit $queueForAudits, Context $usage, UsagePublisher $publisherForUsage, Delete $queueForDeletes, EventDatabase $queueForDatabase, Build $queueForBuilds, Messaging $queueForMessaging, Func $queueForFunctions, Event $queueForWebhooks, Realtime $queueForRealtime, Database $dbForProject, Authorization $authorization, callable $timelimit, EventProcessor $eventProcessor, Bus $bus, ?Key $apiKey) use ($parseLabel) {
->inject('mode')
->action(function (Http $utopia, Request $request, Response $response, Document $project, User $user, Event $queueForEvents, Audit $queueForAudits, Context $usage, UsagePublisher $publisherForUsage, Delete $queueForDeletes, EventDatabase $queueForDatabase, Build $queueForBuilds, Messaging $queueForMessaging, Func $queueForFunctions, Event $queueForWebhooks, Realtime $queueForRealtime, Database $dbForProject, Authorization $authorization, callable $timelimit, EventProcessor $eventProcessor, Bus $bus, ?Key $apiKey, string $mode) use ($parseLabel) {
$responsePayload = $response->getPayload();
@@ -883,7 +908,9 @@ Http::shutdown()
if (! $user->isEmpty()) {
$userClone = clone $user;
// $user doesn't support `type` and can cause unintended effects.
$userClone->setAttribute('type', ACTIVITY_TYPE_USER);
if (empty($user->getAttribute('type'))) {
$userClone->setAttribute('type', $mode === APP_MODE_ADMIN ? ACTIVITY_TYPE_ADMIN : ACTIVITY_TYPE_USER);
}
$queueForAudits->setUser($userClone);
} elseif ($queueForAudits->getUser() === null || $queueForAudits->getUser()->isEmpty()) {
/**
+4 -1
View File
@@ -156,9 +156,12 @@ const SESSION_PROVIDER_SERVER = 'server';
/**
* Activity associated with user or the app.
*/
const ACTIVITY_TYPE_APP = 'app';
const ACTIVITY_TYPE_USER = 'user';
const ACTIVITY_TYPE_ADMIN = 'admin';
const ACTIVITY_TYPE_GUEST = 'guest';
const ACTIVITY_TYPE_KEY_PROJECT = 'keyProject';
const ACTIVITY_TYPE_KEY_ACCOUNT = 'keyAccount';
const ACTIVITY_TYPE_KEY_ORGANIZATION = 'keyOrganization';
/**
* MFA
+8 -1
View File
@@ -1,5 +1,6 @@
<?php
use Appwrite\Network\Platform;
use Appwrite\OpenSSL\OpenSSL;
use Utopia\Database\Database;
use Utopia\Database\Document;
@@ -123,11 +124,17 @@ Database::addFilter(
return;
},
function (mixed $value, Document $document, Database $database) {
return $database->getAuthorization()->skip(fn () => $database
$platforms = $database->getAuthorization()->skip(fn () => $database
->find('platforms', [
Query::equal('projectInternalId', [$document->getSequence()]),
Query::limit(APP_LIMIT_SUBQUERY),
]));
foreach ($platforms as $platform) {
$platform->setAttribute('type', Platform::mapDeprecatedType($platform->getAttribute('type')));
}
return $platforms;
}
);
+12 -3
View File
@@ -106,7 +106,12 @@ use Appwrite\Utopia\Response\Model\Mock;
use Appwrite\Utopia\Response\Model\MockNumber;
use Appwrite\Utopia\Response\Model\None;
use Appwrite\Utopia\Response\Model\Phone;
use Appwrite\Utopia\Response\Model\Platform;
use Appwrite\Utopia\Response\Model\PlatformAndroid;
use Appwrite\Utopia\Response\Model\PlatformApple;
use Appwrite\Utopia\Response\Model\PlatformLinux;
use Appwrite\Utopia\Response\Model\PlatformList;
use Appwrite\Utopia\Response\Model\PlatformWeb;
use Appwrite\Utopia\Response\Model\PlatformWindows;
use Appwrite\Utopia\Response\Model\Preferences;
use Appwrite\Utopia\Response\Model\Project;
use Appwrite\Utopia\Response\Model\Provider;
@@ -197,7 +202,6 @@ Response::setModel(new BaseList('Webhooks List', Response::MODEL_WEBHOOK_LIST, '
Response::setModel(new BaseList('API Keys List', Response::MODEL_KEY_LIST, 'keys', Response::MODEL_KEY, true, true));
Response::setModel(new BaseList('Dev Keys List', Response::MODEL_DEV_KEY_LIST, 'devKeys', Response::MODEL_DEV_KEY, true, false));
Response::setModel(new BaseList('Auth Providers List', Response::MODEL_AUTH_PROVIDER_LIST, 'platforms', Response::MODEL_AUTH_PROVIDER, true, false));
Response::setModel(new BaseList('Platforms List', Response::MODEL_PLATFORM_LIST, 'platforms', Response::MODEL_PLATFORM, true, false));
Response::setModel(new BaseList('Countries List', Response::MODEL_COUNTRY_LIST, 'countries', Response::MODEL_COUNTRY));
Response::setModel(new BaseList('Continents List', Response::MODEL_CONTINENT_LIST, 'continents', Response::MODEL_CONTINENT));
Response::setModel(new BaseList('Languages List', Response::MODEL_LANGUAGE_LIST, 'languages', Response::MODEL_LANGUAGE));
@@ -333,7 +337,12 @@ Response::setModel(new Key());
Response::setModel(new DevKey());
Response::setModel(new MockNumber());
Response::setModel(new AuthProvider());
Response::setModel(new Platform());
Response::setModel(new PlatformWeb());
Response::setModel(new PlatformApple());
Response::setModel(new PlatformAndroid());
Response::setModel(new PlatformWindows());
Response::setModel(new PlatformLinux());
Response::setModel(new PlatformList());
Response::setModel(new Variable());
Response::setModel(new Country());
Response::setModel(new Continent());
+26 -4
View File
@@ -1306,11 +1306,12 @@ return function (Container $container): void {
$dsn = new DSN('mysql://' . $project->getAttribute('database'));
}
$pool = $pools->get($databaseDSN->getHost());
$databaseHost = $databaseDSN->getHost();
$pool = $pools->get($databaseHost);
$adapter = new DatabasePool($pool);
$database = new Database($adapter, $cache);
$sharedTables = \explode(',', System::getEnv('_APP_DATABASE_SHARED_TABLES', ''));
$sharedTables = \array_filter(\explode(',', System::getEnv('_APP_DATABASE_SHARED_TABLES', '')));
$database
->setDatabase(APP_DATABASE)
@@ -1321,10 +1322,31 @@ return function (Container $container): void {
->setMaxQueryValues(APP_DATABASE_QUERY_MAX_VALUES);
// inside pools authorization needs to be set first
$database->getAdapter()->setSupportForAttributes($databaseType !== DOCUMENTSDB);
if (\in_array($dsn->getHost(), $sharedTables)) {
// For separate pools (documentsdb/vectorsdb), check their own shared tables config.
// If not configured, use dedicated mode to avoid cross-engine tenant type mismatches.
if ($databaseHost !== $dsn->getHost()) {
$dbTypeSharedTables = match ($databaseType) {
DOCUMENTSDB => \array_filter(\explode(',', System::getEnv('_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES', ''))),
VECTORSDB => \array_filter(\explode(',', System::getEnv('_APP_DATABASE_VECTORSDB_SHARED_TABLES', ''))),
default => [],
};
if (\in_array($databaseHost, $dbTypeSharedTables)) {
$database
->setSharedTables(true)
->setTenant($project->getSequence())
->setNamespace($databaseDSN->getParam('namespace'));
} else {
$database
->setSharedTables(false)
->setTenant(null)
->setNamespace('_' . $project->getSequence());
}
} elseif (\in_array($dsn->getHost(), $sharedTables)) {
$database
->setSharedTables(true)
->setTenant((int) $project->getSequence())
->setTenant($project->getSequence())
->setNamespace($dsn->getParam('namespace'));
} else {
$database
+25 -4
View File
@@ -202,7 +202,8 @@ return function (Container $container): void {
}
$pools = $register->get('pools');
$pool = $pools->get($databaseDSN->getHost());
$databaseHost = $databaseDSN->getHost();
$pool = $pools->get($databaseHost);
$adapter = new DatabasePool($pool);
$database = new Database($adapter, $cache);
@@ -211,12 +212,32 @@ return function (Container $container): void {
->setAuthorization($authorization);
$database->getAdapter()->setSupportForAttributes($databaseType !== DOCUMENTSDB);
$sharedTables = \explode(',', System::getEnv('_APP_DATABASE_SHARED_TABLES', ''));
$sharedTables = \array_filter(\explode(',', System::getEnv('_APP_DATABASE_SHARED_TABLES', '')));
if (\in_array($dsn->getHost(), $sharedTables, true)) {
// For separate pools (documentsdb/vectorsdb), check their own shared tables config.
// If not configured, use dedicated mode to avoid cross-engine tenant type mismatches.
if ($databaseHost !== $dsn->getHost()) {
$dbTypeSharedTables = match ($databaseType) {
DOCUMENTSDB => \array_filter(\explode(',', System::getEnv('_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES', ''))),
VECTORSDB => \array_filter(\explode(',', System::getEnv('_APP_DATABASE_VECTORSDB_SHARED_TABLES', ''))),
default => [],
};
if (\in_array($databaseHost, $dbTypeSharedTables)) {
$database
->setSharedTables(true)
->setTenant($projectDocument->getSequence())
->setNamespace($databaseDSN->getParam('namespace'));
} else {
$database
->setSharedTables(false)
->setTenant(null)
->setNamespace('_' . $projectDocument->getSequence());
}
} elseif (\in_array($dsn->getHost(), $sharedTables, true)) {
$database
->setSharedTables(true)
->setTenant((int) $projectDocument->getSequence())
->setTenant($projectDocument->getSequence())
->setNamespace($dsn->getParam('namespace'));
} else {
$database
+2
View File
@@ -1,9 +1,11 @@
<?php
use Appwrite\Bus\Listeners\Log;
use Appwrite\Bus\Listeners\Mails;
use Appwrite\Bus\Listeners\Usage;
return [
new Log(),
new Mails(),
new Usage(),
];
+29
View File
@@ -532,6 +532,35 @@ $hostPath = rtrim($this->getParam('hostPath', ''), '/');
- _APP_DB_ADAPTER
- _APP_LOGGING_CONFIG
appwrite-worker-executions:
image: <?php echo $organization; ?>/<?php echo $image; ?>:<?php echo $version."\n"; ?>
entrypoint: worker-executions
<<: *x-logging
container_name: appwrite-worker-executions
restart: unless-stopped
networks:
- appwrite
depends_on:
redis:
condition: service_healthy
<?= $dbService ?>:
condition: service_healthy
environment:
- _APP_ENV
- _APP_WORKER_PER_CORE
- _APP_REDIS_HOST
- _APP_REDIS_PORT
- _APP_REDIS_USER
- _APP_REDIS_PASS
- _APP_ENV
- _APP_DB_ADAPTER
- _APP_DB_HOST
- _APP_DB_PORT
- _APP_DB_SCHEMA
- _APP_DB_USER
- _APP_DB_PASS
- _APP_LOGGING_CONFIG
appwrite-worker-functions:
image: <?php echo $organization; ?>/<?php echo $image; ?>:<?php echo $version."\n"; ?>
entrypoint: worker-functions
+1 -1
View File
@@ -67,7 +67,7 @@
"utopia-php/emails": "0.6.*",
"utopia-php/dns": "1.6.*",
"utopia-php/dsn": "0.2.1",
"utopia-php/framework": "0.34.*",
"utopia-php/http": "0.34.*",
"utopia-php/fetch": "0.5.*",
"utopia-php/image": "0.8.*",
"utopia-php/locale": "0.8.*",
Generated
+75 -145
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "e9c38bbebc60849e70e3640aaa4422cd",
"content-hash": "4fb974e9843f6104e40396e7cad4a833",
"packages": [
{
"name": "adhocore/jwt",
@@ -2708,16 +2708,16 @@
},
{
"name": "symfony/http-client",
"version": "v7.4.7",
"version": "v7.4.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/http-client.git",
"reference": "1010624285470eb60e88ed10035102c75b4ea6af"
"reference": "01933e626c3de76bea1e22641e205e78f6a34342"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/http-client/zipball/1010624285470eb60e88ed10035102c75b4ea6af",
"reference": "1010624285470eb60e88ed10035102c75b4ea6af",
"url": "https://api.github.com/repos/symfony/http-client/zipball/01933e626c3de76bea1e22641e205e78f6a34342",
"reference": "01933e626c3de76bea1e22641e205e78f6a34342",
"shasum": ""
},
"require": {
@@ -2785,7 +2785,7 @@
"http"
],
"support": {
"source": "https://github.com/symfony/http-client/tree/v7.4.7"
"source": "https://github.com/symfony/http-client/tree/v7.4.8"
},
"funding": [
{
@@ -2805,7 +2805,7 @@
"type": "tidelift"
}
],
"time": "2026-03-05T11:16:58+00:00"
"time": "2026-03-30T12:55:43+00:00"
},
{
"name": "symfony/http-client-contracts",
@@ -3850,16 +3850,16 @@
},
{
"name": "utopia-php/database",
"version": "5.3.17",
"version": "5.3.19",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/database.git",
"reference": "cff2b6ed63d3291b74110d086e16ff089fe05993"
"reference": "72ee1614c37e37c7fdd9d4dc87f1f7cdfa1ca691"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/database/zipball/cff2b6ed63d3291b74110d086e16ff089fe05993",
"reference": "cff2b6ed63d3291b74110d086e16ff089fe05993",
"url": "https://api.github.com/repos/utopia-php/database/zipball/72ee1614c37e37c7fdd9d4dc87f1f7cdfa1ca691",
"reference": "72ee1614c37e37c7fdd9d4dc87f1f7cdfa1ca691",
"shasum": ""
},
"require": {
@@ -3903,9 +3903,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/database/issues",
"source": "https://github.com/utopia-php/database/tree/5.3.17"
"source": "https://github.com/utopia-php/database/tree/5.3.19"
},
"time": "2026-03-20T01:18:52+00:00"
"time": "2026-03-31T15:52:08+00:00"
},
{
"name": "utopia-php/detector",
@@ -4269,72 +4269,18 @@
},
"time": "2025-12-18T16:25:10+00:00"
},
{
"name": "utopia-php/framework",
"version": "0.34.17",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/http.git",
"reference": "d3e4143b8b06d9823d0c29a06dacefa5a1b93677"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/http/zipball/d3e4143b8b06d9823d0c29a06dacefa5a1b93677",
"reference": "d3e4143b8b06d9823d0c29a06dacefa5a1b93677",
"shasum": ""
},
"require": {
"ext-swoole": "*",
"php": ">=8.2",
"utopia-php/compression": "0.1.*",
"utopia-php/di": "0.3.*",
"utopia-php/servers": "0.3.*",
"utopia-php/telemetry": "0.2.*",
"utopia-php/validators": "0.2.*"
},
"require-dev": {
"doctrine/instantiator": "^1.5",
"laravel/pint": "1.*",
"phpbench/phpbench": "^1.2",
"phpstan/phpstan": "1.*",
"phpunit/phpunit": "^9.5.25",
"swoole/ide-helper": "4.8.3"
},
"type": "library",
"autoload": {
"psr-4": {
"Utopia\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "A simple, light and advanced PHP HTTP framework",
"keywords": [
"framework",
"http",
"php",
"upf"
],
"support": {
"issues": "https://github.com/utopia-php/http/issues",
"source": "https://github.com/utopia-php/http/tree/0.34.17"
},
"time": "2026-04-06T04:40:23+00:00"
},
{
"name": "utopia-php/http",
"version": "0.34.16",
"version": "0.34.19",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/http.git",
"reference": "2b4021ba3f9d476264ce9fd6703d6c79de9add7f"
"reference": "995c119f31866cacd42d63b1f922bf86eabb396c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/http/zipball/2b4021ba3f9d476264ce9fd6703d6c79de9add7f",
"reference": "2b4021ba3f9d476264ce9fd6703d6c79de9add7f",
"url": "https://api.github.com/repos/utopia-php/http/zipball/995c119f31866cacd42d63b1f922bf86eabb396c",
"reference": "995c119f31866cacd42d63b1f922bf86eabb396c",
"shasum": ""
},
"require": {
@@ -4373,9 +4319,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/http/issues",
"source": "https://github.com/utopia-php/http/tree/0.34.16"
"source": "https://github.com/utopia-php/http/tree/0.34.19"
},
"time": "2026-03-20T10:39:07+00:00"
"time": "2026-04-08T10:23:17+00:00"
},
{
"name": "utopia-php/image",
@@ -4696,16 +4642,16 @@
},
{
"name": "utopia-php/platform",
"version": "0.12.0",
"version": "0.12.1",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/platform.git",
"reference": "068ee46228f0c3972e6b569f2c86b6c80fe583d8"
"reference": "2a6b88168b3a99d4d7d3b37d927f2cb91da5e0fc"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/platform/zipball/068ee46228f0c3972e6b569f2c86b6c80fe583d8",
"reference": "068ee46228f0c3972e6b569f2c86b6c80fe583d8",
"url": "https://api.github.com/repos/utopia-php/platform/zipball/2a6b88168b3a99d4d7d3b37d927f2cb91da5e0fc",
"reference": "2a6b88168b3a99d4d7d3b37d927f2cb91da5e0fc",
"shasum": ""
},
"require": {
@@ -4741,9 +4687,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/platform/issues",
"source": "https://github.com/utopia-php/platform/tree/0.12.0"
"source": "https://github.com/utopia-php/platform/tree/0.12.1"
},
"time": "2026-03-31T14:44:23+00:00"
"time": "2026-04-08T04:11:31+00:00"
},
{
"name": "utopia-php/pools",
@@ -5502,16 +5448,16 @@
"packages-dev": [
{
"name": "appwrite/sdk-generator",
"version": "1.14.0",
"version": "1.17.7",
"source": {
"type": "git",
"url": "https://github.com/appwrite/sdk-generator.git",
"reference": "7e7e257b10a8c1384a237e7d8d73452e2108901e"
"reference": "291471d04c3f0e7b9fcc46668a6255a4c0f2947e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/appwrite/sdk-generator/zipball/7e7e257b10a8c1384a237e7d8d73452e2108901e",
"reference": "7e7e257b10a8c1384a237e7d8d73452e2108901e",
"url": "https://api.github.com/repos/appwrite/sdk-generator/zipball/291471d04c3f0e7b9fcc46668a6255a4c0f2947e",
"reference": "291471d04c3f0e7b9fcc46668a6255a4c0f2947e",
"shasum": ""
},
"require": {
@@ -5547,22 +5493,22 @@
"description": "Appwrite PHP library for generating API SDKs for multiple programming languages and platforms",
"support": {
"issues": "https://github.com/appwrite/sdk-generator/issues",
"source": "https://github.com/appwrite/sdk-generator/tree/1.14.0"
"source": "https://github.com/appwrite/sdk-generator/tree/1.17.7"
},
"time": "2026-03-26T12:50:11+00:00"
"time": "2026-04-08T08:51:05+00:00"
},
{
"name": "brianium/paratest",
"version": "v7.19.2",
"version": "v7.20.0",
"source": {
"type": "git",
"url": "https://github.com/paratestphp/paratest.git",
"reference": "66e4f7910cecf67736bccf2b8bd53a2e3eb98bd9"
"reference": "81c80677c9ec0ed4ef16b246167f11dec81a6e3d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paratestphp/paratest/zipball/66e4f7910cecf67736bccf2b8bd53a2e3eb98bd9",
"reference": "66e4f7910cecf67736bccf2b8bd53a2e3eb98bd9",
"url": "https://api.github.com/repos/paratestphp/paratest/zipball/81c80677c9ec0ed4ef16b246167f11dec81a6e3d",
"reference": "81c80677c9ec0ed4ef16b246167f11dec81a6e3d",
"shasum": ""
},
"require": {
@@ -5586,7 +5532,7 @@
"ext-pcntl": "*",
"ext-pcov": "*",
"ext-posix": "*",
"phpstan/phpstan": "^2.1.40",
"phpstan/phpstan": "^2.1.44",
"phpstan/phpstan-deprecation-rules": "^2.0.4",
"phpstan/phpstan-phpunit": "^2.0.16",
"phpstan/phpstan-strict-rules": "^2.0.10",
@@ -5630,7 +5576,7 @@
],
"support": {
"issues": "https://github.com/paratestphp/paratest/issues",
"source": "https://github.com/paratestphp/paratest/tree/v7.19.2"
"source": "https://github.com/paratestphp/paratest/tree/v7.20.0"
},
"funding": [
{
@@ -5642,7 +5588,7 @@
"type": "paypal"
}
],
"time": "2026-03-09T14:33:17+00:00"
"time": "2026-03-29T15:46:14+00:00"
},
{
"name": "czproject/git-php",
@@ -6258,11 +6204,11 @@
},
{
"name": "phpstan/phpstan",
"version": "2.1.44",
"version": "2.1.46",
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/4a88c083c668b2c364a425c9b3171b2d9ea5d218",
"reference": "4a88c083c668b2c364a425c9b3171b2d9ea5d218",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/a193923fc2d6325ef4e741cf3af8c3e8f54dbf25",
"reference": "a193923fc2d6325ef4e741cf3af8c3e8f54dbf25",
"shasum": ""
},
"require": {
@@ -6307,7 +6253,7 @@
"type": "github"
}
],
"time": "2026-03-25T17:34:21+00:00"
"time": "2026-04-01T09:25:14+00:00"
},
{
"name": "phpunit/php-code-coverage",
@@ -6657,16 +6603,16 @@
},
{
"name": "phpunit/phpunit",
"version": "12.5.14",
"version": "12.5.17",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "47283cfd98d553edcb1353591f4e255dc1bb61f0"
"reference": "85b62adab1a340982df64e66daa4a4435eb5723b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/47283cfd98d553edcb1353591f4e255dc1bb61f0",
"reference": "47283cfd98d553edcb1353591f4e255dc1bb61f0",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/85b62adab1a340982df64e66daa4a4435eb5723b",
"reference": "85b62adab1a340982df64e66daa4a4435eb5723b",
"shasum": ""
},
"require": {
@@ -6688,7 +6634,7 @@
"sebastian/cli-parser": "^4.2.0",
"sebastian/comparator": "^7.1.4",
"sebastian/diff": "^7.0.0",
"sebastian/environment": "^8.0.3",
"sebastian/environment": "^8.0.4",
"sebastian/exporter": "^7.0.2",
"sebastian/global-state": "^8.0.2",
"sebastian/object-enumerator": "^7.0.0",
@@ -6735,31 +6681,15 @@
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.14"
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.17"
},
"funding": [
{
"url": "https://phpunit.de/sponsors.html",
"type": "custom"
},
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
},
{
"url": "https://liberapay.com/sebastianbergmann",
"type": "liberapay"
},
{
"url": "https://thanks.dev/u/gh/sebastianbergmann",
"type": "thanks_dev"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpunit/phpunit",
"type": "tidelift"
"url": "https://phpunit.de/sponsoring.html",
"type": "other"
}
],
"time": "2026-02-18T12:38:40+00:00"
"time": "2026-04-08T03:04:19+00:00"
},
{
"name": "sebastian/cli-parser",
@@ -6832,16 +6762,16 @@
},
{
"name": "sebastian/comparator",
"version": "7.1.4",
"version": "7.1.5",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/comparator.git",
"reference": "6a7de5df2e094f9a80b40a522391a7e6022df5f6"
"reference": "c284f55811f43d555e51e8e5c166ac40d3e33c63"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/6a7de5df2e094f9a80b40a522391a7e6022df5f6",
"reference": "6a7de5df2e094f9a80b40a522391a7e6022df5f6",
"url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/c284f55811f43d555e51e8e5c166ac40d3e33c63",
"reference": "c284f55811f43d555e51e8e5c166ac40d3e33c63",
"shasum": ""
},
"require": {
@@ -6900,7 +6830,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/comparator/issues",
"security": "https://github.com/sebastianbergmann/comparator/security/policy",
"source": "https://github.com/sebastianbergmann/comparator/tree/7.1.4"
"source": "https://github.com/sebastianbergmann/comparator/tree/7.1.5"
},
"funding": [
{
@@ -6920,7 +6850,7 @@
"type": "tidelift"
}
],
"time": "2026-01-24T09:28:48+00:00"
"time": "2026-04-08T04:43:00+00:00"
},
{
"name": "sebastian/complexity",
@@ -7744,16 +7674,16 @@
},
{
"name": "symfony/console",
"version": "v8.0.7",
"version": "v8.0.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/console.git",
"reference": "15ed9008a4ebe2d6a78e4937f74e0c13ef2e618a"
"reference": "5b66d385dc58f69652e56f78a4184615e3f2b7f7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/console/zipball/15ed9008a4ebe2d6a78e4937f74e0c13ef2e618a",
"reference": "15ed9008a4ebe2d6a78e4937f74e0c13ef2e618a",
"url": "https://api.github.com/repos/symfony/console/zipball/5b66d385dc58f69652e56f78a4184615e3f2b7f7",
"reference": "5b66d385dc58f69652e56f78a4184615e3f2b7f7",
"shasum": ""
},
"require": {
@@ -7810,7 +7740,7 @@
"terminal"
],
"support": {
"source": "https://github.com/symfony/console/tree/v8.0.7"
"source": "https://github.com/symfony/console/tree/v8.0.8"
},
"funding": [
{
@@ -7830,7 +7760,7 @@
"type": "tidelift"
}
],
"time": "2026-03-06T14:06:22+00:00"
"time": "2026-03-30T15:14:47+00:00"
},
{
"name": "symfony/polyfill-ctype",
@@ -8164,16 +8094,16 @@
},
{
"name": "symfony/process",
"version": "v8.0.5",
"version": "v8.0.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/process.git",
"reference": "b5f3aa6762e33fd95efbaa2ec4f4bc9fdd16d674"
"reference": "cb8939aff03470d1a9d1d1b66d08c6fa71b3bbdc"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/process/zipball/b5f3aa6762e33fd95efbaa2ec4f4bc9fdd16d674",
"reference": "b5f3aa6762e33fd95efbaa2ec4f4bc9fdd16d674",
"url": "https://api.github.com/repos/symfony/process/zipball/cb8939aff03470d1a9d1d1b66d08c6fa71b3bbdc",
"reference": "cb8939aff03470d1a9d1d1b66d08c6fa71b3bbdc",
"shasum": ""
},
"require": {
@@ -8205,7 +8135,7 @@
"description": "Executes commands in sub-processes",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/process/tree/v8.0.5"
"source": "https://github.com/symfony/process/tree/v8.0.8"
},
"funding": [
{
@@ -8225,20 +8155,20 @@
"type": "tidelift"
}
],
"time": "2026-01-26T15:08:38+00:00"
"time": "2026-03-30T15:14:47+00:00"
},
{
"name": "symfony/string",
"version": "v8.0.6",
"version": "v8.0.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/string.git",
"reference": "6c9e1108041b5dce21a9a4984b531c4923aa9ec4"
"reference": "ae9488f874d7603f9d2dfbf120203882b645d963"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/string/zipball/6c9e1108041b5dce21a9a4984b531c4923aa9ec4",
"reference": "6c9e1108041b5dce21a9a4984b531c4923aa9ec4",
"url": "https://api.github.com/repos/symfony/string/zipball/ae9488f874d7603f9d2dfbf120203882b645d963",
"reference": "ae9488f874d7603f9d2dfbf120203882b645d963",
"shasum": ""
},
"require": {
@@ -8295,7 +8225,7 @@
"utf8"
],
"support": {
"source": "https://github.com/symfony/string/tree/v8.0.6"
"source": "https://github.com/symfony/string/tree/v8.0.8"
},
"funding": [
{
@@ -8315,7 +8245,7 @@
"type": "tidelift"
}
],
"time": "2026-02-09T10:14:57+00:00"
"time": "2026-03-30T15:14:47+00:00"
},
{
"name": "textalk/websocket",
+320
View File
@@ -0,0 +1,320 @@
<?php
namespace Appwrite\Auth\OAuth2;
use Appwrite\Auth\OAuth2;
use Appwrite\OpenSSL\OpenSSL;
use Utopia\System\System;
// Reference Material
// https://docs.x.com/fundamentals/authentication/oauth-2-0/authorization-code
// https://docs.x.com/x-api/users/get-me
class X extends OAuth2
{
private const PKCE_STATE_KEY = '_pkce';
/**
* @var array
*/
protected array $user = [];
/**
* @var array
*/
protected array $tokens = [];
/**
* @var array
*/
protected array $scopes = [
'tweet.read',
'users.read',
'users.email',
'offline.access',
];
/**
* @var string
*/
private string $pkceVerifier = '';
/**
* @return string
*/
public function getName(): string
{
return 'x';
}
public function getLoginURL(): string
{
$state = $this->state;
$state[self::PKCE_STATE_KEY] = $this->encryptPKCEVerifier($this->getPKCEVerifier());
return 'https://x.com/i/oauth2/authorize?' . \http_build_query([
'response_type' => 'code',
'client_id' => $this->appID,
'redirect_uri' => $this->callback,
'scope' => \implode(' ', $this->getScopes()),
'state' => $this->base64UrlEncode(\json_encode($state, JSON_THROW_ON_ERROR)),
'code_challenge' => $this->getPKCEChallenge(),
'code_challenge_method' => 'S256',
]);
}
/**
* @param string $code
*
* @return array
*/
protected function getTokens(string $code): array
{
if (empty($this->tokens)) {
$this->tokens = $this->decodeJsonObject($this->request(
'POST',
'https://api.x.com/2/oauth2/token',
$this->tokenEndpointHeaders(),
\http_build_query([
'code' => $code,
'client_id' => $this->appID,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->callback,
'code_verifier' => $this->getPKCEVerifier(),
])
));
}
return $this->tokens;
}
/**
* @param string $refreshToken
*
* @return array
*/
public function refreshTokens(string $refreshToken): array
{
$this->tokens = $this->decodeJsonObject($this->request(
'POST',
'https://api.x.com/2/oauth2/token',
$this->tokenEndpointHeaders(),
\http_build_query([
'client_id' => $this->appID,
'refresh_token' => $refreshToken,
'grant_type' => 'refresh_token',
])
));
if (empty($this->tokens['refresh_token'])) {
$this->tokens['refresh_token'] = $refreshToken;
}
return $this->tokens;
}
/**
* @param string $accessToken
*
* @return string
*/
public function getUserID(string $accessToken): string
{
$user = $this->getUser($accessToken);
return $user['data']['id'] ?? '';
}
/**
* @param string $accessToken
*
* @return string
*/
public function getUserEmail(string $accessToken): string
{
$user = $this->getUser($accessToken);
return $user['data']['confirmed_email'] ?? '';
}
/**
* Check if the OAuth email is verified.
*
* X returns a confirmed email only when the app has email access enabled
* and the authenticated user has a confirmed email address.
*
* @param string $accessToken
*
* @return bool
*/
public function isEmailVerified(string $accessToken): bool
{
return !empty($this->getUserEmail($accessToken));
}
/**
* @param string $accessToken
*
* @return string
*/
public function getUserName(string $accessToken): string
{
$user = $this->getUser($accessToken);
return $user['data']['name'] ?? '';
}
/**
* @param string $accessToken
*
* @return array
*/
protected function getUser(string $accessToken): array
{
if (empty($this->user)) {
$this->user = $this->decodeJsonObject($this->request(
'GET',
'https://api.x.com/2/users/me?user.fields=confirmed_email',
['Authorization: Bearer ' . $accessToken]
));
}
return $this->user;
}
/**
* @return array<string, mixed>|null
*/
public function parseState(string $state): ?array
{
$decoded = $this->base64UrlDecode($state);
if ($decoded === false) {
return null;
}
$parsed = \json_decode($decoded, true);
if (!\is_array($parsed)) {
return null;
}
$pkce = $parsed[self::PKCE_STATE_KEY] ?? null;
if (\is_array($pkce)) {
$this->pkceVerifier = $this->decryptPKCEVerifier($pkce);
}
unset($parsed[self::PKCE_STATE_KEY]);
return $parsed;
}
/**
* @return list<string>
*/
private function tokenEndpointHeaders(): array
{
return [
'Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret),
'Content-Type: application/x-www-form-urlencoded',
];
}
/**
* @return array<string, mixed>
*/
private function decodeJsonObject(string $json): array
{
$decoded = \json_decode($json, true);
return \is_array($decoded) ? $decoded : [];
}
private function getPKCEVerifier(): string
{
if ($this->pkceVerifier === '') {
$this->pkceVerifier = $this->base64UrlEncode(\random_bytes(64));
}
return $this->pkceVerifier;
}
private function getPKCEChallenge(): string
{
return $this->base64UrlEncode(\hash('sha256', $this->getPKCEVerifier(), true));
}
private function encryptPKCEVerifier(string $verifier): array
{
$iv = OpenSSL::randomPseudoBytes(OpenSSL::cipherIVLength(OpenSSL::CIPHER_AES_128_GCM));
$key = $this->getPKCEStateKey();
$tag = null;
$data = OpenSSL::encrypt($verifier, OpenSSL::CIPHER_AES_128_GCM, $key, OPENSSL_RAW_DATA, $iv, $tag);
if ($data === false || $tag === null) {
throw new \Exception('Failed to encrypt PKCE verifier.');
}
return [
'data' => $this->base64UrlEncode($data),
'iv' => \bin2hex($iv),
'tag' => \bin2hex($tag),
];
}
private function decryptPKCEVerifier(array $payload): string
{
$data = $payload['data'] ?? '';
$iv = $payload['iv'] ?? '';
$tag = $payload['tag'] ?? '';
if ($data === '' || $iv === '' || $tag === '') {
return '';
}
$decodedData = $this->base64UrlDecode($data);
$decodedIv = \hex2bin($iv);
$decodedTag = \hex2bin($tag);
if ($decodedData === false || $decodedIv === false || $decodedTag === false) {
return '';
}
return OpenSSL::decrypt(
$decodedData,
OpenSSL::CIPHER_AES_128_GCM,
$this->getPKCEStateKey(),
OPENSSL_RAW_DATA,
$decodedIv,
$decodedTag
) ?: '';
}
private function getPKCEStateKey(): string
{
$key = System::getEnv('_APP_OPENSSL_KEY_V1', '');
if ($key === '') {
throw new \Exception('X OAuth2 requires _APP_OPENSSL_KEY_V1 to encrypt PKCE state.');
}
return $key;
}
private function base64UrlEncode(string $value): string
{
return \rtrim(\strtr(\base64_encode($value), '+/', '-_'), '=');
}
private function base64UrlDecode(string $value): string|false
{
$padding = \strlen($value) % 4;
if ($padding > 0) {
$value .= \str_repeat('=', 4 - $padding);
}
return \base64_decode(\strtr($value, '-_', '+/'), true);
}
}
@@ -0,0 +1,21 @@
<?php
namespace Appwrite\Bus\Events;
use Utopia\Bus\Event;
class SessionCreated implements Event
{
/**
* @param array<string, mixed> $user
* @param array<string, mixed> $project
* @param array<string, mixed> $session
*/
public function __construct(
public readonly array $user,
public readonly array $project,
public readonly array $session,
public readonly string $locale,
) {
}
}
+154
View File
@@ -0,0 +1,154 @@
<?php
namespace Appwrite\Bus\Listeners;
use Appwrite\Auth\MFA\Type;
use Appwrite\Bus\Events\SessionCreated;
use Appwrite\Event\Mail;
use Appwrite\Template\Template;
use Utopia\Bus\Listener;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Query;
use Utopia\Locale\Locale;
use Utopia\Queue\Publisher;
use Utopia\Storage\Validator\FileName;
use Utopia\System\System;
class Mails extends Listener
{
public static function getName(): string
{
return 'mails';
}
public static function getEvents(): array
{
return [SessionCreated::class];
}
public function __construct()
{
$this
->desc('Sends session alert emails')
->inject('publisher')
->inject('locale')
->inject('platform')
->inject('dbForProject')
->callback($this->handle(...));
}
public function handle(SessionCreated $event, Publisher $publisher, Locale $locale, array $platform, Database $dbForProject): void
{
$project = new Document($event->project);
if (!($project->getAttribute('auths', [])['sessionAlerts'] ?? false)) {
return;
}
if (empty($event->user['email'])) {
return;
}
$provider = $event->session['provider'] ?? '';
$factors = $event->session['factors'] ?? [];
if (\in_array($provider, [SESSION_PROVIDER_MAGIC_URL, SESSION_PROVIDER_TOKEN]) && \in_array(Type::EMAIL, $factors)) {
return;
}
if ($dbForProject->count('sessions', [Query::equal('userId', [$event->user['$id']])]) === 1) {
return;
}
$locale->setDefault($event->locale);
$session = new Document($event->session);
$smtp = $project->getAttribute('smtp', []);
$smtpBaseTemplate = $project->getAttribute('smtpBaseTemplate', 'email-base');
if (!(new FileName())->isValid($smtpBaseTemplate)) {
throw new \Exception('Invalid template path');
}
$customTemplate = $project->getAttribute('templates', [])["email.sessionAlert-$event->locale"] ?? [];
$isBranded = $smtpBaseTemplate === APP_BRANDED_EMAIL_BASE_TEMPLATE;
$subject = $customTemplate['subject'] ?? $locale->getText('emails.sessionAlert.subject');
$preview = $locale->getText('emails.sessionAlert.preview');
$body = empty($customTemplate['message'])
? Template::fromFile(__DIR__ . '/../../../../app/config/locale/templates/email-session-alert.tpl')
->setParam('{{hello}}', $locale->getText('emails.sessionAlert.hello'))
->setParam('{{body}}', $locale->getText('emails.sessionAlert.body'))
->setParam('{{listDevice}}', $locale->getText('emails.sessionAlert.listDevice'))
->setParam('{{listIpAddress}}', $locale->getText('emails.sessionAlert.listIpAddress'))
->setParam('{{listCountry}}', $locale->getText('emails.sessionAlert.listCountry'))
->setParam('{{footer}}', $locale->getText('emails.sessionAlert.footer'))
->setParam('{{thanks}}', $locale->getText('emails.sessionAlert.thanks'))
->setParam('{{signature}}', $locale->getText('emails.sessionAlert.signature'))
->render()
: $customTemplate['message'];
$clientName = $session->getAttribute('clientName')
?: ($session->getAttribute('userAgent') ?: 'UNKNOWN');
$projectName = $project->getId() === 'console'
? $platform['platformName']
: $project->getAttribute('name');
$emailVariables = [
'direction' => $locale->getText('settings.direction'),
'date' => (new \DateTime())->format('F j'),
'year' => (new \DateTime())->format('YYYY'),
'time' => (new \DateTime())->format('H:i:s'),
'user' => $event->user['name'] ?? '',
'project' => $projectName,
'device' => $clientName,
'ipAddress' => $session->getAttribute('ip'),
'country' => $locale->getText('countries.' . $session->getAttribute('countryCode'), $locale->getText('locale.country.unknown')),
];
if ($isBranded) {
$emailVariables += [
'accentColor' => $platform['accentColor'],
'logoUrl' => $platform['logoUrl'],
'twitter' => $platform['twitterUrl'],
'discord' => $platform['discordUrl'],
'github' => $platform['githubUrl'],
'terms' => $platform['termsUrl'],
'privacy' => $platform['privacyUrl'],
'platform' => $platform['platformName'],
];
}
$queueForMails = new Mail($publisher);
if ($smtp['enabled'] ?? false) {
$queueForMails
->setSmtpHost($smtp['host'] ?? '')
->setSmtpPort($smtp['port'] ?? '')
->setSmtpUsername($smtp['username'] ?? '')
->setSmtpPassword($smtp['password'] ?? '')
->setSmtpSecure($smtp['secure'] ?? '')
->setSmtpReplyTo($customTemplate['replyTo'] ?? $smtp['replyTo'] ?? '')
->setSmtpSenderEmail($customTemplate['senderEmail'] ?? $smtp['senderEmail'] ?? System::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM))
->setSmtpSenderName($customTemplate['senderName'] ?? $smtp['senderName'] ?? System::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server'));
}
$queueForMails
->setProject($project)
->setSubject($subject)
->setPreview($preview)
->setBody($body)
->setBodyTemplate(__DIR__ . '/../../../../app/config/locale/templates/' . $smtpBaseTemplate . '.tpl')
->appendVariables($emailVariables)
->setRecipient($event->user['email']);
if ($isBranded) {
$queueForMails->setSenderName($platform['emailSenderName']);
}
$queueForMails->trigger();
}
}
-1
View File
@@ -101,7 +101,6 @@ class Mail extends Event
/**
* Sets preview for the mail event.
*
* @param string $preview
* @return self
*/
public function setPreview(string $preview): self
+2
View File
@@ -333,6 +333,8 @@ class Exception extends \Exception
/** Platform */
public const string PLATFORM_NOT_FOUND = 'platform_not_found';
public const string PLATFORM_METHOD_UNSUPPORTED = 'platform_method_unsupported';
public const string PLATFORM_ALREADY_EXISTS = 'platform_already_exists';
/** GraphqQL */
public const string GRAPHQL_NO_QUERY = 'graphql_no_query';
+68 -45
View File
@@ -6,20 +6,10 @@ class Platform
{
public const TYPE_UNKNOWN = 'unknown';
public const TYPE_WEB = 'web';
public const TYPE_FLUTTER_IOS = 'flutter-ios';
public const TYPE_FLUTTER_ANDROID = 'flutter-android';
public const TYPE_FLUTTER_MACOS = 'flutter-macos';
public const TYPE_FLUTTER_WINDOWS = 'flutter-windows';
public const TYPE_FLUTTER_LINUX = 'flutter-linux';
public const TYPE_FLUTTER_WEB = 'flutter-web';
public const TYPE_APPLE_IOS = 'apple-ios';
public const TYPE_APPLE_MACOS = 'apple-macos';
public const TYPE_APPLE_WATCHOS = 'apple-watchos';
public const TYPE_APPLE_TVOS = 'apple-tvos';
public const TYPE_APPLE = 'apple';
public const TYPE_ANDROID = 'android';
public const TYPE_UNITY = 'unity';
public const TYPE_REACT_NATIVE_IOS = 'react-native-ios';
public const TYPE_REACT_NATIVE_ANDROID = 'react-native-android';
public const TYPE_WINDOWS = 'windows';
public const TYPE_LINUX = 'linux';
public const TYPE_SCHEME = 'scheme';
public const SCHEME_HTTP = 'http';
@@ -57,6 +47,36 @@ class Platform
self::SCHEME_TAURI => 'Web (Tauri)',
];
/**
* Map deprecated platform types to their new consolidated types.
*
* The 1.9.x refactor consolidated ~15 platform types into 5 new ones.
* Existing platforms in the database may still have old type values.
*
* @param string $type
* @return string The mapped type, or the original if not deprecated.
*/
public static function mapDeprecatedType(string $type): string
{
$mapping = [
'flutter-web' => self::TYPE_WEB,
'unity' => self::TYPE_WEB,
'flutter-ios' => self::TYPE_APPLE,
'flutter-macos' => self::TYPE_APPLE,
'apple-ios' => self::TYPE_APPLE,
'apple-macos' => self::TYPE_APPLE,
'apple-watchos' => self::TYPE_APPLE,
'apple-tvos' => self::TYPE_APPLE,
'react-native-ios' => self::TYPE_APPLE,
'flutter-android' => self::TYPE_ANDROID,
'react-native-android' => self::TYPE_ANDROID,
'flutter-windows' => self::TYPE_WINDOWS,
'flutter-linux' => self::TYPE_LINUX,
];
return $mapping[$type] ?? $type;
}
/**
* Get user-friendly platform name from a scheme.
*
@@ -77,25 +97,28 @@ class Platform
$key = strtolower($platform['key'] ?? '');
switch ($type) {
case 'flutter-web':
case 'unity':
case self::TYPE_WEB:
case self::TYPE_FLUTTER_WEB:
if (!empty($hostname)) {
$hostnames[] = $hostname;
}
break;
case self::TYPE_FLUTTER_IOS:
case self::TYPE_FLUTTER_ANDROID:
case self::TYPE_FLUTTER_MACOS:
case self::TYPE_FLUTTER_WINDOWS:
case self::TYPE_FLUTTER_LINUX:
case 'flutter-android':
case 'react-native-android':
case self::TYPE_ANDROID:
case self::TYPE_APPLE_IOS:
case self::TYPE_APPLE_MACOS:
case self::TYPE_APPLE_WATCHOS:
case self::TYPE_APPLE_TVOS:
case self::TYPE_REACT_NATIVE_IOS:
case self::TYPE_REACT_NATIVE_ANDROID:
case self::TYPE_UNITY:
case 'flutter-windows':
case self::TYPE_WINDOWS:
case 'flutter-linux':
case self::TYPE_LINUX:
case 'flutter-ios':
case 'flutter-macos':
case 'apple-ios':
case 'apple-macos':
case 'apple-watchos':
case 'apple-tvos':
case 'react-native-ios':
case self::TYPE_APPLE:
if (!empty($key)) {
$hostnames[] = $key;
}
@@ -120,38 +143,38 @@ class Platform
$schemes[] = $scheme;
}
break;
case 'flutter-web':
case 'unity':
case self::TYPE_WEB:
case self::TYPE_FLUTTER_WEB:
$schemes[] = self::SCHEME_HTTP;
$schemes[] = self::SCHEME_HTTPS;
break;
case self::TYPE_FLUTTER_IOS:
case self::TYPE_APPLE_IOS:
case self::TYPE_REACT_NATIVE_IOS:
$schemes[] = self::SCHEME_IOS;
break;
case self::TYPE_FLUTTER_ANDROID:
case 'flutter-android':
case 'react-native-android':
case self::TYPE_ANDROID:
case self::TYPE_REACT_NATIVE_ANDROID:
$schemes[] = self::SCHEME_ANDROID;
break;
case self::TYPE_FLUTTER_MACOS:
case self::TYPE_APPLE_MACOS:
case 'flutter-ios':
case 'flutter-macos':
case 'apple-ios':
case 'apple-macos':
case 'apple-watchos':
case 'apple-tvos':
case 'react-native-ios':
case self::TYPE_APPLE:
$schemes[] = self::SCHEME_WATCHOS;
$schemes[] = self::SCHEME_MACOS;
$schemes[] = self::SCHEME_TVOS;
$schemes[] = self::SCHEME_IOS;
break;
case self::TYPE_FLUTTER_WINDOWS:
case self::TYPE_UNITY:
case 'flutter-windows':
case self::TYPE_WINDOWS:
$schemes[] = self::SCHEME_WINDOWS;
break;
case self::TYPE_FLUTTER_LINUX:
case 'flutter-linux':
case self::TYPE_LINUX:
$schemes[] = self::SCHEME_LINUX;
break;
case self::TYPE_APPLE_WATCHOS:
$schemes[] = self::SCHEME_WATCHOS;
break;
case self::TYPE_APPLE_TVOS:
$schemes[] = self::SCHEME_TVOS;
break;
default:
break;
}
@@ -7,9 +7,13 @@ use Appwrite\Platform\Action as AppwriteAction;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Operator;
use Utopia\Database\Query;
class Action extends AppwriteAction
{
public const LIST_CACHE_FIELD_DOCUMENTS = 'documents';
public const LIST_CACHE_FIELD_TOTAL = 'total';
private string $context = DATABASE_TYPE_LEGACY;
public function getDatabaseType(): string
@@ -101,4 +105,67 @@ class Action extends AppwriteAction
return $data;
}
/**
* Stable Redis key for a collection's cached list responses.
*
* All variations (schema × roles × queries) for a single collection live as
* fields inside this one Redis hash, so purging every cached entry for a
* collection is a single O(1) DEL regardless of how many variations have
* been cached.
*/
protected function getListCacheKey(Database $dbForProject, string $collectionId): string
{
return \sprintf(
'%s-cache:%s:%s:%s:collection:%s',
$dbForProject->getCacheName(),
$dbForProject->getAdapter()->getHostname(),
$dbForProject->getNamespace(),
$dbForProject->getTenant(),
$collectionId,
);
}
/**
* Hash field for a single variation of a cached list response.
*
* Scoped by the collection schema (attributes + indexes), the caller's
* authorization roles, the exact query set, and the field type so users
* with different permissions never share entries.
*
* @param Document $collection Collection document (for schema hash)
* @param array<mixed> $roles Caller authorization roles
* @param array<Query|string> $queries Queries for this list call
* @param string $type LIST_CACHE_FIELD_DOCUMENTS or LIST_CACHE_FIELD_TOTAL
*/
protected function getListCacheField(Document $collection, array $roles, array $queries, string $type): string
{
$schemaHash = \md5(
\json_encode($collection->getAttribute('attributes', []))
. \json_encode($collection->getAttribute('indexes', []))
);
$serialized = \array_map(
static fn ($query) => $query instanceof Query ? $query->toArray() : $query,
$queries,
);
return \sprintf(
'%s:%s:%s:%s',
$schemaHash,
\md5(\json_encode($roles)),
\md5(\json_encode($serialized)),
$type,
);
}
/**
* Purge every cached list response for a collection.
*
* One DEL on the collection's Redis hash, clearing all variations at once.
*/
protected function purgeListCache(Database $dbForProject, string $collectionId): bool
{
return $dbForProject->getCache()->purge($this->getListCacheKey($dbForProject, $collectionId));
}
}
@@ -3,34 +3,29 @@
namespace Appwrite\Platform\Modules\Databases\Http\Databases\Collections;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Databases\Http\Databases\Action as DatabasesAction;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Platform\Action as UtopiaAction;
use Utopia\Platform\Scope\HTTP;
abstract class Action extends UtopiaAction
abstract class Action extends DatabasesAction
{
/**
* The current API context (either 'table' or 'collection').
*/
private ?string $context = COLLECTIONS;
private ?string $databaseType = LEGACY;
/**
* Get the response model used in the SDK and HTTP responses.
*/
abstract protected function getResponseModel(): string;
public function setHttpPath(string $path): UtopiaAction
public function setHttpPath(string $path): self
{
if (\str_contains($path, '/tablesdb')) {
$this->context = TABLES;
$this->databaseType = TABLESDB;
} elseif (\str_contains($path, '/vectorsdb')) {
$this->databaseType = VECTORSDB;
}
return parent::setHttpPath($path);
parent::setHttpPath($path);
return $this;
}
/**
@@ -41,14 +36,6 @@ abstract class Action extends UtopiaAction
return $this->context;
}
/**
* Get the current API database type.
*/
protected function getDatabaseType(): string
{
return $this->databaseType;
}
/**
* Get the key used in event parameters (e.g., 'collectionId' or 'tableId').
*/
@@ -207,6 +207,8 @@ class Decrement extends Action
->addMetric($this->getDatabasesOperationWriteMetric(), 1)
->addMetric(str_replace('{databaseInternalId}', $database->getSequence(), $this->getDatabasesIdOperationWriteMetric()), 1);
$response->dynamic($document, $this->getResponseModel());
$queueForEvents
->setParam('databaseId', $databaseId)
->setParam('collectionId', $collectionId)
@@ -216,7 +218,5 @@ class Decrement extends Action
->setContext('database', $database)
->setContext($this->getCollectionsEventsContext(), $collection)
->setPayload($response->getPayload(), sensitive: $relationships);
$response->dynamic($document, $this->getResponseModel());
}
}
@@ -207,6 +207,8 @@ class Increment extends Action
->addMetric($this->getDatabasesOperationWriteMetric(), 1)
->addMetric(str_replace('{databaseInternalId}', $database->getSequence(), $this->getDatabasesIdOperationWriteMetric()), 1);
$response->dynamic($document, $this->getResponseModel());
$queueForEvents
->setParam('databaseId', $databaseId)
->setParam('collectionId', $collectionId)
@@ -216,7 +218,5 @@ class Increment extends Action
->setContext('database', $database)
->setContext($this->getCollectionsEventsContext(), $collection)
->setPayload($response->getPayload(), sensitive: $relationships);
$response->dynamic($document, $this->getResponseModel());
}
}
@@ -131,6 +131,7 @@ class XList extends Action
'userEmail' => $log['data']['userEmail'] ?? null,
'userName' => $log['data']['userName'] ?? null,
'mode' => $log['data']['mode'] ?? null,
'userType' => $log['data']['userType'] ?? null,
'ip' => $log['ip'],
'time' => $log['time'],
'osCode' => $os['osCode'],
@@ -72,7 +72,7 @@ class XList extends Action
->param('queries', [], new ArrayList(new Text(APP_LIMIT_ARRAY_ELEMENT_SIZE), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long.', true)
->param('transactionId', null, fn (Database $dbForProject) => new Nullable(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'Transaction ID to read uncommitted changes within the transaction.', true, ['dbForProject'])
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->param('ttl', 0, new Range(min: 0, max: 86400), 'TTL (seconds) for cached responses when caching is enabled for select queries. Must be between 0 and 86400 (24 hours).', true)
->param('ttl', 0, new Range(min: 0, max: 86400), 'TTL (seconds) for caching list responses. Responses are stored in an in-memory key-value cache, keyed per project, collection, schema version (attributes and indexes), caller authorization roles, and the exact query — so users with different permissions never share cached entries. Schema changes invalidate cached entries automatically; document writes do not, so choose a TTL you are comfortable serving as stale data. Set to 0 to disable caching. Must be between 0 and 86400 (24 hours).', true)
->inject('response')
->inject('dbForProject')
->inject('user')
@@ -127,84 +127,59 @@ class XList extends Action
}
try {
$selectQueries = Query::groupByType($queries)['selections'] ?? [];
$hasSelects = ! empty(Query::groupByType($queries)['selections'] ?? []);
$collectionTableId = 'database_' . $database->getSequence() . '_collection_' . $collection->getSequence();
// When there are no select queries, relationship loading is skipped on the
// underlying find() to avoid pulling related documents the caller did not ask for.
$find = $hasSelects
? fn () => $dbForDatabases->find($collectionTableId, $queries)
: fn () => $dbForDatabases->skipRelationships(fn () => $dbForDatabases->find($collectionTableId, $queries));
// Use transaction-aware document retrieval if transactionId is provided
if ($transactionId !== null) {
$documents = $transactionState->listDocuments($database, $collectionTableId, $transactionId, $queries);
$total = $includeTotal ? $transactionState->countDocuments($database, $collectionTableId, $transactionId, $queries) : 0;
} elseif (! empty($selectQueries)) {
} elseif ((int)$ttl > 0) {
$cacheKey = $this->getListCacheKey($dbForProject, $collectionId);
$roles = $dbForProject->getAuthorization()->getRoles();
$documentsField = $this->getListCacheField($collection, $roles, $queries, self::LIST_CACHE_FIELD_DOCUMENTS);
if ((int)$ttl > 0) {
$serializedQueries = [];
foreach ($queries as $query) {
$serializedQueries[] = $query instanceof Query ? $query->toArray() : $query;
}
$hostname = $dbForProject->getAdapter()->getHostname();
$roles = $dbForProject->getAuthorization()->getRoles();
$schemaHash = \md5(\json_encode($collection->getAttribute('attributes', [])) . \json_encode($collection->getAttribute('indexes', [])));
$cacheKeyBase = \sprintf(
'%s-cache-%s:%s:%s:collection:%s:%s:user:%s:%s',
$dbForProject->getCacheName(),
$hostname,
$dbForProject->getNamespace(),
$dbForProject->getTenant(),
$collectionId,
$schemaHash,
\md5(\json_encode($roles)),
\md5(\json_encode($serializedQueries))
);
$documentsCacheKey = $cacheKeyBase . ':documents';
$totalCacheKey = $cacheKeyBase . ':total';
$documentsCacheHit = $totalDocumentsCacheHit = false;
$cachedDocuments = $dbForProject->getCache()->load($documentsCacheKey, $ttl);
if ($cachedDocuments !== null &&
$cachedDocuments !== false &&
\is_array($cachedDocuments)) {
$documents = \array_map(function ($doc) {
return new Document($doc);
}, $cachedDocuments);
$documentsCacheHit = true;
} else {
$documents = $dbForDatabases->find($collectionTableId, $queries);
// Convert Document objects to arrays for caching
$documentsArray = \array_map(function ($doc) {
return $doc->getArrayCopy();
}, $documents);
$dbForProject->getCache()->save($documentsCacheKey, $documentsArray);
}
if ($includeTotal) {
$cachedTotal = $dbForProject->getCache()->load($totalCacheKey, $ttl);
if ($cachedTotal !== null && $cachedTotal !== false) {
$total = $cachedTotal;
$totalDocumentsCacheHit = true;
} else {
$total = $dbForProject->count($collectionTableId, $queries, APP_LIMIT_COUNT);
$dbForProject->getCache()->save($totalCacheKey, $total);
}
} else {
$total = 0;
}
$response->addHeader('X-Appwrite-Cache', $documentsCacheHit ? 'hit' : 'miss');
$documentsCacheHit = false;
$cachedDocuments = $dbForProject->getCache()->load($cacheKey, $ttl, $documentsField);
if ($cachedDocuments !== null &&
$cachedDocuments !== false &&
\is_array($cachedDocuments)) {
$documents = \array_map(function ($doc) {
return new Document($doc);
}, $cachedDocuments);
$documentsCacheHit = true;
} else {
// has selects, allow relationship on documents
$documents = $dbForDatabases->find($collectionTableId, $queries);
$total = $includeTotal ? $dbForDatabases->count($collectionTableId, $queries, APP_LIMIT_COUNT) : 0;
$documents = $find();
// Convert Document objects to arrays for caching
$documentsArray = \array_map(function ($doc) {
return $doc->getArrayCopy();
}, $documents);
$dbForProject->getCache()->save($cacheKey, $documentsArray, $documentsField);
}
if ($includeTotal) {
$totalField = $this->getListCacheField($collection, $roles, $queries, self::LIST_CACHE_FIELD_TOTAL);
$cachedTotal = $dbForProject->getCache()->load($cacheKey, $ttl, $totalField);
if ($cachedTotal !== null && $cachedTotal !== false) {
$total = $cachedTotal;
} else {
$total = $dbForDatabases->count($collectionTableId, $queries, APP_LIMIT_COUNT);
$dbForProject->getCache()->save($cacheKey, $total, $totalField);
}
} else {
$total = 0;
}
$response->addHeader('X-Appwrite-Cache', $documentsCacheHit ? 'hit' : 'miss');
} else {
// has no selects, disable relationship loading on documents
/* @type Document[] $documents */
$documents = $dbForDatabases->skipRelationships(fn () => $dbForDatabases->find($collectionTableId, $queries));
$documents = $find();
$total = $includeTotal ? $dbForDatabases->count($collectionTableId, $queries, APP_LIMIT_COUNT) : 0;
}
} catch (OrderException $e) {
@@ -123,6 +123,7 @@ class XList extends Action
'userEmail' => $log['data']['userEmail'] ?? null,
'userName' => $log['data']['userName'] ?? null,
'mode' => $log['data']['mode'] ?? null,
'userType' => $log['data']['userType'] ?? null,
'ip' => $log['ip'] ?? null,
'time' => $log['time'] ?? null,
'osCode' => $os['osCode'] ?? null,
@@ -68,6 +68,7 @@ class Update extends Action
->param('permissions', null, new Nullable(new Permissions(APP_LIMIT_ARRAY_PARAMS_SIZE)), 'An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions).', true)
->param('documentSecurity', false, new Boolean(true), 'Enables configuring permissions for individual documents. A user needs one of document or collection level permissions to access a document. [Learn more about permissions](https://appwrite.io/docs/permissions).', true)
->param('enabled', true, new Boolean(), 'Is collection enabled? When set to \'disabled\', users cannot access the collection but Server SDKs with and API key can still read and write to the collection. No data is lost when this is toggled.', true)
->param('purge', false, new Boolean(true), 'When true, purge all cached list responses for this collection as part of the update. Use this to force readers to see fresh data immediately instead of waiting for the cache TTL to expire.', true)
->inject('response')
->inject('dbForProject')
->inject('getDatabasesDB')
@@ -76,7 +77,7 @@ class Update extends Action
->callback($this->action(...));
}
public function action(string $databaseId, string $collectionId, ?string $name, ?array $permissions, bool $documentSecurity, bool $enabled, UtopiaResponse $response, Database $dbForProject, callable $getDatabasesDB, Event $queueForEvents, Authorization $authorization): void
public function action(string $databaseId, string $collectionId, ?string $name, ?array $permissions, bool $documentSecurity, bool $enabled, bool $purge, UtopiaResponse $response, Database $dbForProject, callable $getDatabasesDB, Event $queueForEvents, Authorization $authorization): void
{
$database = $authorization->skip(fn () => $dbForProject->getDocument('databases', $databaseId));
if ($database->isEmpty()) {
@@ -117,6 +118,10 @@ class Update extends Action
->setParam('databaseId', $databaseId)
->setParam($this->getEventsParamKey(), $collection->getId());
if ($purge) {
$this->purgeListCache($dbForProject, $collectionId);
}
$this->addRowBytesInfo($collection, $dbForProject);
$response->dynamic($collection, $this->getResponseModel());
@@ -61,16 +61,16 @@ class Create extends Action
$databaseKeys = System::getEnv('_APP_DATABASE_DOCUMENTSDB_KEYS', '');
$databaseOverride = System::getEnv('_APP_DATABASE_DOCUMENTSDB_OVERRIDE');
$dbScheme = System::getEnv('_APP_DB_HOST_DOCUMENTSDB', 'mongodb');
$databaseSharedTables = \explode(',', System::getEnv('_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES', ''));
$databaseSharedTablesV1 = \explode(',', System::getEnv('_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES_V1', ''));
$databaseSharedTables = \array_filter(\explode(',', System::getEnv('_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES', '')));
$databaseSharedTablesV1 = \array_filter(\explode(',', System::getEnv('_APP_DATABASE_DOCUMENTSDB_SHARED_TABLES_V1', '')));
break;
case VECTORSDB:
$databases = Config::getParam('pools-vectorsdb', []);
$databaseKeys = System::getEnv('_APP_DATABASE_VECTORSDB_KEYS', '');
$databaseOverride = System::getEnv('_APP_DATABASE_VECTORSDB_OVERRIDE');
$dbScheme = System::getEnv('_APP_DB_HOST_VECTORSDB', 'postgresql');
$databaseSharedTables = \explode(',', System::getEnv('_APP_DATABASE_VECTORSDB_SHARED_TABLES', ''));
$databaseSharedTablesV1 = \explode(',', System::getEnv('_APP_DATABASE_VECTORSDB_SHARED_TABLES_V1', ''));
$databaseSharedTables = \array_filter(\explode(',', System::getEnv('_APP_DATABASE_VECTORSDB_SHARED_TABLES', '')));
$databaseSharedTablesV1 = \array_filter(\explode(',', System::getEnv('_APP_DATABASE_VECTORSDB_SHARED_TABLES_V1', '')));
break;
default:
// legacy/tablesdb
@@ -108,7 +108,7 @@ class Create extends Action
if ($index !== false) {
$selectedDsn = $databases[$index];
} else {
if (!empty($dsn)) {
if (!empty($dsn) && !empty($databaseSharedTables)) {
$beforeFilter = \array_values($databases);
if ($isSharedTablesV1) {
$databases = array_filter($databases, fn ($value) => \in_array($value, $databaseSharedTablesV1));
@@ -118,7 +118,10 @@ class Create extends Action
$databases = array_filter($databases, fn ($value) => !\in_array($value, $databaseSharedTables));
}
}
$selectedDsn = !empty($databases) ? $databases[array_rand($databases)] : '';
if (empty($databases)) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, "No {$databasetype} database pool available for the current shared-tables mode");
}
$selectedDsn = $databases[array_rand($databases)];
}
if (\in_array($selectedDsn, $databaseSharedTables)) {
@@ -113,6 +113,7 @@ class XList extends Action
'userEmail' => $log['data']['userEmail'] ?? null,
'userName' => $log['data']['userName'] ?? null,
'mode' => $log['data']['mode'] ?? null,
'userType' => $log['data']['userType'] ?? null,
'ip' => $log['ip'],
'time' => $log['time'],
'osCode' => $os['osCode'],
@@ -58,6 +58,7 @@ class Update extends CollectionUpdate
->param('permissions', null, new Permissions(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions).', true)
->param('documentSecurity', false, new Boolean(true), 'Enables configuring permissions for individual documents. A user needs one of document or collection level permissions to access a document. [Learn more about permissions](https://appwrite.io/docs/permissions).', true)
->param('enabled', true, new Boolean(), 'Is collection enabled? When set to \'disabled\', users cannot access the collection but Server SDKs with and API key can still read and write to the collection. No data is lost when this is toggled.', true)
->param('purge', false, new Boolean(true), 'When true, purge all cached list responses for this collection as part of the update. Use this to force readers to see fresh data immediately instead of waiting for the cache TTL to expire.', true)
->inject('response')
->inject('dbForProject')
->inject('getDatabasesDB')
@@ -107,6 +107,7 @@ class XList extends Action
'userEmail' => $log['data']['userEmail'] ?? null,
'userName' => $log['data']['userName'] ?? null,
'mode' => $log['data']['mode'] ?? null,
'userType' => $log['data']['userType'] ?? null,
'ip' => $log['ip'],
'time' => $log['time'],
'osCode' => $os['osCode'],
@@ -57,7 +57,7 @@ class XList extends DocumentXList
->param('queries', [], new ArrayList(new Text(APP_LIMIT_ARRAY_ELEMENT_SIZE), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long.', true)
->param('transactionId', null, fn (Database $dbForProject) => new Nullable(new UID($dbForProject->getAdapter()->getMaxUIDLength())), 'Transaction ID to read uncommitted changes within the transaction.', true, ['dbForProject'])
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->param('ttl', 0, new Range(min: 0, max: 86400), 'TTL (seconds) for cached responses when caching is enabled for select queries. Must be between 0 and 86400 (24 hours).', true)
->param('ttl', 0, new Range(min: 0, max: 86400), 'TTL (seconds) for caching list responses. Responses are stored in an in-memory key-value cache, keyed per project, table, schema version (columns and indexes), caller authorization roles, and the exact query — so users with different permissions never share cached entries. Schema changes invalidate cached entries automatically; row writes do not, so choose a TTL you are comfortable serving as stale data. Set to 0 to disable caching. Must be between 0 and 86400 (24 hours).', true)
->inject('response')
->inject('dbForProject')
->inject('user')
@@ -60,6 +60,7 @@ class Update extends CollectionUpdate
->param('permissions', null, new Nullable(new Permissions(APP_LIMIT_ARRAY_PARAMS_SIZE)), 'An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](https://appwrite.io/docs/permissions).', true)
->param('rowSecurity', false, new Boolean(true), 'Enables configuring permissions for individual rows. A user needs one of row or table-level permissions to access a row. [Learn more about permissions](https://appwrite.io/docs/permissions).', true)
->param('enabled', true, new Boolean(), 'Is table enabled? When set to \'disabled\', users cannot access the table but Server SDKs with and API key can still read and write to the table. No data is lost when this is toggled.', true)
->param('purge', false, new Boolean(true), 'When true, purge all cached list responses for this table as part of the update. Use this to force readers to see fresh data immediately instead of waiting for the cache TTL to expire.', true)
->inject('response')
->inject('dbForProject')
->inject('getDatabasesDB')
@@ -0,0 +1,119 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Keys;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Database\Validator\CustomId;
use Appwrite\Utopia\Response;
use Utopia\Config\Config;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate as DuplicateException;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\Datetime;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Nullable;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
class Create extends Base
{
use HTTP;
public static function getName()
{
return 'createProjectKey';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/v1/project/keys')
->httpAlias('/v1/projects/:projectId/keys')
->desc('Create project key')
->groups(['api', 'project'])
->label('scope', 'keys.write')
->label('event', 'keys.[keyId].create')
->label('audits.event', 'project.key.create')
->label('audits.resource', 'project.key/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'keys',
name: 'createKey',
description: <<<EOT
Create a new API key. It's recommended to have multiple API keys with strict scopes for separate functions within your project.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_CREATED,
model: Response::MODEL_KEY,
)
],
))
->param('keyId', '', fn (Database $dbForPlatform) => new CustomId(false, $dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Key name. Max length: 128 chars.')
->param('scopes', null, new Nullable(new ArrayList(new WhiteList(array_keys(Config::getParam('projectScopes')), true), APP_LIMIT_ARRAY_PARAMS_SIZE)), 'Key scopes list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' scopes are allowed.')
->param('expire', null, new Nullable(new Datetime()), 'Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Use null for unlimited expiration.', true)
->inject('response')
->inject('queueForEvents')
->inject('dbForPlatform')
->inject('project')
->inject('authorization')
->callback($this->action(...));
}
/**
* @param array<string>|null $scopes
*/
public function action(
string $keyId,
string $name,
?array $scopes,
?string $expire,
Response $response,
QueueEvent $queueForEvents,
Database $dbForPlatform,
Document $project,
Authorization $authorization,
) {
$keyId = ($keyId == 'unique()') ? ID::unique() : $keyId;
$key = new Document([
'$id' => $keyId,
'$permissions' => [],
'resourceInternalId' => $project->getSequence(),
'resourceId' => $project->getId(),
'resourceType' => 'projects',
'name' => $name,
'scopes' => $scopes ?? [],
'expire' => $expire,
'sdks' => [],
'accessedAt' => null,
'secret' => API_KEY_STANDARD . '_' . \bin2hex(\random_bytes(128)),
]);
try {
$key = $authorization->skip(fn () => $dbForPlatform->createDocument('keys', $key));
} catch (DuplicateException) {
throw new Exception(Exception::KEY_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('keyId', $key->getId());
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($key, Response::MODEL_KEY);
}
}
@@ -0,0 +1,90 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Keys;
use Appwrite\Event\Event;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Delete extends Base
{
use HTTP;
public static function getName()
{
return 'deleteProjectKey';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_DELETE)
->setHttpPath('/v1/project/keys/:keyId')
->httpAlias('/v1/projects/:projectId/keys/:keyId')
->desc('Delete project key')
->groups(['api', 'project'])
->label('scope', 'keys.write')
->label('event', 'keys.[keyId].delete')
->label('audits.event', 'project.key.delete')
->label('audits.resource', 'project.key/{request.keyId}')
->label('sdk', new Method(
namespace: 'project',
group: 'keys',
name: 'deleteKey',
description: <<<EOT
Delete a key by its unique ID. Once deleted, the key can no longer be used to authenticate API calls.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_NOCONTENT,
model: Response::MODEL_NONE,
)
],
contentType: ContentType::NONE
))
->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->inject('queueForEvents')
->inject('project')
->inject('authorization')
->callback($this->action(...));
}
public function action(
string $keyId,
Response $response,
Database $dbForPlatform,
Event $queueForEvents,
Document $project,
Authorization $authorization,
) {
$key = $authorization->skip(fn () => $dbForPlatform->getDocument('keys', $keyId));
if ($key->isEmpty() || $key->getAttribute('resourceType', '') !== 'projects' || $key->getAttribute('resourceInternalId', '') !== $project->getSequence()) {
throw new Exception(Exception::KEY_NOT_FOUND);
}
if (!$authorization->skip(fn () => $dbForPlatform->deleteDocument('keys', $key->getId()))) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove document from DB');
};
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('keyId', $key->getId());
$response->noContent();
}
}
@@ -0,0 +1,74 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Keys;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Get extends Base
{
use HTTP;
public static function getName()
{
return 'getProjectKey';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/v1/project/keys/:keyId')
->httpAlias('/v1/projects/:projectId/keys/:keyId')
->desc('Get project key')
->groups(['api', 'project'])
->label('scope', 'keys.read')
->label('sdk', new Method(
namespace: 'project',
group: 'keys',
name: 'getKey',
description: <<<EOT
Get a key by its unique ID.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_KEY,
)
]
))
->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->inject('project')
->inject('authorization')
->callback($this->action(...));
}
public function action(
string $keyId,
Response $response,
Database $dbForPlatform,
Document $project,
Authorization $authorization,
) {
$key = $authorization->skip(fn () => $dbForPlatform->getDocument('keys', $keyId));
if ($key->isEmpty() || $key->getAttribute('resourceType', '') !== 'projects' || $key->getAttribute('resourceInternalId', '') !== $project->getSequence()) {
throw new Exception(Exception::KEY_NOT_FOUND);
}
$response->dynamic($key, Response::MODEL_KEY);
}
}
@@ -0,0 +1,111 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Keys;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Config\Config;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\Datetime;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Nullable;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
class Update extends Base
{
use HTTP;
public static function getName()
{
return 'updateProjectKey';
}
public function __construct()
{
$this->setHttpMethod(Action::HTTP_REQUEST_METHOD_PUT)
->setHttpPath('/v1/project/keys/:keyId')
->httpAlias('/v1/projects/:projectId/keys/:keyId')
->desc('Update project key')
->groups(['api', 'project'])
->label('scope', 'keys.write')
->label('event', 'keys.[keyId].update')
->label('audits.event', 'project.key.update')
->label('audits.resource', 'project.key/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'keys',
name: 'updateKey',
description: <<<EOT
Update a key by its unique ID. Use this endpoint to update the name, scopes, or expiration time of an API key.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_KEY,
)
]
))
->param('keyId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Key ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Key name. Max length: 128 chars.')
->param('scopes', null, new Nullable(new ArrayList(new WhiteList(array_keys(Config::getParam('projectScopes')), true), APP_LIMIT_ARRAY_PARAMS_SIZE)), 'Key scopes list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' scopes are allowed.')
->param('expire', null, new Nullable(new Datetime()), 'Expiration time in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. Use null for unlimited expiration.', true)
->inject('response')
->inject('queueForEvents')
->inject('dbForPlatform')
->inject('project')
->inject('authorization')
->callback($this->action(...));
}
/**
* @param array<string>|null $scopes
*/
public function action(
string $keyId,
string $name,
?array $scopes,
?string $expire,
Response $response,
QueueEvent $queueForEvents,
Database $dbForPlatform,
Document $project,
Authorization $authorization,
) {
$key = $authorization->skip(fn () => $dbForPlatform->getDocument('keys', $keyId));
if ($key->isEmpty() || $key->getAttribute('resourceType', '') !== 'projects' || $key->getAttribute('resourceInternalId', '') !== $project->getSequence()) {
throw new Exception(Exception::KEY_NOT_FOUND);
}
$updates = new Document([
'name' => $name,
'scopes' => $scopes ?? [],
'expire' => $expire,
]);
try {
$key = $authorization->skip(fn () => $dbForPlatform->updateDocument('keys', $key->getId(), $updates));
} catch (Duplicate) {
throw new Exception(Exception::KEY_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('keyId', $key->getId());
$response->dynamic($key, Response::MODEL_KEY);
}
}
@@ -0,0 +1,127 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Keys;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Database\Validator\Queries\Keys;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Order as OrderException;
use Utopia\Database\Exception\Query as QueryException;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\Query\Cursor;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Boolean;
class XList extends Base
{
use HTTP;
public static function getName()
{
return 'listProjectKeys';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/v1/project/keys')
->httpAlias('/v1/projects/:projectId/keys')
->desc('List project keys')
->groups(['api', 'project'])
->label('scope', 'keys.read')
->label('sdk', new Method(
namespace: 'project',
group: 'keys',
name: 'listKeys',
description: <<<EOT
Get a list of all API keys from the current project.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_KEY_LIST,
)
]
))
->param('queries', [], new Keys(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Keys::ALLOWED_ATTRIBUTES), true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('project')
->inject('response')
->inject('dbForPlatform')
->inject('authorization')
->callback($this->action(...));
}
/**
* @param array<string> $queries
*/
public function action(
array $queries,
bool $includeTotal,
Document $project,
Response $response,
Database $dbForPlatform,
Authorization $authorization,
) {
try {
$queries = Query::parseQueries($queries);
} catch (QueryException $e) {
throw new Exception(Exception::GENERAL_QUERY_INVALID, $e->getMessage());
}
// Backwards compatibility
if (\count(Query::getByType($queries, [Query::TYPE_LIMIT])) === 0) {
$queries[] = Query::limit(5000);
}
$queries[] = Query::equal('resourceType', ['projects']);
$queries[] = Query::equal('resourceInternalId', [$project->getSequence()]);
$cursor = Query::getCursorQueries($queries, false);
$cursor = \reset($cursor);
if ($cursor !== false) {
$validator = new Cursor();
if (!$validator->isValid($cursor)) {
throw new Exception(Exception::GENERAL_QUERY_INVALID, $validator->getDescription());
}
$keyId = $cursor->getValue();
$cursorDocument = $authorization->skip(fn () => $dbForPlatform->findOne('keys', [
Query::equal('$id', [$keyId]),
Query::equal('resourceType', ['projects']),
Query::equal('resourceInternalId', [$project->getSequence()]),
]));
if ($cursorDocument->isEmpty()) {
throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, "Key '{$keyId}' for the 'cursor' value not found.");
}
$cursor->setValue($cursorDocument);
}
$filterQueries = Query::groupByType($queries)['filters'];
try {
$keys = $authorization->skip(fn () => $dbForPlatform->find('keys', $queries));
$total = $includeTotal ? $authorization->skip(fn () => $dbForPlatform->count('keys', $filterQueries, APP_LIMIT_COUNT)) : 0;
} catch (OrderException $e) {
throw new Exception(Exception::DATABASE_QUERY_ORDER_NULL, "The order attribute '{$e->getAttribute()}' had a null value. Cursor pagination requires all documents order attribute values are non-null.");
}
$response->dynamic(new Document([
'keys' => $keys,
'total' => $total,
]), Response::MODEL_KEY_LIST);
}
}
@@ -0,0 +1,105 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms\Android;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Database\Validator\CustomId;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate as DuplicateException;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Create extends Action
{
use HTTP;
public static function getName()
{
return 'createProjectAndroidPlatform';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/v1/project/platforms/android')
->desc('Create project Android platform')
->groups(['api', 'project'])
->label('scope', 'platforms.write')
->label('event', 'platforms.[platformId].create')
->label('audits.event', 'project.platform.create')
->label('audits.resource', 'project.platform/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'createAndroidPlatform',
description: <<<EOT
Create a new Android platform for your project. Use this endpoint to register a new Android platform where your users will run your application which will interact with the Appwrite API.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_CREATED,
model: Response::MODEL_PLATFORM_ANDROID,
)
],
))
->param('platformId', '', fn (Database $dbForPlatform) => new CustomId(false, $dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('applicationId', '', new Text(256), 'Android application ID. Max length: 256 chars.')
->inject('response')
->inject('queueForEvents')
->inject('project')
->inject('dbForPlatform')
->inject('authorization')
->callback($this->action(...));
}
public function action(
string $platformId,
string $name,
string $applicationId,
Response $response,
QueueEvent $queueForEvents,
Document $project,
Database $dbForPlatform,
Authorization $authorization,
) {
$platformId = ($platformId == 'unique()') ? ID::unique() : $platformId;
$platform = new Document([
'$id' => $platformId,
'$permissions' => [],
'projectInternalId' => $project->getSequence(),
'projectId' => $project->getId(),
'type' => Platform::TYPE_ANDROID,
'name' => $name,
'key' => $applicationId,
'hostname' => '',
]);
try {
$platform = $authorization->skip(fn () => $dbForPlatform->createDocument('platforms', $platform));
} catch (DuplicateException) {
throw new Exception(Exception::PLATFORM_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('platformId', $platform->getId());
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($platform, Response::MODEL_PLATFORM_ANDROID);
}
}
@@ -0,0 +1,103 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms\Android;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Update extends Action
{
use HTTP;
public static function getName()
{
return 'updateProjectAndroidPlatform';
}
public function __construct()
{
$this->setHttpMethod(Action::HTTP_REQUEST_METHOD_PUT)
->setHttpPath('/v1/project/platforms/android/:platformId')
->desc('Update project Android platform')
->groups(['api', 'project'])
->label('scope', 'platforms.write')
->label('event', 'platforms.[platformId].update')
->label('audits.event', 'project.platform.update')
->label('audits.resource', 'project.platform/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'updateAndroidPlatform',
description: <<<EOT
Update an Android platform by its unique ID. Use this endpoint to update the platform's name or application ID.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_PLATFORM_ANDROID,
)
]
))
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('applicationId', '', new Text(256), 'Android application ID. Max length: 256 chars.')
->inject('response')
->inject('queueForEvents')
->inject('dbForPlatform')
->inject('authorization')
->inject('project')
->callback($this->action(...));
}
public function action(
string $platformId,
string $name,
string $applicationId,
Response $response,
QueueEvent $queueForEvents,
Database $dbForPlatform,
Authorization $authorization,
Document $project,
) {
$platform = $authorization->skip(fn () => $dbForPlatform->getDocument('platforms', $platformId));
if ($platform->isEmpty() || $platform->getAttribute('projectInternalId', '') !== $project->getSequence()) {
throw new Exception(Exception::PLATFORM_NOT_FOUND);
}
if ($platform->getAttribute('type', '') !== Platform::TYPE_ANDROID) {
throw new Exception(Exception::PLATFORM_METHOD_UNSUPPORTED);
}
$updates = new Document([
'name' => $name,
'key' => $applicationId,
]);
try {
$platform = $authorization->skip(fn () => $dbForPlatform->updateDocument('platforms', $platform->getId(), $updates));
} catch (Duplicate) {
throw new Exception(Exception::PLATFORM_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('platformId', $platform->getId());
$response->dynamic($platform, Response::MODEL_PLATFORM_ANDROID);
}
}
@@ -0,0 +1,105 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms\Apple;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Database\Validator\CustomId;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate as DuplicateException;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Create extends Action
{
use HTTP;
public static function getName()
{
return 'createProjectApplePlatform';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/v1/project/platforms/apple')
->desc('Create project Apple platform')
->groups(['api', 'project'])
->label('scope', 'platforms.write')
->label('event', 'platforms.[platformId].create')
->label('audits.event', 'project.platform.create')
->label('audits.resource', 'project.platform/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'createApplePlatform',
description: <<<EOT
Create a new Apple platform for your project. Use this endpoint to register a new Apple platform where your users will run your application which will interact with the Appwrite API.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_CREATED,
model: Response::MODEL_PLATFORM_APPLE,
)
],
))
->param('platformId', '', fn (Database $dbForPlatform) => new CustomId(false, $dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('bundleIdentifier', '', new Text(256), 'Apple bundle identifier. Max length: 256 chars.')
->inject('response')
->inject('queueForEvents')
->inject('project')
->inject('dbForPlatform')
->inject('authorization')
->callback($this->action(...));
}
public function action(
string $platformId,
string $name,
string $bundleIdentifier,
Response $response,
QueueEvent $queueForEvents,
Document $project,
Database $dbForPlatform,
Authorization $authorization,
) {
$platformId = ($platformId == 'unique()') ? ID::unique() : $platformId;
$platform = new Document([
'$id' => $platformId,
'$permissions' => [],
'projectInternalId' => $project->getSequence(),
'projectId' => $project->getId(),
'type' => Platform::TYPE_APPLE,
'name' => $name,
'key' => $bundleIdentifier,
'hostname' => '',
]);
try {
$platform = $authorization->skip(fn () => $dbForPlatform->createDocument('platforms', $platform));
} catch (DuplicateException) {
throw new Exception(Exception::PLATFORM_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('platformId', $platform->getId());
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($platform, Response::MODEL_PLATFORM_APPLE);
}
}
@@ -0,0 +1,103 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms\Apple;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Update extends Action
{
use HTTP;
public static function getName()
{
return 'updateProjectApplePlatform';
}
public function __construct()
{
$this->setHttpMethod(Action::HTTP_REQUEST_METHOD_PUT)
->setHttpPath('/v1/project/platforms/apple/:platformId')
->desc('Update project Apple platform')
->groups(['api', 'project'])
->label('scope', 'platforms.write')
->label('event', 'platforms.[platformId].update')
->label('audits.event', 'project.platform.update')
->label('audits.resource', 'project.platform/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'updateApplePlatform',
description: <<<EOT
Update an Apple platform by its unique ID. Use this endpoint to update the platform's name or bundle identifier.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_PLATFORM_APPLE,
)
]
))
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('bundleIdentifier', '', new Text(256), 'Apple bundle identifier. Max length: 256 chars.')
->inject('response')
->inject('queueForEvents')
->inject('dbForPlatform')
->inject('authorization')
->inject('project')
->callback($this->action(...));
}
public function action(
string $platformId,
string $name,
string $bundleIdentifier,
Response $response,
QueueEvent $queueForEvents,
Database $dbForPlatform,
Authorization $authorization,
Document $project,
) {
$platform = $authorization->skip(fn () => $dbForPlatform->getDocument('platforms', $platformId));
if ($platform->isEmpty() || $platform->getAttribute('projectInternalId', '') !== $project->getSequence()) {
throw new Exception(Exception::PLATFORM_NOT_FOUND);
}
if ($platform->getAttribute('type', '') !== Platform::TYPE_APPLE) {
throw new Exception(Exception::PLATFORM_METHOD_UNSUPPORTED);
}
$updates = new Document([
'name' => $name,
'key' => $bundleIdentifier,
]);
try {
$platform = $authorization->skip(fn () => $dbForPlatform->updateDocument('platforms', $platform->getId(), $updates));
} catch (Duplicate) {
throw new Exception(Exception::PLATFORM_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('platformId', $platform->getId());
$response->dynamic($platform, Response::MODEL_PLATFORM_APPLE);
}
}
@@ -0,0 +1,89 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms;
use Appwrite\Event\Event;
use Appwrite\Extend\Exception;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Delete extends Action
{
use HTTP;
public static function getName()
{
return 'deleteProjectPlatform';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_DELETE)
->setHttpPath('/v1/project/platforms/:platformId')
->httpAlias('/v1/projects/:projectId/platforms/:platformId')
->desc('Delete project platform')
->groups(['api', 'project'])
->label('scope', 'platforms.write')
->label('event', 'platforms.[platformId].delete')
->label('audits.event', 'project.platform.delete')
->label('audits.resource', 'project.platform/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'deletePlatform',
description: <<<EOT
Delete a platform by its unique ID. This endpoint removes the platform and all its configurations from the project.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_NOCONTENT,
model: Response::MODEL_NONE,
)
],
contentType: ContentType::NONE
))
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->inject('authorization')
->inject('project')
->inject('queueForEvents')
->callback($this->action(...));
}
public function action(
string $platformId,
Response $response,
Database $dbForPlatform,
Authorization $authorization,
Document $project,
Event $queueForEvents,
) {
$platform = $authorization->skip(fn () => $dbForPlatform->getDocument('platforms', $platformId));
if ($platform->isEmpty() || $platform->getAttribute('projectInternalId', '') !== $project->getSequence()) {
throw new Exception(Exception::PLATFORM_NOT_FOUND);
}
if (!$authorization->skip(fn () => $dbForPlatform->deleteDocument('platforms', $platform->getId()))) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove document from DB');
};
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('platformId', $platform->getId());
$response->noContent();
}
}
@@ -0,0 +1,92 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Get extends Action
{
use HTTP;
public static function getName()
{
return 'getProjectPlatform';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/v1/project/platforms/:platformId')
->httpAlias('/v1/projects/:projectId/platforms/:platformId')
->desc('Get project platform')
->groups(['api', 'project'])
->label('scope', 'platforms.read')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'getPlatform',
description: <<<EOT
Get a platform by its unique ID. This endpoint returns the platform's details, including its name, type, and key configurations.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: [
Response::MODEL_PLATFORM_WEB,
Response::MODEL_PLATFORM_APPLE,
Response::MODEL_PLATFORM_ANDROID,
Response::MODEL_PLATFORM_WINDOWS,
Response::MODEL_PLATFORM_LINUX,
],
)
]
))
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID.', false, ['dbForPlatform'])
->inject('response')
->inject('dbForPlatform')
->inject('authorization')
->inject('project')
->callback($this->action(...));
}
public function action(
string $platformId,
Response $response,
Database $dbForPlatform,
Authorization $authorization,
Document $project
) {
$platform = $authorization->skip(fn () => $dbForPlatform->getDocument('platforms', $platformId));
if ($platform->isEmpty() || $platform->getAttribute('projectInternalId', '') !== $project->getSequence()) {
throw new Exception(Exception::PLATFORM_NOT_FOUND);
}
$type = Platform::mapDeprecatedType($platform->getAttribute('type'));
$platform->setAttribute('type', $type);
$model = match($type) {
Platform::TYPE_WEB => Response::MODEL_PLATFORM_WEB,
Platform::TYPE_APPLE => Response::MODEL_PLATFORM_APPLE,
Platform::TYPE_ANDROID => Response::MODEL_PLATFORM_ANDROID,
Platform::TYPE_WINDOWS => Response::MODEL_PLATFORM_WINDOWS,
Platform::TYPE_LINUX => Response::MODEL_PLATFORM_LINUX,
default => Response::MODEL_PLATFORM_WEB // Backwards compatibility
};
$response->dynamic($platform, $model);
}
}
@@ -0,0 +1,105 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms\Linux;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Database\Validator\CustomId;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate as DuplicateException;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Create extends Action
{
use HTTP;
public static function getName()
{
return 'createProjectLinuxPlatform';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/v1/project/platforms/linux')
->desc('Create project Linux platform')
->groups(['api', 'project'])
->label('scope', 'platforms.write')
->label('event', 'platforms.[platformId].create')
->label('audits.event', 'project.platform.create')
->label('audits.resource', 'project.platform/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'createLinuxPlatform',
description: <<<EOT
Create a new Linux platform for your project. Use this endpoint to register a new Linux platform where your users will run your application which will interact with the Appwrite API.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_CREATED,
model: Response::MODEL_PLATFORM_LINUX,
)
],
))
->param('platformId', '', fn (Database $dbForPlatform) => new CustomId(false, $dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('packageName', '', new Text(256), 'Linux package name. Max length: 256 chars.')
->inject('response')
->inject('queueForEvents')
->inject('project')
->inject('dbForPlatform')
->inject('authorization')
->callback($this->action(...));
}
public function action(
string $platformId,
string $name,
string $packageName,
Response $response,
QueueEvent $queueForEvents,
Document $project,
Database $dbForPlatform,
Authorization $authorization,
) {
$platformId = ($platformId == 'unique()') ? ID::unique() : $platformId;
$platform = new Document([
'$id' => $platformId,
'$permissions' => [],
'projectInternalId' => $project->getSequence(),
'projectId' => $project->getId(),
'type' => Platform::TYPE_LINUX,
'name' => $name,
'key' => $packageName,
'hostname' => '', // Web platform attribute
]);
try {
$platform = $authorization->skip(fn () => $dbForPlatform->createDocument('platforms', $platform));
} catch (DuplicateException) {
throw new Exception(Exception::PLATFORM_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('platformId', $platform->getId());
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($platform, Response::MODEL_PLATFORM_LINUX);
}
}
@@ -0,0 +1,103 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms\Linux;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Update extends Action
{
use HTTP;
public static function getName()
{
return 'updateProjectLinuxPlatform';
}
public function __construct()
{
$this->setHttpMethod(Action::HTTP_REQUEST_METHOD_PUT)
->setHttpPath('/v1/project/platforms/linux/:platformId')
->desc('Update project Linux platform')
->groups(['api', 'project'])
->label('scope', 'platforms.write')
->label('event', 'platforms.[platformId].update')
->label('audits.event', 'project.platform.update')
->label('audits.resource', 'project.platform/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'updateLinuxPlatform',
description: <<<EOT
Update a Linux platform by its unique ID. Use this endpoint to update the platform's name or package name.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_PLATFORM_LINUX,
)
]
))
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('packageName', '', new Text(256), 'Linux package name. Max length: 256 chars.')
->inject('response')
->inject('queueForEvents')
->inject('dbForPlatform')
->inject('authorization')
->inject('project')
->callback($this->action(...));
}
public function action(
string $platformId,
string $name,
string $packageName,
Response $response,
QueueEvent $queueForEvents,
Database $dbForPlatform,
Authorization $authorization,
Document $project,
) {
$platform = $authorization->skip(fn () => $dbForPlatform->getDocument('platforms', $platformId));
if ($platform->isEmpty() || $platform->getAttribute('projectInternalId', '') !== $project->getSequence()) {
throw new Exception(Exception::PLATFORM_NOT_FOUND);
}
if ($platform->getAttribute('type', '') !== Platform::TYPE_LINUX) {
throw new Exception(Exception::PLATFORM_METHOD_UNSUPPORTED);
}
$updates = new Document([
'name' => $name,
'key' => $packageName,
]);
try {
$platform = $authorization->skip(fn () => $dbForPlatform->updateDocument('platforms', $platform->getId(), $updates));
} catch (Duplicate) {
throw new Exception(Exception::PLATFORM_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('platformId', $platform->getId());
$response->dynamic($platform, Response::MODEL_PLATFORM_LINUX);
}
}
@@ -0,0 +1,173 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms\Web;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Database\Validator\CustomId;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate as DuplicateException;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Hostname;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
/**
* WARNING: This kind of platform has most complex action, because it holds backwards compatibility too.
* If possible, refer to any other type of platform for APIs, for more simpler endpoint.
*/
class Create extends Action
{
use HTTP;
public static function getName()
{
return 'createProjectWebPlatform';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/v1/project/platforms/web')
->httpAlias('/v1/projects/:projectId/platforms')
->desc('Create project web platform')
->groups(['api', 'project'])
->label('scope', 'platforms.write')
->label('event', 'platforms.[platformId].create')
->label('audits.event', 'project.platform.create')
->label('audits.resource', 'project.platform/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'createWebPlatform',
description: <<<EOT
Create a new web platform for your project. Use this endpoint to register a new platform where your users will run your application which will interact with the Appwrite API.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_CREATED,
model: Response::MODEL_PLATFORM_WEB,
)
],
))
->param('platformId', '', fn (Database $dbForPlatform) => new CustomId(false, $dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('hostname', '', new Hostname(), 'Platform web hostname. Max length: 256 chars.', optional: true) // Optional for backwards compatibility
->param('key', '', new Text(256), 'Deprecated: Package name for Android or bundle ID for iOS or macOS. Max length: 256 chars.', optional: true, deprecated: true) // Exists for backwards compatibility
->param('type', '', new Text(256), 'Deprecated: Platform type. Max length: 256 chars.', optional: true, deprecated: true) // Exists for backwards compatibility
->inject('request')
->inject('response')
->inject('queueForEvents')
->inject('project')
->inject('dbForPlatform')
->inject('authorization')
->callback($this->action(...));
}
public function action(
string $platformId,
string $name,
string $hostname,
?string $key, // For backwards compatibility
?string $type, // For backwards compatibility
Request $request,
Response $response,
QueueEvent $queueForEvents,
Document $project,
Database $dbForPlatform,
Authorization $authorization,
) {
$key = $key ?? ''; // App platform attribute, backwards compatibility
$type = $type ?? ''; // App platform attribute, backwards compatibility
// Backwards compatibility
// Used to have: type, name, key, hostname
if (!empty($type)) {
// Validate deprecated type, and rename to new type
$deprecatedTypeMapping = [
// Web
'web' => Platform::TYPE_WEB,
'flutter-web' => Platform::TYPE_WEB,
'unity' => Platform::TYPE_WEB, // Was not officially supported anyway
// Apple
'flutter-macos' => Platform::TYPE_APPLE,
'flutter-ios' => Platform::TYPE_APPLE,
'react-native-ios' => Platform::TYPE_APPLE,
'apple-ios' => Platform::TYPE_APPLE,
'apple-macos' => Platform::TYPE_APPLE,
'apple-watchos' => Platform::TYPE_APPLE,
'apple-tvos' => Platform::TYPE_APPLE,
// Android
'flutter-android' => Platform::TYPE_ANDROID,
'android' => Platform::TYPE_ANDROID,
'react-native-android' => Platform::TYPE_ANDROID,
'flutter-linux' => Platform::TYPE_LINUX,
'flutter-windows' => Platform::TYPE_WINDOWS,
];
$typeValidator = new WhiteList(\array_keys($deprecatedTypeMapping));
if (!$typeValidator->isValid($request->getParam('type', ''))) {
throw new Exception(Exception::GENERAL_BAD_REQUEST, 'Param "type" is invalid: ' . $typeValidator->getDescription());
}
$type = $deprecatedTypeMapping[$request->getParam('type', '')] ?? '';
}
if (!empty($key)) {
// Validate deprecated app id (key)
$keyValidator = new Text(256);
if (!$keyValidator->isValid($key)) {
throw new Exception(Exception::GENERAL_BAD_REQUEST, 'Param "key" is invalid: ' . $keyValidator->getDescription());
}
}
if (empty($key) && empty($type)) {
// Modern request, validate hostname
if (empty($hostname)) {
throw new Exception(Exception::GENERAL_BAD_REQUEST, 'Param "hostname" is not optional.');
}
}
$platformId = ($platformId == 'unique()') ? ID::unique() : $platformId;
$platform = new Document([
'$id' => $platformId,
'$permissions' => [],
'projectInternalId' => $project->getSequence(),
'projectId' => $project->getId(),
'type' => $type ?: Platform::TYPE_WEB, // Preserve type for backwards compatibility
'name' => $name,
'key' => $key,
'hostname' => $hostname
]);
try {
$platform = $authorization->skip(fn () => $dbForPlatform->createDocument('platforms', $platform));
} catch (DuplicateException) {
throw new Exception(Exception::PLATFORM_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('platformId', $platform->getId());
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($platform, Response::MODEL_PLATFORM_WEB);
}
}
@@ -0,0 +1,151 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms\Web;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Hostname;
use Utopia\Validator\Text;
class Update extends Action
{
use HTTP;
public static function getName()
{
return 'updateProjectWebPlatform';
}
public function __construct()
{
$this->setHttpMethod(Action::HTTP_REQUEST_METHOD_PUT)
->setHttpPath('/v1/project/platforms/web/:platformId')
->httpAlias('/v1/projects/:projectId/platforms/:platformId')
->desc('Update project web platform')
->groups(['api', 'project'])
->label('scope', 'platforms.write')
->label('event', 'platforms.[platformId].update')
->label('audits.event', 'project.platform.update')
->label('audits.resource', 'project.platform/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'updateWebPlatform',
description: <<<EOT
Update a web platform by its unique ID. Use this endpoint to update the platform's name or hostname.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_PLATFORM_WEB,
)
]
))
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('hostname', '', new Hostname(), 'Platform web hostname. Max length: 256 chars.', optional: true) // Optional for backwards compatibility
->param('key', '', new Text(256), 'Package name for Android or bundle ID for iOS or macOS. Max length: 256 chars.', optional: true, deprecated: true) // Exists for backwards compatibility
->inject('response')
->inject('queueForEvents')
->inject('dbForPlatform')
->inject('authorization')
->inject('project')
->callback($this->action(...));
}
public function action(
string $platformId,
string $name,
string $hostname,
?string $key, // For backwards compatibility
Response $response,
QueueEvent $queueForEvents,
Database $dbForPlatform,
Authorization $authorization,
Document $project,
) {
$key = $key ?? ''; // App platform attribute, backwards compatibility
// Backwards compatibility
// Used to have: type, name, key, hostname
if (!empty($key)) {
// Validate deprecated app id (key)
$keyValidator = new Text(256);
if (!$keyValidator->isValid($key)) {
throw new Exception(Exception::GENERAL_BAD_REQUEST, 'Param "key" is invalid: ' . $keyValidator->getDescription());
}
}
// One day, ideally, we ensure hostname is not empty
// But for backwards compatibility backend must threat it as optional for now
$platform = $authorization->skip(fn () => $dbForPlatform->getDocument('platforms', $platformId));
if ($platform->isEmpty() || $platform->getAttribute('projectInternalId', '') !== $project->getSequence()) {
throw new Exception(Exception::PLATFORM_NOT_FOUND);
}
// Wrapped in if, for backwards compatibility
if (!empty($hostname)) {
$supportedTypes = [
Platform::TYPE_WEB,
// Backwards compatibility
'flutter-web',
'unity',
'flutter-macos',
'flutter-ios',
'react-native-ios',
'apple-ios',
'apple-macos',
'apple-watchos',
'apple-tvos',
'flutter-android',
'react-native-android',
'flutter-windows',
'flutter-linux',
];
if (!in_array($platform->getAttribute('type', ''), $supportedTypes)) {
throw new Exception(Exception::PLATFORM_METHOD_UNSUPPORTED);
}
}
$updates = new Document([
'name' => $name,
]);
// Wrapped in if, for backwards compatibility
if (!empty($hostname)) {
$updates->setAttribute('hostname', $hostname);
}
// Backwards compatibility
if (!empty($key)) {
$updates->setAttribute('key', $key);
}
try {
$platform = $authorization->skip(fn () => $dbForPlatform->updateDocument('platforms', $platform->getId(), $updates));
} catch (Duplicate) {
throw new Exception(Exception::PLATFORM_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('platformId', $platform->getId());
$response->dynamic($platform, Response::MODEL_PLATFORM_WEB);
}
}
@@ -0,0 +1,105 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms\Windows;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Database\Validator\CustomId;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate as DuplicateException;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Create extends Action
{
use HTTP;
public static function getName()
{
return 'createProjectWindowsPlatform';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/v1/project/platforms/windows')
->desc('Create project Windows platform')
->groups(['api', 'project'])
->label('scope', 'platforms.write')
->label('event', 'platforms.[platformId].create')
->label('audits.event', 'project.platform.create')
->label('audits.resource', 'project.platform/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'createWindowsPlatform',
description: <<<EOT
Create a new Windows platform for your project. Use this endpoint to register a new Windows platform where your users will run your application which will interact with the Appwrite API.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_CREATED,
model: Response::MODEL_PLATFORM_WINDOWS,
)
],
))
->param('platformId', '', fn (Database $dbForPlatform) => new CustomId(false, $dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('packageIdentifierName', '', new Text(256), 'Windows package identifier name. Max length: 256 chars.')
->inject('response')
->inject('queueForEvents')
->inject('project')
->inject('dbForPlatform')
->inject('authorization')
->callback($this->action(...));
}
public function action(
string $platformId,
string $name,
string $packageIdentifierName,
Response $response,
QueueEvent $queueForEvents,
Document $project,
Database $dbForPlatform,
Authorization $authorization,
) {
$platformId = ($platformId == 'unique()') ? ID::unique() : $platformId;
$platform = new Document([
'$id' => $platformId,
'$permissions' => [],
'projectInternalId' => $project->getSequence(),
'projectId' => $project->getId(),
'type' => Platform::TYPE_WINDOWS,
'name' => $name,
'key' => $packageIdentifierName,
'hostname' => '',
]);
try {
$platform = $authorization->skip(fn () => $dbForPlatform->createDocument('platforms', $platform));
} catch (DuplicateException) {
throw new Exception(Exception::PLATFORM_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('platformId', $platform->getId());
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($platform, Response::MODEL_PLATFORM_WINDOWS);
}
}
@@ -0,0 +1,103 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms\Windows;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Update extends Action
{
use HTTP;
public static function getName()
{
return 'updateProjectWindowsPlatform';
}
public function __construct()
{
$this->setHttpMethod(Action::HTTP_REQUEST_METHOD_PUT)
->setHttpPath('/v1/project/platforms/windows/:platformId')
->desc('Update project Windows platform')
->groups(['api', 'project'])
->label('scope', 'platforms.write')
->label('event', 'platforms.[platformId].update')
->label('audits.event', 'project.platform.update')
->label('audits.resource', 'project.platform/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'updateWindowsPlatform',
description: <<<EOT
Update a Windows platform by its unique ID. Use this endpoint to update the platform's name or package identifier name.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_PLATFORM_WINDOWS,
)
]
))
->param('platformId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Platform ID.', false, ['dbForPlatform'])
->param('name', null, new Text(128), 'Platform name. Max length: 128 chars.')
->param('packageIdentifierName', '', new Text(256), 'Windows package identifier name. Max length: 256 chars.')
->inject('response')
->inject('queueForEvents')
->inject('dbForPlatform')
->inject('authorization')
->inject('project')
->callback($this->action(...));
}
public function action(
string $platformId,
string $name,
string $packageIdentifierName,
Response $response,
QueueEvent $queueForEvents,
Database $dbForPlatform,
Authorization $authorization,
Document $project,
) {
$platform = $authorization->skip(fn () => $dbForPlatform->getDocument('platforms', $platformId));
if ($platform->isEmpty() || $platform->getAttribute('projectInternalId', '') !== $project->getSequence()) {
throw new Exception(Exception::PLATFORM_NOT_FOUND);
}
if ($platform->getAttribute('type', '') !== Platform::TYPE_WINDOWS) {
throw new Exception(Exception::PLATFORM_METHOD_UNSUPPORTED);
}
$updates = new Document([
'name' => $name,
'key' => $packageIdentifierName,
]);
try {
$platform = $authorization->skip(fn () => $dbForPlatform->updateDocument('platforms', $platform->getId(), $updates));
} catch (Duplicate) {
throw new Exception(Exception::PLATFORM_ALREADY_EXISTS);
}
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents->setParam('platformId', $platform->getId());
$response->dynamic($platform, Response::MODEL_PLATFORM_WINDOWS);
}
}
@@ -0,0 +1,130 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Platforms;
use Appwrite\Extend\Exception;
use Appwrite\Network\Platform;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Database\Validator\Queries\Platforms;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Order as OrderException;
use Utopia\Database\Exception\Query as QueryException;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\Query\Cursor;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Boolean;
class XList extends Action
{
use HTTP;
public static function getName()
{
return 'listProjectPlatforms';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/v1/project/platforms')
->httpAlias('/v1/projects/:projectId/platforms')
->desc('List project platforms')
->groups(['api', 'project'])
->label('scope', 'platforms.read')
->label('sdk', new Method(
namespace: 'project',
group: 'platforms',
name: 'listPlatforms',
description: <<<EOT
Get a list of all platforms in the project. This endpoint returns an array of all platforms and their configurations.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_PLATFORM_LIST,
)
]
))
->param('queries', [], new Platforms(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Platforms::ALLOWED_ATTRIBUTES), true)
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('project')
->inject('response')
->inject('dbForPlatform')
->inject('authorization')
->callback($this->action(...));
}
/**
* @param array<string> $queries
*/
public function action(
array $queries,
bool $includeTotal,
Document $project,
Response $response,
Database $dbForPlatform,
Authorization $authorization,
) {
try {
$queries = Query::parseQueries($queries);
} catch (QueryException $e) {
throw new Exception(Exception::GENERAL_QUERY_INVALID, $e->getMessage());
}
foreach ($queries as $query) {
if (\in_array($query->getAttribute(), ['bundleIdentifier', 'applicationId', 'packageIdentifierName', 'packageName'])) {
$query->setAttribute('key');
}
}
$queries[] = Query::equal('projectInternalId', [$project->getSequence()]);
$cursor = Query::getCursorQueries($queries, false);
$cursor = \reset($cursor);
if ($cursor !== false) {
$validator = new Cursor();
if (!$validator->isValid($cursor)) {
throw new Exception(Exception::GENERAL_QUERY_INVALID, $validator->getDescription());
}
$platformId = $cursor->getValue();
$cursorDocument = $authorization->skip(fn () => $dbForPlatform->findOne('platforms', [
Query::equal('$id', [$platformId]),
Query::equal('projectInternalId', [$project->getSequence()]),
]));
if ($cursorDocument->isEmpty()) {
throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, "Platform '{$platformId}' for the 'cursor' value not found.");
}
$cursor->setValue($cursorDocument);
}
$filterQueries = Query::groupByType($queries)['filters'];
try {
$platforms = $authorization->skip(fn () => $dbForPlatform->find('platforms', $queries));
$total = $includeTotal ? $authorization->skip(fn () => $dbForPlatform->count('platforms', $filterQueries, APP_LIMIT_COUNT)) : 0;
} catch (OrderException $e) {
throw new Exception(Exception::DATABASE_QUERY_ORDER_NULL, "The order attribute '{$e->getAttribute()}' had a null value. Cursor pagination requires all documents order attribute values are non-null.");
}
foreach ($platforms as $platform) {
$platform->setAttribute('type', Platform::mapDeprecatedType($platform->getAttribute('type')));
}
$response->dynamic(new Document([
'platforms' => $platforms,
'total' => $total,
]), Response::MODEL_PLATFORM_LIST);
}
}
@@ -4,7 +4,6 @@ namespace Appwrite\Platform\Modules\Project\Http\Project\Variables;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
@@ -19,7 +18,7 @@ use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Boolean;
use Utopia\Validator\Text;
class Create extends Base
class Create extends Action
{
use HTTP;
@@ -4,7 +4,6 @@ namespace Appwrite\Platform\Modules\Project\Http\Project\Variables;
use Appwrite\Event\Event;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Method;
@@ -16,7 +15,7 @@ use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Delete extends Base
class Delete extends Action
{
use HTTP;
@@ -35,7 +34,7 @@ class Delete extends Base
->label('scope', 'project.write')
->label('event', 'variables.[variableId].delete')
->label('audits.event', 'project.variable.delete')
->label('audits.resource', 'project.variable/{response.$id}')
->label('audits.resource', 'project.variable/{request.variableId}')
->label('sdk', new Method(
namespace: 'project',
group: 'variables',
@@ -3,7 +3,6 @@
namespace Appwrite\Platform\Modules\Project\Http\Project\Variables;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
@@ -13,7 +12,7 @@ use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Get extends Base
class Get extends Action
{
use HTTP;
@@ -4,7 +4,6 @@ namespace Appwrite\Platform\Modules\Project\Http\Project\Variables;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
@@ -19,7 +18,7 @@ use Utopia\Validator\Boolean;
use Utopia\Validator\Nullable;
use Utopia\Validator\Text;
class Update extends Base
class Update extends Action
{
use HTTP;
@@ -3,7 +3,6 @@
namespace Appwrite\Platform\Modules\Project\Http\Project\Variables;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
@@ -19,7 +18,7 @@ use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Boolean;
class XList extends Base
class XList extends Action
{
use HTTP;
@@ -3,7 +3,25 @@
namespace Appwrite\Platform\Modules\Project\Services;
use Appwrite\Platform\Modules\Project\Http\Init;
use Appwrite\Platform\Modules\Project\Http\Project\Keys\Create as CreateKey;
use Appwrite\Platform\Modules\Project\Http\Project\Keys\Delete as DeleteKey;
use Appwrite\Platform\Modules\Project\Http\Project\Keys\Get as GetKey;
use Appwrite\Platform\Modules\Project\Http\Project\Keys\Update as UpdateKey;
use Appwrite\Platform\Modules\Project\Http\Project\Keys\XList as ListKeys;
use Appwrite\Platform\Modules\Project\Http\Project\Labels\Update as UpdateProjectLabels;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Android\Create as CreateAndroidPlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Android\Update as UpdateAndroidPlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Apple\Create as CreateApplePlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Apple\Update as UpdateApplePlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Delete as DeletePlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Get as GetPlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Linux\Create as CreateLinuxPlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Linux\Update as UpdateLinuxPlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Web\Create as CreateWebPlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Web\Update as UpdateWebPlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Windows\Create as CreateWindowsPlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Windows\Update as UpdateWindowsPlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\XList as ListPlatforms;
use Appwrite\Platform\Modules\Project\Http\Project\Variables\Create as CreateVariable;
use Appwrite\Platform\Modules\Project\Http\Project\Variables\Delete as DeleteVariable;
use Appwrite\Platform\Modules\Project\Http\Project\Variables\Get as GetVariable;
@@ -21,12 +39,35 @@ class Http extends Service
$this->addAction(Init::getName(), new Init());
// Project
$this->addAction(UpdateProjectLabels::getName(), new UpdateProjectLabels());
// Variables
$this->addAction(CreateVariable::getName(), new CreateVariable());
$this->addAction(ListVariables::getName(), new ListVariables());
$this->addAction(GetVariable::getName(), new GetVariable());
$this->addAction(DeleteVariable::getName(), new DeleteVariable());
$this->addAction(UpdateVariable::getName(), new UpdateVariable());
$this->addAction(UpdateProjectLabels::getName(), new UpdateProjectLabels());
// Keys
$this->addAction(CreateKey::getName(), new CreateKey());
$this->addAction(ListKeys::getName(), new ListKeys());
$this->addAction(GetKey::getName(), new GetKey());
$this->addAction(DeleteKey::getName(), new DeleteKey());
$this->addAction(UpdateKey::getName(), new UpdateKey());
// Platforms
$this->addAction(DeletePlatform::getName(), new DeletePlatform());
$this->addAction(UpdateWebPlatform::getName(), new UpdateWebPlatform());
$this->addAction(UpdateApplePlatform::getName(), new UpdateApplePlatform());
$this->addAction(UpdateAndroidPlatform::getName(), new UpdateAndroidPlatform());
$this->addAction(UpdateWindowsPlatform::getName(), new UpdateWindowsPlatform());
$this->addAction(UpdateLinuxPlatform::getName(), new UpdateLinuxPlatform());
$this->addAction(CreateWebPlatform::getName(), new CreateWebPlatform());
$this->addAction(CreateApplePlatform::getName(), new CreateApplePlatform());
$this->addAction(CreateAndroidPlatform::getName(), new CreateAndroidPlatform());
$this->addAction(CreateWindowsPlatform::getName(), new CreateWindowsPlatform());
$this->addAction(CreateLinuxPlatform::getName(), new CreateLinuxPlatform());
$this->addAction(GetPlatform::getName(), new GetPlatform());
$this->addAction(ListPlatforms::getName(), new ListPlatforms());
}
}
@@ -79,7 +79,7 @@ class Delete extends Action
Device $deviceForFiles,
DeleteEvent $queueForDeletes,
Authorization $authorization,
User $user
User $user,
) {
$bucket = $authorization->skip(fn () => $dbForProject->getDocument('buckets', $bucketId));
@@ -110,10 +110,17 @@ class Delete extends Action
$deviceDeleted = false;
if ($file->getAttribute('chunksTotal') !== $file->getAttribute('chunksUploaded')) {
$deviceDeleted = $deviceForFiles->abort(
$file->getAttribute('path'),
($file->getAttribute('metadata', [])['uploadId'] ?? '')
);
try {
$deviceDeleted = $deviceForFiles->abort(
$file->getAttribute('path'),
($file->getAttribute('metadata', [])['uploadId'] ?? '')
);
} catch (\Exception $e) {
// If the partial upload chunks are already gone from the device
// (e.g. the upload never wrote anything to disk), treat it as deleted
// so the pending file document can still be removed from the database.
$deviceDeleted = true;
}
} else {
$deviceDeleted = $deviceForFiles->delete($file->getAttribute('path'));
}
@@ -15,7 +15,6 @@ use Utopia\Compression\Algorithms\GZIP;
use Utopia\Compression\Algorithms\Zstd;
use Utopia\Compression\Compression;
use Utopia\Config\Config;
use Utopia\Console;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
@@ -26,6 +25,7 @@ use Utopia\Http\Adapter\Swoole\Request;
use Utopia\Image\Image;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Span\Span;
use Utopia\Storage\Device;
use Utopia\System\System;
use Utopia\Validator\HexColor;
@@ -54,6 +54,7 @@ class Get extends Action
->label('cache', true)
->label('cache.resourceType', 'bucket/{request.bucketId}')
->label('cache.resource', 'file/{request.fileId}')
->label('cache.params', ['width', 'height', 'gravity', 'quality', 'borderWidth', 'borderColor', 'borderRadius', 'opacity', 'rotation', 'background', 'output'])
->label('sdk', new Method(
namespace: 'storage',
group: 'files',
@@ -268,7 +269,17 @@ class Get extends Action
$totalTime = \microtime(true) - $startTime;
Console::info("File preview rendered,project=" . $project->getId() . ",bucket=" . $bucketId . ",file=" . $file->getId() . ",uri=" . $request->getURI() . ",total=" . $totalTime . ",rendering=" . $renderingTime . ",decryption=" . $decryptionTime . ",decompression=" . $decompressionTime . ",download=" . $downloadTime);
Span::add('storage.file.id', $file->getId());
Span::add('storage.bucket.id', $bucketId);
Span::add('storage.file.size_bytes', $file->getAttribute('sizeActual'));
if (!empty($type)) {
Span::add('storage.file.extension', $type);
}
Span::add('storage.timing.download_seconds', $downloadTime);
Span::add('storage.timing.decryption_seconds', $decryptionTime);
Span::add('storage.timing.decompression_seconds', $decompressionTime);
Span::add('storage.timing.rendering_seconds', $renderingTime);
Span::add('storage.timing.total_seconds', $totalTime);
$contentType = (\array_key_exists($output, $outputs)) ? $outputs[$output] : $outputs['jpg'];
@@ -277,7 +288,9 @@ class Get extends Action
$transformedAt = $file->getAttribute('transformedAt', '');
if (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_PROJECT_ACCESS)) > $transformedAt) {
$file->setAttribute('transformedAt', DateTime::now());
$authorization->skip(fn () => $dbForProject->updateDocument('bucket_' . $file->getAttribute('bucketInternalId'), $file->getId(), $file));
$authorization->skip(fn () => $dbForProject->updateDocument('bucket_' . $file->getAttribute('bucketInternalId'), $file->getId(), new Document([
'transformedAt' => $file->getAttribute('transformedAt'),
])));
}
}
@@ -103,6 +103,7 @@ class XList extends Action
'userEmail' => $log['data']['userEmail'] ?? null,
'userName' => $log['data']['userName'] ?? null,
'mode' => $log['data']['mode'] ?? null,
'userType' => $log['data']['userType'] ?? null,
'ip' => $log['ip'],
'time' => $log['time'],
'osCode' => $os['osCode'],
@@ -5,7 +5,6 @@ namespace Appwrite\Platform\Modules\Webhooks\Http\Webhooks;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Event\Validator\Event;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
@@ -25,7 +24,7 @@ use Utopia\Validator\Multiple;
use Utopia\Validator\Text;
use Utopia\Validator\URL;
class Create extends Base
class Create extends Action
{
use HTTP;
@@ -4,7 +4,6 @@ namespace Appwrite\Platform\Modules\Webhooks\Http\Webhooks;
use Appwrite\Event\Event;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Method;
@@ -18,7 +17,7 @@ use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Delete extends Base
class Delete extends Action
{
use HTTP;
@@ -3,7 +3,6 @@
namespace Appwrite\Platform\Modules\Webhooks\Http\Webhooks;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
@@ -16,7 +15,7 @@ use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Get extends Base
class Get extends Action
{
use HTTP;
@@ -4,7 +4,6 @@ namespace Appwrite\Platform\Modules\Webhooks\Http\Webhooks\Signature;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
@@ -17,7 +16,7 @@ use Utopia\Database\Validator\UID;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Update extends Base
class Update extends Action
{
use HTTP;
@@ -5,7 +5,6 @@ namespace Appwrite\Platform\Modules\Webhooks\Http\Webhooks;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Event\Validator\Event;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
@@ -24,7 +23,7 @@ use Utopia\Validator\Multiple;
use Utopia\Validator\Text;
use Utopia\Validator\URL;
class Update extends Base
class Update extends Action
{
use HTTP;
@@ -3,7 +3,6 @@
namespace Appwrite\Platform\Modules\Webhooks\Http\Webhooks;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Compute\Base;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
@@ -20,7 +19,7 @@ use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Boolean;
class XList extends Base
class XList extends Action
{
use HTTP;
+5 -19
View File
@@ -639,29 +639,15 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
} catch (\Throwable) {
}
// Checkout dev branch (or create if it doesn't exist)
// Create or checkout dev branch from the base branch
// This ensures dev always starts from the latest base branch,
// avoiding history divergence caused by squash merges.
try {
$repo->execute('checkout', '-f', $gitBranch);
$repo->execute('checkout', '-B', $gitBranch, $repoBranch);
} catch (\Throwable) {
$repo->execute('checkout', '-b', $gitBranch);
}
// Fetch dev branch, or push to create it on remote
try {
$repo->execute('fetch', 'origin', $gitBranch, '--quiet', '--no-tags', '--depth', '1');
} catch (\Throwable) {
try {
$repo->execute('push', '-u', 'origin', $gitBranch, '--quiet');
} catch (\Throwable) {
}
}
// Sync with remote dev branch
try {
$repo->execute('reset', '--hard', "origin/{$gitBranch}");
} catch (\Throwable) {
}
// Backup .github before cleaning working tree
$githubDir = $target . '/.github';
$githubBackup = \sys_get_temp_dir() . '/.github-backup-' . \getmypid();
@@ -699,7 +685,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
return true;
}
$repo->execute('push', '-u', 'origin', $gitBranch, '--quiet');
$repo->execute('push', '--force-with-lease', '-u', 'origin', $gitBranch, '--quiet');
} catch (\Throwable $e) {
Console::warning(" Git push failed: " . $e->getMessage());
return false;
+7 -3
View File
@@ -21,7 +21,6 @@ use Utopia\Database\Adapter\MySQL;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\DI\Container;
use Utopia\Http\Adapter\FPM\Server as FPMServer;
use Utopia\Http\Http;
use Utopia\Http\Request as UtopiaRequest;
use Utopia\Http\Response as UtopiaResponse;
@@ -448,7 +447,7 @@ class Specs extends Action
}
$arguments = [
new Http(new FPMServer($specsContainer), 'UTC'),
$specsContainer,
$services,
$routes,
$models,
@@ -482,7 +481,12 @@ class Specs extends Action
? $specsDir . '/' . $format . '-mocks-' . $platform . '.json'
: $specsDir . '/' . $format . '-' . $version . '-' . $platform . '.json';
$parsedSpecs = $specs->parse();
try {
$parsedSpecs = $specs->parse();
} catch (\RuntimeException $e) {
throw new \RuntimeException("Spec generation failed for {$platform} ({$format}): " . $e->getMessage(), 0, $e);
}
$encodedSpecs = \json_encode($parsedSpecs, JSON_PRETTY_PRINT);
unset($parsedSpecs);
+5 -1
View File
@@ -379,7 +379,11 @@ class Migrations extends Action
'webhooks.read',
'webhooks.write',
'project.read',
'project.write'
'project.write',
'keys.read',
'keys.write',
'platforms.read',
'platforms.write',
]
]);
+29 -4
View File
@@ -4,12 +4,12 @@ namespace Appwrite\SDK\Specification;
use Appwrite\Utopia\Response\Model;
use Utopia\Config\Config;
use Utopia\Http\Http;
use Utopia\DI\Container;
use Utopia\Http\Route;
abstract class Format
{
protected Http $app;
protected Container $container;
/**
* @var array<Route>
@@ -80,9 +80,9 @@ abstract class Format
protected array $enumBlacklist = [];
public function __construct(Http $app, array $services, array $routes, array $models, array $keys, int $authCount, string $platform)
public function __construct(Container $container, array $services, array $routes, array $models, array $keys, int $authCount, string $platform)
{
$this->app = $app;
$this->container = $container;
$this->services = $services;
$this->routes = $routes;
$this->models = $models;
@@ -210,6 +210,28 @@ abstract class Format
return $this->services;
}
/**
* @param list<string> $injections
* @return array<string, mixed>
*/
protected function getResources(array $injections): array
{
$resources = [];
foreach ($injections as $name) {
$resources[$name] = $this->container->get($name);
}
return $resources;
}
protected function getValidator(array $param): mixed
{
return \is_callable($param['validator'])
? ($param['validator'])(...$this->getResources($param['injections'] ?? []))
: $param['validator'];
}
protected function getDescriptionContents(?string $description): string
{
if ($description === null || $description === '') {
@@ -769,6 +791,9 @@ abstract class Format
protected function getNestedModels(Model $model, array &$usedModels): void
{
foreach ($model->getRules() as $rule) {
if (($rule['hidden'] ?? false) === true) {
continue;
}
if (!in_array($model->getType(), $usedModels)) {
continue;
}
@@ -278,6 +278,18 @@ class OpenAPI3 extends Format
}
}
if (\is_string($model)) {
throw new \RuntimeException("Unresolved response model '{$model}' for method '{$sdk->getNamespace()}.{$sdk->getMethodName()}'. Ensure the model is registered.");
}
if (\is_array($model)) {
foreach ($model as $m) {
if (\is_string($m)) {
throw new \RuntimeException("Unresolved response model '{$m}' for method '{$sdk->getNamespace()}.{$sdk->getMethodName()}'. Ensure the model is registered.");
}
}
}
if (!(\is_array($model)) && $model->isNone()) {
$temp['responses'][(string)$response->getCode() ?? '500'] = [
'description' => in_array($produces, [
@@ -367,7 +379,7 @@ class OpenAPI3 extends Format
/**
* @var \Utopia\Validator $validator
*/
$validator = (\is_callable($param['validator'])) ? call_user_func_array($param['validator'], $this->app->getResources($param['injections'])) : $param['validator'];
$validator = $this->getValidator($param);
$node = [
'name' => $name,
@@ -821,6 +833,10 @@ class OpenAPI3 extends Format
}
foreach ($model->getRules() as $name => $rule) {
if (($rule['hidden'] ?? false) === true) {
continue;
}
$type = '';
$format = null;
$items = null;
@@ -285,6 +285,18 @@ class Swagger2 extends Format
}
}
if (\is_string($model)) {
throw new \RuntimeException("Unresolved response model '{$model}' for method '{$sdk->getNamespace()}.{$sdk->getMethodName()}'. Ensure the model is registered.");
}
if (\is_array($model)) {
foreach ($model as $m) {
if (\is_string($m)) {
throw new \RuntimeException("Unresolved response model '{$m}' for method '{$sdk->getNamespace()}.{$sdk->getMethodName()}'. Ensure the model is registered.");
}
}
}
if (!(\is_array($model)) && $model->isNone()) {
$temp['responses'][(string)$response->getCode() ?? '500'] = [
'description' => in_array($produces, [
@@ -369,9 +381,7 @@ class Swagger2 extends Format
}
/** @var Validator $validator */
$validator = (\is_callable($param['validator']))
? ($param['validator'])(...$this->app->getResources($param['injections']))
: $param['validator'];
$validator = $this->getValidator($param);
$node = [
'name' => $name,
@@ -801,6 +811,10 @@ class Swagger2 extends Format
}
foreach ($model->getRules() as $name => $rule) {
if (($rule['hidden'] ?? false) === true) {
continue;
}
$type = '';
$format = null;
$items = null;
@@ -0,0 +1,25 @@
<?php
namespace Appwrite\Utopia\Database\Validator\Queries;
class Platforms extends Base
{
public const ALLOWED_ATTRIBUTES = [
'type',
'name',
'hostname',
'bundleIdentifier',
'applicationId',
'packageIdentifierName',
'packageName',
];
/**
* Expression constructor
*
*/
public function __construct()
{
parent::__construct('platforms', self::ALLOWED_ATTRIBUTES);
}
}
+4
View File
@@ -234,6 +234,10 @@ class Request extends UtopiaRequest
public function cacheIdentifier(): string
{
$params = $this->getParams();
$allowedParams = $this->getRoute()?->getLabel('cache.params', null);
if ($allowedParams !== null) {
$params = array_intersect_key($params, array_flip($allowedParams));
}
ksort($params);
return md5($this->getURI() . '*' . serialize($params) . '*' . APP_CACHE_BUSTER);
}
@@ -11,9 +11,69 @@ class V21 extends Filter
public function parse(array $content, string $model): array
{
switch ($model) {
// Web is special case compared to others, because it holds backwards compatibility logic
case 'project.createWebPlatform':
$content = $this->fillPlatformId($content);
$content = $this->removePlatformStore($content);
// Keep 'key' for backwards compatibility
break;
case 'project.updateWebPlatform':
$content = $this->removePlatformStore($content);
// Keep 'key' for backwards compatibility
break;
case 'project.createApplePlatform':
$content = $this->fillPlatformId($content);
$content = $this->removePlatformStore($content);
$content = $this->replacePlatformKey($content, 'bundleIdentifier');
unset($content['hostname']); // Hostname unsupported
break;
case 'project.updateApplePlatform':
$content = $this->removePlatformStore($content);
$content = $this->replacePlatformKey($content, 'bundleIdentifier');
unset($content['hostname']); // Hostname unsupported
break;
case 'project.createAndroidPlatform':
$content = $this->fillPlatformId($content);
$content = $this->removePlatformStore($content);
$content = $this->replacePlatformKey($content, 'applicationId');
unset($content['hostname']); // Hostname unsupported
break;
case 'project.updateAndroidPlatform':
$content = $this->removePlatformStore($content);
$content = $this->replacePlatformKey($content, 'applicationId');
unset($content['hostname']); // Hostname unsupported
break;
case 'project.createWindowsPlatform':
$content = $this->fillPlatformId($content);
$content = $this->removePlatformStore($content);
$content = $this->replacePlatformKey($content, 'packageIdentifierName');
unset($content['hostname']); // Hostname unsupported
break;
case 'project.updateWindowsPlatform':
$content = $this->removePlatformStore($content);
$content = $this->replacePlatformKey($content, 'packageIdentifierName');
unset($content['hostname']); // Hostname unsupported
break;
case 'project.createLinuxPlatform':
$content = $this->fillPlatformId($content);
$content = $this->removePlatformStore($content);
$content = $this->replacePlatformKey($content, 'packageName');
unset($content['hostname']); // Hostname unsupported
break;
case 'project.updateLinuxPlatform':
$content = $this->removePlatformStore($content);
$content = $this->replacePlatformKey($content, 'packageName');
unset($content['hostname']); // Hostname unsupported
break;
case 'project.listPlatforms':
$content = $this->preservePlatformsQueries($content);
break;
case 'webhooks.create':
$content = $this->fillWebhookid($content);
break;
case 'project.createKey':
$content = $this->fillKeyId($content);
break;
case 'project.createVariable':
$content = $this->fillVariableId($content);
break;
@@ -65,6 +125,12 @@ class V21 extends Filter
return $content;
}
protected function fillKeyId(array $content): array
{
$content['keyId'] = $content['keyId'] ?? 'unique()';
return $content;
}
protected function fillVariableId(array $content): array
{
$content['variableId'] = $content['variableId'] ?? 'unique()';
@@ -79,4 +145,33 @@ class V21 extends Filter
return $content;
}
protected function fillPlatformId(array $content): array
{
$content['platformId'] = $content['platformId'] ?? 'unique()';
return $content;
}
protected function replacePlatformKey(array $content, string $newKey): array
{
$content[$newKey] = $content[$newKey] ?? $content['key'] ?? null;
unset($content['key']);
return $content;
}
protected function removePlatformStore(array $content): array
{
unset($content['store']);
return $content;
}
protected function preservePlatformsQueries(array $content): array
{
$content['queries'] = $content['queries'] ?? [
Query::limit(5000)
];
return $content;
}
}
+12 -2
View File
@@ -256,7 +256,11 @@ class Response extends SwooleResponse
public const MODEL_MOCK_NUMBER = 'mockNumber';
public const MODEL_AUTH_PROVIDER = 'authProvider';
public const MODEL_AUTH_PROVIDER_LIST = 'authProviderList';
public const MODEL_PLATFORM = 'platform';
public const MODEL_PLATFORM_APPLE = 'platformApple';
public const MODEL_PLATFORM_ANDROID = 'platformAndroid';
public const MODEL_PLATFORM_WINDOWS = 'platformWindows';
public const MODEL_PLATFORM_LINUX = 'platformLinux';
public const MODEL_PLATFORM_WEB = 'platformWeb';
public const MODEL_PLATFORM_LIST = 'platformList';
public const MODEL_VARIABLE = 'variable';
public const MODEL_VARIABLE_LIST = 'variableList';
@@ -476,7 +480,13 @@ class Response extends SwooleResponse
foreach ($rule['type'] as $type) {
$condition = false;
foreach ($this->getModel($type)->conditions as $attribute => $val) {
$condition = $item->getAttribute($attribute) === $val;
if (\is_array($val)) {
$condition = \in_array($item->getAttribute($attribute), $val);
} else {
$condition = $item->getAttribute($attribute) === $val;
}
if (!$condition) {
break;
}
@@ -11,6 +11,23 @@ class V21 extends Filter
public function parse(array $content, string $model): array
{
return match ($model) {
// Web is special case, it has backwards compatibility
Response::MODEL_PLATFORM_WEB => $this->parsePlatform($content),
Response::MODEL_PLATFORM_APPLE => $this->parsePlatform($content),
Response::MODEL_PLATFORM_ANDROID => $this->parsePlatform($content),
Response::MODEL_PLATFORM_WINDOWS => $this->parsePlatform($content),
Response::MODEL_PLATFORM_LINUX => $this->parsePlatform($content),
Response::MODEL_PLATFORM_LIST => $this->handleList(
$content,
"platforms",
fn ($item) => $this->parsePlatform($item),
),
Response::MODEL_PROJECT => $this->parseProjectForPlatform($content),
Response::MODEL_PROJECT_LIST => $this->handleList(
$content,
"projects",
fn ($item) => $this->parseProjectForPlatform($item),
),
Response::MODEL_USER => $this->parseUser($content),
Response::MODEL_USER_LIST => $this->handleList(
$content,
@@ -107,4 +124,34 @@ class V21 extends Filter
return $content;
}
protected function parseProjectForPlatform(array $content): array
{
// Parse platforms under project, since it's a subquery
$content['platforms'] = \array_map(fn ($item) => $this->parsePlatform($item), $content['platforms']);
return $content;
}
protected function parsePlatform(array $content): array
{
// Map platform-specific identifier fields back to 'key'
$content['key'] =
($content['bundleIdentifier'] ?? '')
?: ($content['applicationId'] ?? '')
?: ($content['packageIdentifierName'] ?? '')
?: ($content['packageName'] ?? '')
?: ($content['key'] ?? '')
?: '';
unset($content['bundleIdentifier']);
unset($content['applicationId']);
unset($content['packageIdentifierName']);
unset($content['packageName']);
// Restore fields removed in v1.9
$content['store'] = $content['store'] ?? '';
$content['hostname'] = $content['hostname'] ?? '';
return $content;
}
}
@@ -7,11 +7,6 @@ use Appwrite\Utopia\Response\Model;
class AuthProvider extends Model
{
/**
* @var bool
*/
protected bool $public = false;
public function __construct()
{
$this
@@ -7,11 +7,6 @@ use Appwrite\Utopia\Response\Model;
class DevKey extends Model
{
/**
* @var bool
*/
protected bool $public = false;
public function __construct()
{
$this
@@ -40,6 +40,12 @@ class Log extends Model
'default' => '',
'example' => 'admin',
])
->addRule('userType', [
'type' => self::TYPE_STRING,
'description' => 'User type who triggered the audit log. Possible values: user, admin, guest, keyProject, keyAccount, keyOrganization.',
'default' => '',
'example' => 'user',
])
->addRule('ip', [
'type' => self::TYPE_STRING,
'description' => 'IP session in use when the session was created.',
@@ -1,100 +0,0 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;
class Platform extends Model
{
/**
* @var bool
*/
protected bool $public = false;
public function __construct()
{
$this
->addRule('$id', [
'type' => self::TYPE_STRING,
'description' => 'Platform ID.',
'default' => '',
'example' => '5e5ea5c16897e',
])
->addRule('$createdAt', [
'type' => self::TYPE_DATETIME,
'description' => 'Platform creation date in ISO 8601 format.',
'default' => '',
'example' => self::TYPE_DATETIME_EXAMPLE,
])
->addRule('$updatedAt', [
'type' => self::TYPE_DATETIME,
'description' => 'Platform update date in ISO 8601 format.',
'default' => '',
'example' => self::TYPE_DATETIME_EXAMPLE,
])
->addRule('name', [
'type' => self::TYPE_STRING,
'description' => 'Platform name.',
'default' => '',
'example' => 'My Web App',
])
->addRule('type', [
'type' => self::TYPE_ENUM,
'description' => 'Platform type. Possible values are: web, flutter-web, flutter-ios, flutter-android, flutter-linux, flutter-macos, flutter-windows, apple-ios, apple-macos, apple-watchos, apple-tvos, android, unity, react-native-ios, react-native-android.',
'default' => '',
'example' => 'web',
'enum' => ['web', 'flutter-web', 'flutter-ios', 'flutter-android', 'flutter-linux', 'flutter-macos', 'flutter-windows', 'apple-ios', 'apple-macos', 'apple-watchos', 'apple-tvos', 'android', 'unity', 'react-native-ios', 'react-native-android'],
])
->addRule('key', [
'type' => self::TYPE_STRING,
'description' => 'Platform Key. iOS bundle ID or Android package name. Empty string for other platforms.',
'default' => '',
'example' => 'com.company.appname',
])
->addRule('store', [
'type' => self::TYPE_STRING,
'description' => 'App store or Google Play store ID.',
'example' => '',
])
->addRule('hostname', [
'type' => self::TYPE_STRING,
'description' => 'Web app hostname. Empty string for other platforms.',
'default' => '',
'example' => 'app.example.com',
])
->addRule('httpUser', [
'type' => self::TYPE_STRING,
'description' => 'HTTP basic authentication username.',
'default' => '',
'example' => 'username',
])
->addRule('httpPass', [
'type' => self::TYPE_STRING,
'description' => 'HTTP basic authentication password.',
'default' => '',
'example' => 'password',
])
;
}
/**
* Get Name
*
* @return string
*/
public function getName(): string
{
return 'Platform';
}
/**
* Get Type
*
* @return string
*/
public function getType(): string
{
return Response::MODEL_PLATFORM;
}
}
@@ -0,0 +1,58 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Network\Platform;
use Appwrite\Utopia\Response;
use Utopia\Database\Document;
class PlatformAndroid extends PlatformBase
{
public function __construct()
{
$this->conditions = [
'type' => Platform::TYPE_ANDROID,
];
parent::__construct();
$this
->addRule('applicationId', [
'type' => self::TYPE_STRING,
'description' => 'Android application ID.',
'default' => '',
'example' => 'com.company.appname',
])
;
}
/**
* Get Name
*
* @return string
*/
public function getName(): string
{
return 'Platform Android';
}
/**
* Get Type
*
* @return string
*/
public function getType(): string
{
return Response::MODEL_PLATFORM_ANDROID;
}
public function filter(Document $document): Document
{
// DB level: 'key'
// API level: 'applicationId'
$document->setAttribute('applicationId', $document->getAttribute('key', null));
$document->removeAttribute('key');
return $document;
}
}
@@ -0,0 +1,58 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Network\Platform;
use Appwrite\Utopia\Response;
use Utopia\Database\Document;
class PlatformApple extends PlatformBase
{
public function __construct()
{
$this->conditions = [
'type' => Platform::TYPE_APPLE,
];
parent::__construct();
$this
->addRule('bundleIdentifier', [
'type' => self::TYPE_STRING,
'description' => 'Apple bundle identifier.',
'default' => '',
'example' => 'com.company.appname',
])
;
}
/**
* Get Name
*
* @return string
*/
public function getName(): string
{
return 'Platform Apple';
}
/**
* Get Type
*
* @return string
*/
public function getType(): string
{
return Response::MODEL_PLATFORM_APPLE;
}
public function filter(Document $document): Document
{
// DB level: 'key'
// API level: 'bundleIdentifier'
$document->setAttribute('bundleIdentifier', $document->getAttribute('key', null));
$document->removeAttribute('key');
return $document;
}
}
@@ -0,0 +1,57 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Network\Platform;
use Appwrite\Utopia\Response\Model;
abstract class PlatformBase extends Model
{
public function getSupportedTypes(): array
{
return [
Platform::TYPE_WINDOWS,
Platform::TYPE_APPLE,
Platform::TYPE_ANDROID,
Platform::TYPE_LINUX,
Platform::TYPE_WEB,
];
}
public function __construct()
{
$this
->addRule('$id', [
'type' => self::TYPE_STRING,
'description' => 'Platform ID.',
'default' => '',
'example' => '5e5ea5c16897e',
])
->addRule('$createdAt', [
'type' => self::TYPE_DATETIME,
'description' => 'Platform creation date in ISO 8601 format.',
'default' => '',
'example' => self::TYPE_DATETIME_EXAMPLE,
])
->addRule('$updatedAt', [
'type' => self::TYPE_DATETIME,
'description' => 'Platform update date in ISO 8601 format.',
'default' => '',
'example' => self::TYPE_DATETIME_EXAMPLE,
])
->addRule('name', [
'type' => self::TYPE_STRING,
'description' => 'Platform name.',
'default' => '',
'example' => 'My Web App',
])
->addRule('type', [
'type' => self::TYPE_ENUM,
'description' => 'Platform type. Possible values are: ' . implode(', ', self::getSupportedTypes()) . '.',
'default' => '',
'example' => Platform::TYPE_WEB,
'enum' => self::getSupportedTypes(),
])
;
}
}
@@ -0,0 +1,58 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Network\Platform;
use Appwrite\Utopia\Response;
use Utopia\Database\Document;
class PlatformLinux extends PlatformBase
{
public function __construct()
{
$this->conditions = [
'type' => Platform::TYPE_LINUX,
];
parent::__construct();
$this
->addRule('packageName', [
'type' => self::TYPE_STRING,
'description' => 'Linux package name.',
'default' => '',
'example' => 'com.company.appname',
])
;
}
/**
* Get Name
*
* @return string
*/
public function getName(): string
{
return 'Platform Linux';
}
/**
* Get Type
*
* @return string
*/
public function getType(): string
{
return Response::MODEL_PLATFORM_LINUX;
}
public function filter(Document $document): Document
{
// DB level: 'key'
// API level: 'packageName'
$document->setAttribute('packageName', $document->getAttribute('key', null));
$document->removeAttribute('key');
return $document;
}
}
@@ -0,0 +1,53 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;
class PlatformList extends Model
{
public function __construct()
{
$this
->addRule('total', [
'type' => self::TYPE_INTEGER,
'description' => 'Total number of platforms in the given project.',
'default' => 0,
'example' => 5,
])
->addRule('platforms', [
'type' => [
Response::MODEL_PLATFORM_WEB,
Response::MODEL_PLATFORM_APPLE,
Response::MODEL_PLATFORM_ANDROID,
Response::MODEL_PLATFORM_WINDOWS,
Response::MODEL_PLATFORM_LINUX,
],
'description' => 'List of platforms.',
'default' => [],
'array' => true
])
;
}
/**
* Get Name
*
* @return string
*/
public function getName(): string
{
return 'Platforms List';
}
/**
* Get Type
*
* @return string
*/
public function getType(): string
{
return Response::MODEL_PLATFORM_LIST;
}
}
@@ -0,0 +1,71 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Network\Platform;
use Appwrite\Utopia\Response;
class PlatformWeb extends PlatformBase
{
public function __construct()
{
$this->conditions = [
'type' => [
Platform::TYPE_WEB,
// Backwards compatibility
'flutter-web',
'unity',
'flutter-macos',
'flutter-ios',
'react-native-ios',
'apple-ios',
'apple-macos',
'apple-watchos',
'apple-tvos',
'flutter-android',
'react-native-android',
'flutter-windows',
'flutter-linux',
],
];
parent::__construct();
$this
->addRule('hostname', [
'type' => self::TYPE_STRING,
'description' => 'Web app hostname. Empty string for other platforms.',
'default' => '',
'example' => 'app.example.com',
])
// Backwards compatibility
->addRule('key', [
'hidden' => true,
'type' => self::TYPE_STRING,
'description' => 'Deprecated for old versions using alias endpoint to create universal platform.',
'default' => '',
'example' => 'com.company.appname',
])
;
}
/**
* Get Name
*
* @return string
*/
public function getName(): string
{
return 'Platform Web';
}
/**
* Get Type
*
* @return string
*/
public function getType(): string
{
return Response::MODEL_PLATFORM_WEB;
}
}
@@ -0,0 +1,58 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Network\Platform;
use Appwrite\Utopia\Response;
use Utopia\Database\Document;
class PlatformWindows extends PlatformBase
{
public function __construct()
{
$this->conditions = [
'type' => Platform::TYPE_WINDOWS,
];
parent::__construct();
$this
->addRule('packageIdentifierName', [
'type' => self::TYPE_STRING,
'description' => 'Windows package identifier name.',
'default' => '',
'example' => 'com.company.appname',
])
;
}
/**
* Get Name
*
* @return string
*/
public function getName(): string
{
return 'Platform Windows';
}
/**
* Get Type
*
* @return string
*/
public function getType(): string
{
return Response::MODEL_PLATFORM_WINDOWS;
}
public function filter(Document $document): Document
{
// DB level: 'key'
// API level: 'packageIdentifierName'
$document->setAttribute('packageIdentifierName', $document->getAttribute('key', null));
$document->removeAttribute('key');
return $document;
}
}
@@ -9,11 +9,6 @@ use Utopia\Database\Document;
class Project extends Model
{
/**
* @var bool
*/
protected bool $public = false;
public function __construct()
{
$this
@@ -200,7 +195,13 @@ class Project extends Model
'array' => true,
])
->addRule('platforms', [
'type' => Response::MODEL_PLATFORM,
'type' => [
Response::MODEL_PLATFORM_WEB,
Response::MODEL_PLATFORM_APPLE,
Response::MODEL_PLATFORM_ANDROID,
Response::MODEL_PLATFORM_WINDOWS,
Response::MODEL_PLATFORM_LINUX,
],
'description' => 'List of Platforms.',
'default' => [],
'example' => new \stdClass(),
@@ -7,11 +7,6 @@ use Appwrite\Utopia\Response\Model;
class Webhook extends Model
{
/**
* @var bool
*/
protected bool $public = true;
public function __construct()
{
$this
+7 -22
View File
@@ -219,7 +219,8 @@ class Client
curl_setopt($ch, CURLOPT_HTTPHEADER, $formattedHeaders);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $header) use (&$responseHeaders, &$cookies) {
curl_setopt($ch, CURLOPT_COOKIEFILE, ''); // enable in-memory RFC 6265 cookie engine
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $header) use (&$responseHeaders) {
$len = strlen($header);
$header = explode(':', $header, 2);
@@ -227,12 +228,6 @@ class Client
return $len;
}
if (strtolower(trim($header[0])) == 'set-cookie') {
$parsed = $this->parseCookie((string)trim($header[1]));
$name = array_key_first($parsed);
$cookies[$name] = $parsed[$name];
}
$responseHeaders[strtolower(trim($header[0]))] = trim($header[1]);
return $len;
@@ -259,6 +254,11 @@ class Client
$responseType = $responseHeaders['content-type'] ?? '';
$responseStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
foreach (curl_getinfo($ch, CURLINFO_COOKIELIST) as $line) {
$parts = explode("\t", $line);
$cookies[$parts[5]] = $parts[6] ?? '';
}
if ($decode && $method !== self::METHOD_HEAD) {
$strpos = strpos($responseType, ';');
$strpos = \is_bool($strpos) ? \strlen($responseType) : $strpos;
@@ -309,21 +309,6 @@ class Client
];
}
/**
* Parse Cookie String
*
* @param string $cookie
* @return array
*/
public function parseCookie(string $cookie): array
{
$cookies = [];
parse_str(strtr($cookie, ['&' => '%26', '+' => '%2B', ';' => '&']), $cookies);
return $cookies;
}
/**
* Flatten params array to PHP multiple format
*
+5 -1
View File
@@ -164,7 +164,11 @@ trait ProjectCustom
'webhooks.read',
'webhooks.write',
'project.read',
'project.write'
'project.write',
'keys.read',
'keys.write',
'platforms.read',
'platforms.write',
],
]);

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