Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

fix(backend:auth): harden OIDC account binding

johaven710ce71c2d85
diff --git a/backend/migrations/0004_gigantic_romulus.sql b/backend/migrations/0004_gigantic_romulus.sql
new file mode 100644
index 00000000..8f0b20ce
--- /dev/null
+++ b/backend/migrations/0004_gigantic_romulus.sql
@@ -0,0 +1,2 @@
+ALTER TABLE `users` ADD `externalId` varchar(255);--> statement-breakpoint
+ALTER TABLE `users` ADD CONSTRAINT `external_id_idx` UNIQUE(`externalId`);
\ No newline at end of file
diff --git a/backend/migrations/meta/0004_snapshot.json b/backend/migrations/meta/0004_snapshot.json
new file mode 100644
index 00000000..b984acfc
--- /dev/null
+++ b/backend/migrations/meta/0004_snapshot.json
@@ -0,0 +1,2477 @@
+{
+ "version": "5",
+ "dialect": "mysql",
+ "id": "2f63e809-e21d-48a9-bcb6-1d64255bd1b1",
+ "prevId": "da1a6d68-b222-46e6-bda9-2a917b447be2",
+ "tables": {
+ "cache": {
+ "name": "cache",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "varchar(768)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expiration": {
+ "name": "expiration",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": -1
+ }
+ },
+ "indexes": {
+ "expiration_idx": {
+ "name": "expiration_idx",
+ "columns": [
+ "expiration"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "cache_key": {
+ "name": "cache_key",
+ "columns": [
+ "key"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "email": {
+ "name": "email",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "externalId": {
+ "name": "externalId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "firstName": {
+ "name": "firstName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastName": {
+ "name": "lastName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "passwordAttempts": {
+ "name": "passwordAttempts",
+ "type": "tinyint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "role": {
+ "name": "role",
+ "type": "tinyint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "isActive": {
+ "name": "isActive",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "secrets": {
+ "name": "secrets",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "language": {
+ "name": "language",
+ "type": "varchar(10)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "storageUsage": {
+ "name": "storageUsage",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ },
+ "storageQuota": {
+ "name": "storageQuota",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "storageIndexing": {
+ "name": "storageIndexing",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "notification": {
+ "name": "notification",
+ "type": "tinyint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "onlineStatus": {
+ "name": "onlineStatus",
+ "type": "tinyint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "currentIp": {
+ "name": "currentIp",
+ "type": "varchar(45)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastIp": {
+ "name": "lastIp",
+ "type": "varchar(45)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "currentAccess": {
+ "name": "currentAccess",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastAccess": {
+ "name": "lastAccess",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "email_idx": {
+ "name": "email_idx",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ },
+ "login_idx": {
+ "name": "login_idx",
+ "columns": [
+ "login"
+ ],
+ "isUnique": true
+ },
+ "external_id_idx": {
+ "name": "external_id_idx",
+ "columns": [
+ "externalId"
+ ],
+ "isUnique": true
+ },
+ "role_idx": {
+ "name": "role_idx",
+ "columns": [
+ "role"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "users_id": {
+ "name": "users_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "groups": {
+ "name": "groups",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "tinyint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "tinyint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "name_idx": {
+ "name": "name_idx",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ },
+ "parent_idx": {
+ "name": "parent_idx",
+ "columns": [
+ "parentId"
+ ],
+ "isUnique": false
+ },
+ "type_idx": {
+ "name": "type_idx",
+ "columns": [
+ "type"
+ ],
+ "isUnique": false
+ },
+ "visibility_idx": {
+ "name": "visibility_idx",
+ "columns": [
+ "visibility"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "groups_parentId_groups_id_fk": {
+ "name": "groups_parentId_groups_id_fk",
+ "tableFrom": "groups",
+ "tableTo": "groups",
+ "columnsFrom": [
+ "parentId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "groups_id": {
+ "name": "groups_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "users_groups": {
+ "name": "users_groups",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "groupId": {
+ "name": "groupId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "tinyint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "user_idx": {
+ "name": "user_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "group_idx": {
+ "name": "group_idx",
+ "columns": [
+ "groupId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "users_groups_userId_users_id_fk": {
+ "name": "users_groups_userId_users_id_fk",
+ "tableFrom": "users_groups",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "users_groups_groupId_groups_id_fk": {
+ "name": "users_groups_groupId_groups_id_fk",
+ "tableFrom": "users_groups",
+ "tableTo": "groups",
+ "columnsFrom": [
+ "groupId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "users_groups_userId_groupId_pk": {
+ "name": "users_groups_userId_groupId_pk",
+ "columns": [
+ "userId",
+ "groupId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "users_guests": {
+ "name": "users_guests",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guestId": {
+ "name": "guestId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "user_idx": {
+ "name": "user_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "guest_id": {
+ "name": "guest_id",
+ "columns": [
+ "guestId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "users_guests_userId_users_id_fk": {
+ "name": "users_guests_userId_users_id_fk",
+ "tableFrom": "users_guests",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "users_guests_guestId_users_id_fk": {
+ "name": "users_guests_guestId_users_id_fk",
+ "tableFrom": "users_guests",
+ "tableTo": "users",
+ "columnsFrom": [
+ "guestId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "users_guests_userId_guestId_pk": {
+ "name": "users_guests_userId_guestId_pk",
+ "columns": [
+ "userId",
+ "guestId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {
+ "user_guest_check": {
+ "name": "user_guest_check",
+ "value": "`users_guests`.`userId` <> `users_guests`.`guestId`"
+ }
+ }
+ },
+ "spaces": {
+ "name": "spaces",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "alias": {
+ "name": "alias",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "storageUsage": {
+ "name": "storageUsage",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "storageQuota": {
+ "name": "storageQuota",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "storageIndexing": {
+ "name": "storageIndexing",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
+ },
+ "disabledAt": {
+ "name": "disabledAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "alias_idx": {
+ "name": "alias_idx",
+ "columns": [
+ "alias"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "spaces_id": {
+ "name": "spaces_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "spaces_members": {
+ "name": "spaces_members",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "groupId": {
+ "name": "groupId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "linkId": {
+ "name": "linkId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "tinyint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "space_idx": {
+ "name": "space_idx",
+ "columns": [
+ "spaceId"
+ ],
+ "isUnique": false
+ },
+ "user_idx": {
+ "name": "user_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "group_idx": {
+ "name": "group_idx",
+ "columns": [
+ "groupId"
+ ],
+ "isUnique": false
+ },
+ "link_idx": {
+ "name": "link_idx",
+ "columns": [
+ "linkId"
+ ],
+ "isUnique": false
+ },
+ "role_idx": {
+ "name": "role_idx",
+ "columns": [
+ "role"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "spaces_members_spaceId_spaces_id_fk": {
+ "name": "spaces_members_spaceId_spaces_id_fk",
+ "tableFrom": "spaces_members",
+ "tableTo": "spaces",
+ "columnsFrom": [
+ "spaceId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "spaces_members_userId_users_id_fk": {
+ "name": "spaces_members_userId_users_id_fk",
+ "tableFrom": "spaces_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "spaces_members_groupId_groups_id_fk": {
+ "name": "spaces_members_groupId_groups_id_fk",
+ "tableFrom": "spaces_members",
+ "tableTo": "groups",
+ "columnsFrom": [
+ "groupId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "spaces_members_linkId_links_id_fk": {
+ "name": "spaces_members_linkId_links_id_fk",
+ "tableFrom": "spaces_members",
+ "tableTo": "links",
+ "columnsFrom": [
+ "linkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "spaces_members_id": {
+ "name": "spaces_members_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "space_user_uniq": {
+ "name": "space_user_uniq",
+ "columns": [
+ "spaceId",
+ "userId"
+ ]
+ },
+ "space_group_uniq": {
+ "name": "space_group_uniq",
+ "columns": [
+ "spaceId",
+ "groupId"
+ ]
+ },
+ "space_link_uniq": {
+ "name": "space_link_uniq",
+ "columns": [
+ "spaceId",
+ "linkId"
+ ]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "spaces_roots": {
+ "name": "spaces_roots",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fileId": {
+ "name": "fileId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "externalPath": {
+ "name": "externalPath",
+ "type": "varchar(4096)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "alias_idx": {
+ "name": "alias_idx",
+ "columns": [
+ "alias"
+ ],
+ "isUnique": false
+ },
+ "space_idx": {
+ "name": "space_idx",
+ "columns": [
+ "spaceId"
+ ],
+ "isUnique": false
+ },
+ "file_idx": {
+ "name": "file_idx",
+ "columns": [
+ "fileId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "spaces_roots_spaceId_spaces_id_fk": {
+ "name": "spaces_roots_spaceId_spaces_id_fk",
+ "tableFrom": "spaces_roots",
+ "tableTo": "spaces",
+ "columnsFrom": [
+ "spaceId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "spaces_roots_fileId_files_id_fk": {
+ "name": "spaces_roots_fileId_files_id_fk",
+ "tableFrom": "spaces_roots",
+ "tableTo": "files",
+ "columnsFrom": [
+ "fileId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "spaces_roots_id": {
+ "name": "spaces_roots_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "space_root_alias_uniq": {
+ "name": "space_root_alias_uniq",
+ "columns": [
+ "id",
+ "alias"
+ ]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "shares": {
+ "name": "shares",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "spaceRootId": {
+ "name": "spaceRootId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fileId": {
+ "name": "fileId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "externalPath": {
+ "name": "externalPath",
+ "type": "varchar(4096)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "tinyint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "alias": {
+ "name": "alias",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "description": {
+ "name": "description",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "storageUsage": {
+ "name": "storageUsage",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "storageQuota": {
+ "name": "storageQuota",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "storageIndexing": {
+ "name": "storageIndexing",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
+ },
+ "disabledAt": {
+ "name": "disabledAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "alias_idx": {
+ "name": "alias_idx",
+ "columns": [
+ "alias"
+ ],
+ "isUnique": true
+ },
+ "parent_idx": {
+ "name": "parent_idx",
+ "columns": [
+ "parentId"
+ ],
+ "isUnique": false
+ },
+ "owner_idx": {
+ "name": "owner_idx",
+ "columns": [
+ "ownerId"
+ ],
+ "isUnique": false
+ },
+ "space_idx": {
+ "name": "space_idx",
+ "columns": [
+ "spaceId"
+ ],
+ "isUnique": false
+ },
+ "space_root_idx": {
+ "name": "space_root_idx",
+ "columns": [
+ "spaceRootId"
+ ],
+ "isUnique": false
+ },
+ "file_idx": {
+ "name": "file_idx",
+ "columns": [
+ "fileId"
+ ],
+ "isUnique": false
+ },
+ "type_idx": {
+ "name": "type_idx",
+ "columns": [
+ "type"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "shares_ownerId_users_id_fk": {
+ "name": "shares_ownerId_users_id_fk",
+ "tableFrom": "shares",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shares_parentId_shares_id_fk": {
+ "name": "shares_parentId_shares_id_fk",
+ "tableFrom": "shares",
+ "tableTo": "shares",
+ "columnsFrom": [
+ "parentId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shares_spaceId_spaces_id_fk": {
+ "name": "shares_spaceId_spaces_id_fk",
+ "tableFrom": "shares",
+ "tableTo": "spaces",
+ "columnsFrom": [
+ "spaceId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shares_spaceRootId_spaces_roots_id_fk": {
+ "name": "shares_spaceRootId_spaces_roots_id_fk",
+ "tableFrom": "shares",
+ "tableTo": "spaces_roots",
+ "columnsFrom": [
+ "spaceRootId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shares_fileId_files_id_fk": {
+ "name": "shares_fileId_files_id_fk",
+ "tableFrom": "shares",
+ "tableTo": "files",
+ "columnsFrom": [
+ "fileId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "shares_id": {
+ "name": "shares_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "shares_members": {
+ "name": "shares_members",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "shareId": {
+ "name": "shareId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "groupId": {
+ "name": "groupId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "linkId": {
+ "name": "linkId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "share_idx": {
+ "name": "share_idx",
+ "columns": [
+ "shareId"
+ ],
+ "isUnique": false
+ },
+ "user_idx": {
+ "name": "user_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "group_idx": {
+ "name": "group_idx",
+ "columns": [
+ "groupId"
+ ],
+ "isUnique": false
+ },
+ "link_idx": {
+ "name": "link_idx",
+ "columns": [
+ "linkId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "shares_members_shareId_shares_id_fk": {
+ "name": "shares_members_shareId_shares_id_fk",
+ "tableFrom": "shares_members",
+ "tableTo": "shares",
+ "columnsFrom": [
+ "shareId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shares_members_userId_users_id_fk": {
+ "name": "shares_members_userId_users_id_fk",
+ "tableFrom": "shares_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shares_members_groupId_groups_id_fk": {
+ "name": "shares_members_groupId_groups_id_fk",
+ "tableFrom": "shares_members",
+ "tableTo": "groups",
+ "columnsFrom": [
+ "groupId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shares_members_linkId_links_id_fk": {
+ "name": "shares_members_linkId_links_id_fk",
+ "tableFrom": "shares_members",
+ "tableTo": "links",
+ "columnsFrom": [
+ "linkId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "shares_members_id": {
+ "name": "shares_members_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "share_user_uniq": {
+ "name": "share_user_uniq",
+ "columns": [
+ "shareId",
+ "userId"
+ ]
+ },
+ "share_group_uniq": {
+ "name": "share_group_uniq",
+ "columns": [
+ "shareId",
+ "groupId"
+ ]
+ },
+ "share_link_uniq": {
+ "name": "share_link_uniq",
+ "columns": [
+ "shareId",
+ "linkId"
+ ]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "files": {
+ "name": "files",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "spaceExternalRootId": {
+ "name": "spaceExternalRootId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shareExternalId": {
+ "name": "shareExternalId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "path": {
+ "name": "path",
+ "type": "varchar(4096)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "isDir": {
+ "name": "isDir",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "inTrash": {
+ "name": "inTrash",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "mime": {
+ "name": "mime",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "size": {
+ "name": "size",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ },
+ "mtime": {
+ "name": "mtime",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ },
+ "ctime": {
+ "name": "ctime",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "owner_idx": {
+ "name": "owner_idx",
+ "columns": [
+ "ownerId"
+ ],
+ "isUnique": false
+ },
+ "space_idx": {
+ "name": "space_idx",
+ "columns": [
+ "spaceId"
+ ],
+ "isUnique": false
+ },
+ "space_external_root_idx": {
+ "name": "space_external_root_idx",
+ "columns": [
+ "spaceExternalRootId"
+ ],
+ "isUnique": false
+ },
+ "share_external_idx": {
+ "name": "share_external_idx",
+ "columns": [
+ "shareExternalId"
+ ],
+ "isUnique": false
+ },
+ "name_idx": {
+ "name": "name_idx",
+ "columns": [
+ "name"
+ ],
+ "isUnique": false
+ },
+ "path_idx": {
+ "name": "path_idx",
+ "columns": [
+ "path"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "files_ownerId_users_id_fk": {
+ "name": "files_ownerId_users_id_fk",
+ "tableFrom": "files",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "files_spaceId_spaces_id_fk": {
+ "name": "files_spaceId_spaces_id_fk",
+ "tableFrom": "files",
+ "tableTo": "spaces",
+ "columnsFrom": [
+ "spaceId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "files_spaceExternalRootId_spaces_roots_id_fk": {
+ "name": "files_spaceExternalRootId_spaces_roots_id_fk",
+ "tableFrom": "files",
+ "tableTo": "spaces_roots",
+ "columnsFrom": [
+ "spaceExternalRootId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "files_shareExternalId_shares_id_fk": {
+ "name": "files_shareExternalId_shares_id_fk",
+ "tableFrom": "files",
+ "tableTo": "shares",
+ "columnsFrom": [
+ "shareExternalId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "files_id": {
+ "name": "files_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "files_recents": {
+ "name": "files_recents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shareId": {
+ "name": "shareId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "path": {
+ "name": "path",
+ "type": "varchar(4096)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime": {
+ "name": "mime",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "mtime": {
+ "name": "mtime",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "owner_idx": {
+ "name": "owner_idx",
+ "columns": [
+ "ownerId"
+ ],
+ "isUnique": false
+ },
+ "space_idx": {
+ "name": "space_idx",
+ "columns": [
+ "spaceId"
+ ],
+ "isUnique": false
+ },
+ "share_idx": {
+ "name": "share_idx",
+ "columns": [
+ "shareId"
+ ],
+ "isUnique": false
+ },
+ "mtime_idx": {
+ "name": "mtime_idx",
+ "columns": [
+ "mtime"
+ ],
+ "isUnique": false
+ },
+ "path_idx": {
+ "name": "path_idx",
+ "columns": [
+ "path"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "files_recents_ownerId_users_id_fk": {
+ "name": "files_recents_ownerId_users_id_fk",
+ "tableFrom": "files_recents",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "files_recents_spaceId_spaces_id_fk": {
+ "name": "files_recents_spaceId_spaces_id_fk",
+ "tableFrom": "files_recents",
+ "tableTo": "spaces",
+ "columnsFrom": [
+ "spaceId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "files_recents_shareId_shares_id_fk": {
+ "name": "files_recents_shareId_shares_id_fk",
+ "tableFrom": "files_recents",
+ "tableTo": "shares",
+ "columnsFrom": [
+ "shareId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "links": {
+ "name": "links",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "uuid": {
+ "name": "uuid",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "requireAuth": {
+ "name": "requireAuth",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "nbAccess": {
+ "name": "nbAccess",
+ "type": "int unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "limitAccess": {
+ "name": "limitAccess",
+ "type": "int unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "user_idx": {
+ "name": "user_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "uuid_idx": {
+ "name": "uuid_idx",
+ "columns": [
+ "uuid"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "links_userId_users_id_fk": {
+ "name": "links_userId_users_id_fk",
+ "tableFrom": "links",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "links_id": {
+ "name": "links_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "comments": {
+ "name": "comments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fileId": {
+ "name": "fileId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "modifiedAt": {
+ "name": "modifiedAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "user_idx": {
+ "name": "user_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "file_idx": {
+ "name": "file_idx",
+ "columns": [
+ "fileId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "comments_userId_users_id_fk": {
+ "name": "comments_userId_users_id_fk",
+ "tableFrom": "comments",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "comments_fileId_files_id_fk": {
+ "name": "comments_fileId_files_id_fk",
+ "tableFrom": "comments",
+ "tableTo": "files",
+ "columnsFrom": [
+ "fileId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "comments_id": {
+ "name": "comments_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "notifications": {
+ "name": "notifications",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "fromUserId": {
+ "name": "fromUserId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "toUserId": {
+ "name": "toUserId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "wasRead": {
+ "name": "wasRead",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "from_user_idx": {
+ "name": "from_user_idx",
+ "columns": [
+ "fromUserId"
+ ],
+ "isUnique": false
+ },
+ "to_user_idx": {
+ "name": "to_user_idx",
+ "columns": [
+ "toUserId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "notifications_fromUserId_users_id_fk": {
+ "name": "notifications_fromUserId_users_id_fk",
+ "tableFrom": "notifications",
+ "tableTo": "users",
+ "columnsFrom": [
+ "fromUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notifications_toUserId_users_id_fk": {
+ "name": "notifications_toUserId_users_id_fk",
+ "tableFrom": "notifications",
+ "tableTo": "users",
+ "columnsFrom": [
+ "toUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "notifications_id": {
+ "name": "notifications_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "sync_clients": {
+ "name": "sync_clients",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "char(36)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "char(36)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tokenExpiration": {
+ "name": "tokenExpiration",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "info": {
+ "name": "info",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "currentIp": {
+ "name": "currentIp",
+ "type": "varchar(45)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastIp": {
+ "name": "lastIp",
+ "type": "varchar(45)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "currentAccess": {
+ "name": "currentAccess",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastAccess": {
+ "name": "lastAccess",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "owner_idx": {
+ "name": "owner_idx",
+ "columns": [
+ "ownerId"
+ ],
+ "isUnique": false
+ },
+ "token_idx": {
+ "name": "token_idx",
+ "columns": [
+ "token"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sync_clients_ownerId_users_id_fk": {
+ "name": "sync_clients_ownerId_users_id_fk",
+ "tableFrom": "sync_clients",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "sync_clients_id": {
+ "name": "sync_clients_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "sync_paths": {
+ "name": "sync_paths",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "char(36)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "spaceRootId": {
+ "name": "spaceRootId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shareId": {
+ "name": "shareId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fileId": {
+ "name": "fileId",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "client_idx": {
+ "name": "client_idx",
+ "columns": [
+ "clientId"
+ ],
+ "isUnique": false
+ },
+ "owner_idx": {
+ "name": "owner_idx",
+ "columns": [
+ "ownerId"
+ ],
+ "isUnique": false
+ },
+ "space_idx": {
+ "name": "space_idx",
+ "columns": [
+ "spaceId"
+ ],
+ "isUnique": false
+ },
+ "space_root_idx": {
+ "name": "space_root_idx",
+ "columns": [
+ "spaceRootId"
+ ],
+ "isUnique": false
+ },
+ "share_idx": {
+ "name": "share_idx",
+ "columns": [
+ "shareId"
+ ],
+ "isUnique": false
+ },
+ "file_idx": {
+ "name": "file_idx",
+ "columns": [
+ "fileId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sync_paths_clientId_sync_clients_id_fk": {
+ "name": "sync_paths_clientId_sync_clients_id_fk",
+ "tableFrom": "sync_paths",
+ "tableTo": "sync_clients",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sync_paths_ownerId_users_id_fk": {
+ "name": "sync_paths_ownerId_users_id_fk",
+ "tableFrom": "sync_paths",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sync_paths_spaceId_spaces_id_fk": {
+ "name": "sync_paths_spaceId_spaces_id_fk",
+ "tableFrom": "sync_paths",
+ "tableTo": "spaces",
+ "columnsFrom": [
+ "spaceId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sync_paths_spaceRootId_spaces_roots_id_fk": {
+ "name": "sync_paths_spaceRootId_spaces_roots_id_fk",
+ "tableFrom": "sync_paths",
+ "tableTo": "spaces_roots",
+ "columnsFrom": [
+ "spaceRootId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sync_paths_shareId_shares_id_fk": {
+ "name": "sync_paths_shareId_shares_id_fk",
+ "tableFrom": "sync_paths",
+ "tableTo": "shares",
+ "columnsFrom": [
+ "shareId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sync_paths_fileId_files_id_fk": {
+ "name": "sync_paths_fileId_files_id_fk",
+ "tableFrom": "sync_paths",
+ "tableTo": "files",
+ "columnsFrom": [
+ "fileId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "sync_paths_id": {
+ "name": "sync_paths_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ }
+ },
+ "views": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "tables": {},
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/backend/migrations/meta/_journal.json b/backend/migrations/meta/_journal.json
index 83377f3c..6c38fe97 100644
--- a/backend/migrations/meta/_journal.json
+++ b/backend/migrations/meta/_journal.json
@@ -29,6 +29,13 @@
"when": 1761385913473,
"tag": "0003_giant_luckman",
"breakpoints": true
+ },
+ {
+ "idx": 4,
+ "version": "5",
+ "when": 1786979666928,
+ "tag": "0004_gigantic_romulus",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/backend/src/applications/users/models/user.model.ts b/backend/src/applications/users/models/user.model.ts
index a9d484da..82981ba5 100644
--- a/backend/src/applications/users/models/user.model.ts
+++ b/backend/src/applications/users/models/user.model.ts
@@ -34,6 +34,8 @@ export class UserModel implements User {
createdAt: Date
// exclusions
@Exclude()
+ externalId: string | null
+ @Exclude()
password: string
@Exclude()
secrets: UserSecrets
diff --git a/backend/src/applications/users/schemas/user.interface.ts b/backend/src/applications/users/schemas/user.interface.ts
index a83ea3df..5f214553 100644
--- a/backend/src/applications/users/schemas/user.interface.ts
+++ b/backend/src/applications/users/schemas/user.interface.ts
@@ -7,6 +7,7 @@ export class User implements UserSchema {
id: number
email: string
login: string
+ externalId: string | null
firstName: string
lastName: string
password: string
diff --git a/backend/src/applications/users/schemas/users.schema.ts b/backend/src/applications/users/schemas/users.schema.ts
index d582fa49..f65485dc 100644
--- a/backend/src/applications/users/schemas/users.schema.ts
+++ b/backend/src/applications/users/schemas/users.schema.ts
@@ -29,6 +29,7 @@ export const users = mysqlTable(
id: bigint('id', { mode: 'number', unsigned: true }).autoincrement().primaryKey(),
email: varchar('email', { length: 255 }).notNull(),
login: varchar('login', { length: 255 }).notNull(),
+ externalId: varchar('externalId', { length: 255 }),
firstName: varchar('firstName', { length: 255 }),
lastName: varchar('lastName', { length: 255 }),
password: varchar('password', { length: 255 }).notNull(),
@@ -51,7 +52,12 @@ export const users = mysqlTable(
.default(sql`CURRENT_TIMESTAMP`)
.notNull()
},
- (table) => [uniqueIndex('email_idx').on(table.email), uniqueIndex('login_idx').on(table.login), index('role_idx').on(table.role)]
+ (table) => [
+ uniqueIndex('email_idx').on(table.email),
+ uniqueIndex('login_idx').on(table.login),
+ uniqueIndex('external_id_idx').on(table.externalId),
+ index('role_idx').on(table.role)
+ ]
)
export const userFullNameSQL = (user: any): SQL<string> => sql`TRIM(CONCAT(${user.firstName}, ' ', ${user.lastName}))`
diff --git a/backend/src/applications/users/services/users-manager.service.spec.ts b/backend/src/applications/users/services/users-manager.service.spec.ts
index 2577955c..70916b75 100755
--- a/backend/src/applications/users/services/users-manager.service.spec.ts
+++ b/backend/src/applications/users/services/users-manager.service.spec.ts
@@ -149,6 +149,11 @@ describe(UsersManager.name, () => {
const u2 = await usersManager.findUser(userTest.login, false)
expect(u2).toBeInstanceOf(UserModel)
expect(u2.password).toBeDefined()
+ const externalLookupSpy = vi.spyOn(usersQueriesService, 'fromExternalIdOrEmail').mockResolvedValue(userTest)
+ const externalUser = await usersManager.findUserByExternalIdOrEmail('subject-1', userTest.email, false)
+ expect(externalUser).toBeInstanceOf(UserModel)
+ expect(externalUser.password).toBeDefined()
+ expect(externalLookupSpy).toHaveBeenCalledWith('subject-1', userTest.email)
const me1: any = await usersManager.me(userTest)
expect(me1.user.password).toBeUndefined()
usersQueriesService.from = vi.fn().mockReturnValue(null)
diff --git a/backend/src/applications/users/services/users-manager.service.ts b/backend/src/applications/users/services/users-manager.service.ts
index cb9fe350..7f340b72 100755
--- a/backend/src/applications/users/services/users-manager.service.ts
+++ b/backend/src/applications/users/services/users-manager.service.ts
@@ -87,6 +87,13 @@ export class UsersManager {
return user ? new UserModel(user, removePassword) : null
}
+ async findUserByExternalIdOrEmail(externalId: string, email: string, removePassword: false): Promise<UserModel>
+ async findUserByExternalIdOrEmail(externalId: string, email: string, removePassword?: true): Promise<Omit<UserModel, 'password'>>
+ async findUserByExternalIdOrEmail(externalId: string, email: string, removePassword: boolean = true): Promise<Omit<UserModel, 'password'>> {
+ const user: User = await this.usersQueries.fromExternalIdOrEmail(externalId, email)
+ return user ? new UserModel(user, removePassword) : null
+ }
+
async validateLocalPasswordByLogin(
loginOrEmail: string,
password: string,
diff --git a/backend/src/applications/users/services/users-queries.service.ts b/backend/src/applications/users/services/users-queries.service.ts
index fe73ff68..d0e4b786 100644
--- a/backend/src/applications/users/services/users-queries.service.ts
+++ b/backend/src/applications/users/services/users-queries.service.ts
@@ -1,5 +1,5 @@
import { Inject, Injectable, Logger } from '@nestjs/common'
-import { and, countDistinct, eq, inArray, isNotNull, like, lte, ne, notInArray, or, SelectedFields, SQL, sql } from 'drizzle-orm'
+import { and, countDistinct, desc, eq, inArray, isNotNull, isNull, like, lte, ne, notInArray, or, SelectedFields, SQL, sql } from 'drizzle-orm'
import { alias } from 'drizzle-orm/mysql-core'
import { MySql2PreparedQuery, MySqlQueryResult } from 'drizzle-orm/mysql2'
import { anonymizePassword, comparePassword, uniquePermissions } from '../../../common/functions'
@@ -39,6 +39,7 @@ import { userFullNameSQL, users } from '../schemas/users.schema'
@Injectable()
export class UsersQueries {
private readonly logger = new Logger(UsersQueries.name)
+ private fromExternalIdOrEmailPermissionsQuery: MySql2PreparedQuery<any> = null
private fromLoginOrEmailPermissionsQuery: MySql2PreparedQuery<any> = null
private fromIdPermissionsQuery: MySql2PreparedQuery<any> = null
@@ -128,6 +129,31 @@ export class UsersQueries {
return user
}
+ async fromExternalIdOrEmail(externalId: string, email: string): Promise<User> {
+ if (!this.fromExternalIdOrEmailPermissionsQuery) {
+ const externalIdPlaceholder = sql.placeholder('externalId')
+ const emailPlaceholder = sql.placeholder('email')
+ this.fromExternalIdOrEmailPermissionsQuery = this.db
+ .select({
+ user: users,
+ groupsPermissions: sql`GROUP_CONCAT(DISTINCT (${groups.permissions}) SEPARATOR ${USER_PERMS_SEP})`
+ })
+ .from(users)
+ .leftJoin(usersGroups, eq(usersGroups.userId, users.id))
+ .leftJoin(groups, and(eq(groups.id, usersGroups.groupId), ne(groups.permissions, '')))
+ .where(or(eq(users.externalId, externalIdPlaceholder), eq(users.email, emailPlaceholder)))
+ .groupBy(users.id)
+ .orderBy(desc(eq(users.externalId, externalIdPlaceholder)))
+ .limit(1)
+ .prepare()
+ }
+ const r = await this.fromExternalIdOrEmailPermissionsQuery.execute({ externalId, email })
+ if (!r.length) return null
+ const [user, groupsPermissions] = [r[0].user, r[0].groupsPermissions]
+ user.permissions = uniquePermissions(`${user.permissions},${groupsPermissions}`, USER_PERMS_SEP)
+ return user
+ }
+
async getUserSecrets(userId: number): Promise<UserSecrets> {
const [r]: { secrets: UserSecrets }[] = await this.db.select({ secrets: users.secrets }).from(users).where(eq(users.id, userId)).limit(1)
return r.secrets || {}
@@ -198,6 +224,46 @@ export class UsersQueries {
}
}
+ async bindExternalId(userId: number, externalId: string): Promise<boolean> {
+ try {
+ const isBound = await this.db.transaction(async (tx) => {
+ const [user]: Pick<User, 'externalId'>[] = await tx
+ .select({ externalId: users.externalId })
+ .from(users)
+ .where(eq(users.id, userId))
+ .limit(1)
+ .for('update')
+
+ if (!user) {
+ return false
+ }
+
+ if (user.externalId !== null) {
+ return user.externalId === externalId
+ }
+
+ dbCheckAffectedRows(
+ await tx
+ .update(users)
+ .set({ externalId })
+ .where(and(eq(users.id, userId), isNull(users.externalId))),
+ 1
+ )
+ return true
+ })
+
+ if (isBound) {
+ this.logger.verbose({ tag: this.bindExternalId.name, msg: `external identity was bound to user (${userId})` })
+ } else {
+ this.logger.warn({ tag: this.bindExternalId.name, msg: `external identity binding was rejected for user (${userId})` })
+ }
+ return isBound
+ } catch (e) {
+ this.logger.error({ tag: this.bindExternalId.name, msg: `external identity was not bound to user (${userId}) : ${e}` })
+ return false
+ }
+ }
+
async updateAccesses(userId: number, ip: string, passwordAttempts: 'preserve' | 'reset' | 'increment'): Promise<boolean> {
const set: Partial<Record<keyof User, any>> = {
lastAccess: users.currentAccess,
diff --git a/backend/src/applications/users/users.e2e-spec.ts b/backend/src/applications/users/users.e2e-spec.ts
index a19fe11f..146ba375 100644
--- a/backend/src/applications/users/users.e2e-spec.ts
+++ b/backend/src/applications/users/users.e2e-spec.ts
@@ -8,13 +8,16 @@ import { USER_ROLE } from './constants/user'
import { DeleteUserDto } from './dto/delete-user.dto'
import { UserModel } from './models/user.model'
import { AdminUsersManager } from './services/admin-users-manager.service'
+import { UsersQueries } from './services/users-queries.service'
import { generateUserTest } from './utils/test'
describe('Users (e2e)', () => {
let app: NestFastifyApplication
let authManager: AuthManager
let adminUsersManager: AdminUsersManager
+ let usersQueries: UsersQueries
let userTest: UserModel
+ let legacyUserTest: UserModel
let tokens: TokenResponseDto
beforeAll(async () => {
@@ -23,13 +26,17 @@ describe('Users (e2e)', () => {
await app.getHttpAdapter().getInstance().ready()
authManager = app.get<AuthManager>(AuthManager)
adminUsersManager = app.get<AdminUsersManager>(AdminUsersManager)
+ usersQueries = app.get<UsersQueries>(UsersQueries)
userTest = new UserModel(generateUserTest(false), false)
+ legacyUserTest = new UserModel(generateUserTest(false), false)
})
afterAll(async () => {
- await expect(
- adminUsersManager.deleteUserOrGuest(userTest.id, userTest.login, { deleteSpace: true } satisfies DeleteUserDto)
- ).resolves.not.toThrow()
+ for (const user of [userTest, legacyUserTest]) {
+ if (user.id) {
+ await expect(adminUsersManager.deleteUserOrGuest(user.id, user.login, { deleteSpace: true } satisfies DeleteUserDto)).resolves.not.toThrow()
+ }
+ }
await app.close()
})
@@ -66,6 +73,30 @@ describe('Users (e2e)', () => {
expect(content.user.id).toBe(userTest.id)
})
+ it('should bind and resolve external identities in the database', async () => {
+ const externalId = 'SUBJECT-1'
+ legacyUserTest = await adminUsersManager.createUserOrGuest(legacyUserTest, USER_ROLE.USER)
+
+ expect(await usersQueries.bindExternalId(userTest.id, externalId)).toBe(true)
+ expect((await usersQueries.from(userTest.id)).externalId).toBe(externalId)
+ expect(await usersQueries.bindExternalId(userTest.id, externalId)).toBe(true)
+ expect(await usersQueries.bindExternalId(userTest.id, 'subject-1')).toBe(false)
+ expect(await usersQueries.bindExternalId(0, externalId)).toBe(false)
+
+ const emailFallback = await usersQueries.fromExternalIdOrEmail('unknown-subject', legacyUserTest.email)
+ expect(emailFallback.id).toBe(legacyUserTest.id)
+
+ const externalIdPriority = await usersQueries.fromExternalIdOrEmail(externalId, legacyUserTest.email)
+ expect(externalIdPriority.id).toBe(userTest.id)
+
+ const concurrentExternalIds = ['CONCURRENT-SUBJECT-1', 'CONCURRENT-SUBJECT-2']
+ const concurrentBindings = await Promise.all(
+ concurrentExternalIds.map((concurrentExternalId) => usersQueries.bindExternalId(legacyUserTest.id, concurrentExternalId))
+ )
+ expect(concurrentBindings.filter(Boolean)).toHaveLength(1)
+ expect(concurrentExternalIds).toContain((await usersQueries.from(legacyUserTest.id)).externalId)
+ })
+
it(`GET ${API_USERS_AVATAR} => 200`, async () => {
const res1 = await app.inject({
method: 'GET',
diff --git a/backend/src/authentication/providers/oidc/auth-oidc.config.ts b/backend/src/authentication/providers/oidc/auth-oidc.config.ts
index 99ae979b..06155dd0 100644
--- a/backend/src/authentication/providers/oidc/auth-oidc.config.ts
+++ b/backend/src/authentication/providers/oidc/auth-oidc.config.ts
@@ -47,7 +47,7 @@ export class AuthProviderOIDCSecurityConfig {
@IsOptional()
@IsBoolean()
- requireVerifiedEmail? = false
+ requireVerifiedEmail? = true
@IsOptional()
@IsBoolean()
diff --git a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts
index 631d54c0..ac723481 100644
--- a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts
+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.spec.ts
@@ -42,7 +42,7 @@ vi.mock('../../../configuration/config.environment', () => ({
tokenEndpointAuthMethod: 'client_secret_basic',
allowInsecureRequests: false,
skipSubjectCheck: false,
- requireVerifiedEmail: false,
+ requireVerifiedEmail: true,
allowPrivateIpAvatarDownload: false
},
options: {
@@ -91,7 +91,9 @@ vi.mock('openid-client', () => {
describe(AuthProviderOIDC.name, () => {
let service: AuthProviderOIDC
let usersManager: {
+ usersQueries: { bindExternalId: Mock }
findUser: Mock
+ findUserByExternalIdOrEmail: Mock
logUser: Mock
validateLocalPasswordByLogin: Mock
updateAccesses: Mock
@@ -122,7 +124,9 @@ describe(AuthProviderOIDC.name, () => {
beforeAll(async () => {
usersManager = {
+ usersQueries: { bindExternalId: vi.fn().mockResolvedValue(true) },
findUser: vi.fn(),
+ findUserByExternalIdOrEmail: vi.fn(),
logUser: vi.fn(),
validateLocalPasswordByLogin: vi.fn(),
updateAccesses: vi.fn().mockResolvedValue(undefined),
@@ -156,7 +160,7 @@ describe(AuthProviderOIDC.name, () => {
;(service as any).oidcConfig.security.supportPKCE = true
;(service as any).oidcConfig.security.allowInsecureRequests = false
;(service as any).oidcConfig.security.allowPrivateIpAvatarDownload = false
- ;(service as any).oidcConfig.security.requireVerifiedEmail = false
+ ;(service as any).oidcConfig.security.requireVerifiedEmail = true
;(service as any).oidcConfig.options.enablePasswordAuth = false
vi.spyOn(filesUtils, 'temporaryFilePath').mockReturnValue('/tmp/sync-in/alice/tmp/~tmp-avatar-test-id-avatar.png')
;(service as any).oidcConfig.options.autoSyncAvatar = false
@@ -302,7 +306,11 @@ describe(AuthProviderOIDC.name, () => {
const result = await service.handleCallback(req as any, reply as any, { code: 'abc' })
expect(result).toEqual({ id: 7 })
- expect(processSpy).toHaveBeenCalledWith({ sub: 'subject-1', email: '[email protected]', email_verified: true, preferred_username: 'alice' }, '127.0.0.1')
+ expect(processSpy).toHaveBeenCalledWith(
+ { sub: 'subject-1', email: '[email protected]', email_verified: true, preferred_username: 'alice' },
+ 'subject-1',
+ '127.0.0.1'
+ )
expect(reply.clearCookie).toHaveBeenCalledWith(OAuthCookie.State, { path: '/' })
expect(reply.clearCookie).toHaveBeenCalledWith(OAuthCookie.Nonce, { path: '/' })
expect(reply.clearCookie).toHaveBeenCalledWith(OAuthCookie.CodeVerifier, { path: '/' })
@@ -347,15 +355,15 @@ describe(AuthProviderOIDC.name, () => {
})
it('creates identities with admin role when claims match', async () => {
- usersManager.findUser.mockResolvedValue(null)
+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(null)
adminUsersManager.createUserOrGuest.mockResolvedValue({ id: 10, login: 'bob' })
usersManager.fromUserId.mockResolvedValue({ id: 10, role: USER_ROLE.ADMINISTRATOR, login: 'bob', setFullName: vi.fn() } as any)
- const userInfo = { sub: 'x', email: '[email protected]', email_verified: true, preferred_username: 'bob', groups: ['admins'] }
+ const userInfo = { sub: 'EXTERNAL-X', email: '[email protected]', email_verified: true, preferred_username: 'bob', groups: ['admins'] }
- const result = await (service as any).processUserInfo(userInfo, '127.0.0.1')
+ const result = await (service as any).processUserInfo(userInfo, userInfo.sub, '127.0.0.1')
expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(
- expect.objectContaining({ role: USER_ROLE.ADMINISTRATOR }),
+ expect.objectContaining({ externalId: 'EXTERNAL-X', role: USER_ROLE.ADMINISTRATOR }),
USER_ROLE.ADMINISTRATOR
)
expect(result.role).toBe(USER_ROLE.ADMINISTRATOR)
@@ -365,29 +373,155 @@ describe(AuthProviderOIDC.name, () => {
;(service as any).oidcConfig.security.requireVerifiedEmail = true
await expect(
- (service as any).processUserInfo({ sub: 'x', email: '[email protected]', email_verified: false, preferred_username: 'alice' }, '127.0.0.1')
+ (service as any).processUserInfo({ sub: 'x', email: '[email protected]', email_verified: false, preferred_username: 'alice' }, 'x', '127.0.0.1')
).rejects.toMatchObject({ status: HttpStatus.BAD_REQUEST, message: 'OIDC email must be verified' })
})
- it('allows OIDC profiles with unverified emails by default', async () => {
- const existingUser = { id: 19, login: 'alice', email: '[email protected]', role: USER_ROLE.USER, setFullName: vi.fn() } as any
- usersManager.findUser.mockResolvedValue(existingUser)
+ it('allows OIDC profiles with unverified emails when verification is disabled', async () => {
+ ;(service as any).oidcConfig.security.requireVerifiedEmail = false
+ const existingUser = {
+ id: 19,
+ login: 'alice',
+ email: '[email protected]',
+ externalId: null,
+ role: USER_ROLE.USER,
+ isActive: true,
+ setFullName: vi.fn()
+ } as any
+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(existingUser)
const result = await (service as any).processUserInfo(
{ sub: 'x', email: '[email protected]', email_verified: false, preferred_username: 'alice' },
+ 'x',
'127.0.0.1'
)
expect(result).toBe(existingUser)
+ expect(usersManager.usersQueries.bindExternalId).toHaveBeenCalledWith(existingUser.id, 'x')
+ })
+
+ it('rejects a disabled local user before binding its external identity', async () => {
+ const existingUser = {
+ id: 19,
+ login: 'alice',
+ email: '[email protected]',
+ externalId: null,
+ role: USER_ROLE.USER,
+ isActive: false
+ } as any
+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(existingUser)
+
+ await expect(
+ (service as any).processUserInfo(
+ { sub: 'subject-1', email: '[email protected]', email_verified: true, preferred_username: 'alice' },
+ 'subject-1',
+ '127.0.0.1'
+ )
+ ).rejects.toMatchObject({ status: HttpStatus.FORBIDDEN, message: 'Account locked' })
+
+ expect(usersManager.usersQueries.bindExternalId).not.toHaveBeenCalled()
+ expect(adminUsersManager.updateUserOrGuest).not.toHaveBeenCalled()
+ expect(usersManager.updateAccesses).not.toHaveBeenCalled()
+ })
+
+ it('rejects login when the external identity cannot be bound', async () => {
+ const existingUser = {
+ id: 19,
+ login: 'alice',
+ email: '[email protected]',
+ externalId: null,
+ role: USER_ROLE.USER,
+ isActive: true
+ } as any
+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(existingUser)
+ usersManager.usersQueries.bindExternalId.mockResolvedValueOnce(false)
+
+ await expect(
+ (service as any).processUserInfo(
+ { sub: 'subject-1', email: '[email protected]', email_verified: true, preferred_username: 'alice' },
+ 'subject-1',
+ '127.0.0.1'
+ )
+ ).rejects.toMatchObject({ status: HttpStatus.UNAUTHORIZED, message: 'Unable to link OIDC identity' })
+
+ expect(adminUsersManager.updateUserOrGuest).not.toHaveBeenCalled()
+ expect(usersManager.updateAccesses).not.toHaveBeenCalled()
+ })
+
+ it('rejects an existing external identity that differs only by case', async () => {
+ const existingUser = {
+ id: 20,
+ login: 'alice',
+ email: '[email protected]',
+ externalId: 'subject-1',
+ role: USER_ROLE.USER,
+ isActive: true,
+ setFullName: vi.fn()
+ } as any
+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(existingUser)
+
+ await expect(
+ (service as any).processUserInfo(
+ { sub: 'SUBJECT-1', email: '[email protected]', email_verified: true, preferred_username: 'alice' },
+ 'SUBJECT-1',
+ '127.0.0.1'
+ )
+ ).rejects.toMatchObject({ status: HttpStatus.UNAUTHORIZED, message: 'OIDC identity mismatch' })
+
+ expect(usersManager.findUserByExternalIdOrEmail).toHaveBeenCalledWith('SUBJECT-1', existingUser.email, false)
+ expect(usersManager.usersQueries.bindExternalId).not.toHaveBeenCalled()
+ })
+
+ it('keeps the local login stable after the external identity is linked', async () => {
+ const existingUser = {
+ id: 20,
+ login: 'alice',
+ email: '[email protected]',
+ externalId: 'subject-1',
+ role: USER_ROLE.USER,
+ isActive: true,
+ firstName: '',
+ lastName: '',
+ setFullName: vi.fn()
+ } as any
+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(existingUser)
+
+ await (service as any).processUserInfo(
+ { sub: 'subject-1', email: '[email protected]', email_verified: true, preferred_username: 'renamed-alice' },
+ 'subject-1',
+ '127.0.0.1'
+ )
+
+ expect(existingUser.login).toBe('alice')
+ expect(adminUsersManager.updateUserOrGuest).not.toHaveBeenCalled()
+ })
+
+ it('rejects an email already linked to another external identity', async () => {
+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue({
+ id: 21,
+ login: 'alice',
+ email: '[email protected]',
+ externalId: 'another-subject',
+ isActive: true
+ })
+
+ await expect(
+ (service as any).processUserInfo(
+ { sub: 'subject-1', email: '[email protected]', email_verified: true, preferred_username: 'alice' },
+ 'subject-1',
+ '127.0.0.1'
+ )
+ ).rejects.toMatchObject({ status: HttpStatus.UNAUTHORIZED, message: 'OIDC identity mismatch' })
})
it('does not sync the user avatar by default', async () => {
- const existingUser = { id: 20, login: 'alice', email: '[email protected]', role: USER_ROLE.USER, setFullName: vi.fn() } as any
- usersManager.findUser.mockResolvedValue(existingUser)
+ const existingUser = { id: 20, login: 'alice', email: '[email protected]', role: USER_ROLE.USER, isActive: true, setFullName: vi.fn() } as any
+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(existingUser)
const updatePictureUrlSpy = vi.spyOn(service as any, 'updatePictureUrl').mockResolvedValue(undefined)
await (service as any).processUserInfo(
{ sub: 'x', email: '[email protected]', email_verified: true, preferred_username: 'alice', picture: 'https://cdn.example.test/avatar.jpg' },
+ 'x',
'127.0.0.1'
)
@@ -396,7 +530,7 @@ describe(AuthProviderOIDC.name, () => {
it('syncs the user avatar when enabled', async () => {
;(service as any).oidcConfig.options.autoSyncAvatar = true
- const existingUser = { id: 21, login: 'alice', email: '[email protected]', role: USER_ROLE.USER, setFullName: vi.fn() } as any
+ const existingUser = { id: 21, login: 'alice', email: '[email protected]', role: USER_ROLE.USER, isActive: true, setFullName: vi.fn() } as any
const userInfo = {
sub: 'x',
@@ -404,10 +538,10 @@ describe(AuthProviderOIDC.name, () => {
preferred_username: 'alice',
picture: 'https://cdn.example.test/avatar.jpg'
}
- usersManager.findUser.mockResolvedValue(existingUser)
+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(existingUser)
const updatePictureUrlSpy = vi.spyOn(service as any, 'updatePictureUrl').mockResolvedValue(undefined)
- await (service as any).processUserInfo(userInfo, '127.0.0.1')
+ await (service as any).processUserInfo(userInfo, userInfo.sub, '127.0.0.1')
expect(updatePictureUrlSpy).toHaveBeenCalledWith(existingUser, userInfo)
})
@@ -479,11 +613,11 @@ describe(AuthProviderOIDC.name, () => {
if (scenario.mode === 'create') {
const id = 110 + index
- usersManager.findUser.mockResolvedValue(null)
+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(null)
adminUsersManager.createUserOrGuest.mockResolvedValue({ id, login: `user-${id}` })
usersManager.fromUserId.mockResolvedValue({ id, role: USER_ROLE.USER, login: `user-${id}`, setFullName: vi.fn() } as any)
- await (service as any).processUserInfo(scenario.profile, '127.0.0.1')
+ await (service as any).processUserInfo(scenario.profile, scenario.profile.sub, '127.0.0.1')
expect(adminUsersManager.createUserOrGuest).toHaveBeenCalledWith(
expect.objectContaining({ storageQuota: scenario.expectedQuota }),
@@ -497,14 +631,15 @@ describe(AuthProviderOIDC.name, () => {
login: 'alice',
role: USER_ROLE.USER,
+ isActive: true,
firstName: '',
lastName: '',
storageQuota: 4096,
setFullName: vi.fn()
} as any
- usersManager.findUser.mockResolvedValue(existingUser)
+ usersManager.findUserByExternalIdOrEmail.mockResolvedValue(existingUser)
- await (service as any).processUserInfo(scenario.profile, '127.0.0.1')
+ await (service as any).processUserInfo(scenario.profile, scenario.profile.sub, '127.0.0.1')
if (scenario.expectedUpdate) {
expect(adminUsersManager.updateUserOrGuest).toHaveBeenCalledWith(
diff --git a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
index c43b7584..efb8e526 100644
--- a/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
+++ b/backend/src/authentication/providers/oidc/auth-provider-oidc.service.ts
@@ -176,7 +176,7 @@ export class AuthProviderOIDC implements AuthProvider {
}
// Process the user info and create/update the user
- return await this.processUserInfo(userInfo, req.ip)
+ return await this.processUserInfo(userInfo, claims.sub, req.ip)
} catch (error: AuthorizationResponseError | HttpException | any) {
if (error instanceof AuthorizationResponseError) {
this.logger.error({ tag: this.handleCallback.name, msg: `OIDC callback error: ${error.code} - ${error.error_description}` })
@@ -313,12 +313,30 @@ export class AuthProviderOIDC implements AuthProvider {
return (this.oidcConfig.security.supportPKCE ?? true) && config.serverMetadata().supportsPKCE()
}
- private async processUserInfo(userInfo: UserInfoResponse, ip?: string): Promise<UserModel> {
+ private async processUserInfo(userInfo: UserInfoResponse, externalId: string, ip?: string): Promise<UserModel> {
// Extract user information
const { login, email } = this.extractLoginAndEmail(userInfo)
- // Check if user exists
- let user: UserModel = await this.usersManager.findUser(email || login, false)
+ // Resolve an already linked external identity first, then fall back to email for existing OIDC users.
+ let user: UserModel = await this.usersManager.findUserByExternalIdOrEmail(externalId, email, false)
+
+ if (user?.externalId && user.externalId !== externalId) {
+ this.logger.warn({ tag: this.processUserInfo.name, msg: `OIDC email is already linked to another external identity` })
+ throw new HttpException('OIDC identity mismatch', HttpStatus.UNAUTHORIZED)
+ }
+
+ // Enforce the local account status before binding an unlinked external identity.
+ if (user && !user.isActive) {
+ this.logger.warn({ tag: this.processUserInfo.name, msg: `OIDC login rejected for disabled user *${user.login}*` })
+ throw new HttpException('Account locked', HttpStatus.FORBIDDEN)
+ }
+
+ if (user && !user.externalId) {
+ if (!(await this.usersManager.usersQueries.bindExternalId(user.id, externalId))) {
+ throw new HttpException('Unable to link OIDC identity', HttpStatus.UNAUTHORIZED)
+ }
+ user.externalId = externalId
+ }
if (!user && !this.oidcConfig.options.autoCreateUser) {
this.logger.warn({ tag: this.processUserInfo.name, msg: `User not found and autoCreateUser is disabled` })
@@ -332,7 +350,7 @@ export class AuthProviderOIDC implements AuthProvider {
const identity = this.createIdentity(login, email, userInfo, isAdmin)
// Create or update user
- user = await this.updateOrCreateUser(identity, user)
+ user = await this.updateOrCreateUser(identity, user, externalId)
// Update picture url (if it exists)
if (this.oidcConfig.options.autoSyncAvatar) {
await this.updatePictureUrl(user, userInfo)
@@ -382,14 +400,19 @@ export class AuthProviderOIDC implements AuthProvider {
return identity
}
- private async updateOrCreateUser(identity: Omit<CreateUserDto, 'password'> & { password?: string }, user: UserModel | null): Promise<UserModel> {
+ private async updateOrCreateUser(
+ identity: Omit<CreateUserDto, 'password'> & { password?: string },
+ user: UserModel | null,
+ externalId: string
+ ): Promise<UserModel> {
if (user === null) {
// Create new user with a random password (required by the system but not used for OIDC login)
const userWithPassword = {
...identity,
+ externalId,
password: generateShortUUID(24),
permissions: this.oidcConfig.options.autoCreatePermissions.join(',')
- } as CreateUserDto
+ } as CreateUserDto & { externalId: string }
const createdUser = await this.adminUsersManager.createUserOrGuest(userWithPassword, identity.role)
const freshUser = await this.usersManager.fromUserId(createdUser.id)
if (!freshUser) {
@@ -399,10 +422,10 @@ export class AuthProviderOIDC implements AuthProvider {
return freshUser
}
- // Check if user information has changed (excluding password)
+ // Check if user information has changed. The local login is initialized once and remains stable.
const identityHasChanged: UpdateUserDto = Object.fromEntries(
Object.keys(identity)
- .filter((key) => key !== 'password')
+ .filter((key) => key !== 'password' && key !== 'login')
.map((key: string) => (identity[key] !== user[key] ? [key, identity[key]] : null))
.filter(Boolean)
)
diff --git a/backend/src/authentication/providers/oidc/oidc.md b/backend/src/authentication/providers/oidc/oidc.md
new file mode 100644
index 00000000..ca9014c9
--- /dev/null
+++ b/backend/src/authentication/providers/oidc/oidc.md
@@ -0,0 +1,241 @@
+# OpenID Connect
+
+Sync-in delegates authentication to one configured OpenID Connect (OIDC) identity provider. The provider is enabled when `auth.provider` is set to
+`oidc`.
+
+The current implementation supports:
+
+- OIDC discovery from the configured issuer URL;
+- the Authorization Code flow for a confidential client;
+- `client_secret_basic` and `client_secret_post` token endpoint authentication;
+- optional PKCE with the `S256` challenge method;
+- profile retrieval from the UserInfo endpoint;
+- web and desktop loopback callbacks;
+- automatic local account creation and profile synchronization;
+- role, storage quota, and avatar mapping;
+- an optional local password flow alongside OIDC.
+
+Only one IdP can be configured at a time. Sync-in creates its own local session after the OIDC callback and does not retain the IdP access, ID, or
+refresh tokens.
+
+## Authentication flow
+
+1. The client opens `/api/auth/oidc/login`.
+2. Sync-in discovers the provider metadata on first use and caches the resulting client configuration.
+3. Sync-in generates `state` and `nonce` values. It also generates a PKCE verifier when PKCE is enabled and advertised by the provider.
+4. The browser is redirected to the provider's authorization endpoint with `response_type=code` and the configured scopes.
+5. The provider redirects the browser to the configured callback after authentication.
+6. Sync-in validates `state`, `nonce`, and the PKCE verifier when applicable, then exchanges the authorization code at the token endpoint.
+7. The ID token is validated and its `sub` claim is required. The access token is then used to retrieve the profile from the UserInfo endpoint.
+8. Sync-in resolves, creates, or updates the local user and issues local Sync-in access and refresh cookies.
+
+The temporary `state`, `nonce`, and PKCE verifier values are stored in HTTP-only, `SameSite=Lax` cookies for up to ten minutes. They are cleared after
+the callback whether authentication succeeds or fails. The authorization redirect response also disables caching and referrer forwarding.
+
+Discovery uses HTTPS by default and has a six-second timeout. Insecure HTTP can be enabled explicitly for development or a trusted legacy provider.
+
+## Redirect URIs
+
+The web callback is configured with `redirectUri` and is normally:
+
+```text
+https://sync-in.example.com/api/auth/oidc/callback
+```
+
+Desktop authentication uses one of these fixed loopback callbacks:
+
+```text
+http://127.0.0.1:49152/oidc/callback
+http://127.0.0.1:49153/oidc/callback
+http://127.0.0.1:49154/oidc/callback
+```
+
+Every callback used by a client must be registered as an allowed redirect URI at the IdP. A desktop client selects its loopback callback with the
+`desktop_port` login parameter; any other port is rejected.
+
+After a successful callback, the web flow redirects to the Sync-in frontend with an `oidc=true` marker and the local token expiration timestamps in
+the URL fragment. Authentication tokens remain in the Sync-in cookies and are not placed in that URL.
+
+## ID token and UserInfo responsibilities
+
+Sync-in intentionally uses the two responses for different purposes:
+
+- the validated ID token supplies the stable external identity (`sub`);
+- the UserInfo response supplies the local profile attributes.
+
+By default, the UserInfo `sub` must match the ID token `sub`. `security.skipSubjectCheck` disables this comparison only for non-compliant providers;
+the ID token `sub` remains the identity stored by Sync-in, and a `sub` is still required in both responses.
+
+The ID token issuer is validated against the discovered provider as part of OIDC validation, but Sync-in does not persist `iss` in the user record.
+This is appropriate for the current single-IdP model; it is not an issuer-and-subject binding suitable for multiple simultaneous providers.
+
+## Supported claims
+
+Unless specified otherwise, claims in this table are read from the UserInfo response.
+
+| Claim | Required | Usage |
+| --- | --- | --- |
+| ID token `sub` | Yes | Stored unchanged as the local `externalId`. |
+| UserInfo `sub` | Yes | Checked against the ID token subject unless `skipSubjectCheck` is enabled. |
+| `email` | Yes | Trimmed, used for legacy account linking, and synchronized to the local profile. |
+| `email_verified` | By default | Must be the boolean `true` when `requireVerifiedEmail` is enabled. |
+| `preferred_username` | No | Initializes a new local login after trimming and lowercasing. |
+| `given_name` / `family_name` | No | Synchronize the local first and last names. |
+| `name` | No | Split into first and last names only when both structured name claims are absent. |
+| `groups` / `roles` | No | Top-level arrays inspected for an exact `adminRoleOrGroup` match. |
+| `picture` | No | HTTP(S) avatar URL used when automatic avatar synchronization is enabled. |
+| Configured quota claim | No | Synchronizes the local storage quota in bytes. |
+
+If `preferred_username` is absent, the email local-part initializes the login. Because email is required, the UserInfo `sub` is not normally used as
+the login fallback.
+
+Claims available only in an ID token are not merged into the UserInfo profile. Provider-specific mappers must expose roles, groups, quota, and other
+profile attributes through the UserInfo endpoint when those mappings are required.
+
+## Identity binding and backward compatibility
+
+The validated ID token `sub` is the stable external identity. Sync-in stores it unchanged in the nullable, unique `users.externalId` column.
+
+At login, accounts are resolved in this order:
+
+1. Match `externalId` against the ID token `sub`.
+2. Fall back to the OIDC email only for an existing account whose `externalId` is still empty.
+3. Atomically persist the unchanged `sub` on that account so later logins no longer depend on its email.
+4. Create a new local account when no match exists and `autoCreateUser` is enabled.
+
+The email fallback is the compatibility path for accounts that authenticated through OIDC before external identities were stored. It never matches a
+local login. An email match is rejected when that local account is already linked to a different external identity.
+
+Once linked, a user continues to be found by `externalId` if their IdP email changes. The new email can then be synchronized to the local profile.
+Conversely, a legacy account whose email changed before its first external-ID binding cannot be located through the old email automatically.
+
+The issuer is not stored because Sync-in supports a single configured IdP. Changing `issuerUrl` therefore requires an explicit migration or reset of
+existing `externalId` values before users authenticate against the replacement provider.
+
+## Account creation and profile synchronization
+
+When `autoCreateUser` is enabled, a first successful login creates a local user with:
+
+- the normalized `preferred_username`, or the email local-part, as `login`;
+- the required OIDC email;
+- the mapped first and last names;
+- the unchanged ID token `sub` as `externalId`;
+- the configured creation-time permissions;
+- the mapped administrator role and storage quota, when present;
+- an internal random password required by the local user model but not used for OIDC authentication.
+
+When automatic creation is disabled, authentication succeeds only for an already linked account or a compatible existing account found by email.
+
+For an existing user, each successful OIDC login can synchronize:
+
+- email;
+- first and last names;
+- administrator or regular-user role;
+- storage quota, when the configured claim is present and valid;
+- avatar, when enabled.
+
+The local `login`, password, and permissions are not synchronized. In particular, `preferred_username` initializes the login but does not rename it on
+later authentications. Automatic provisioning does not currently generate an alternative login when the derived value conflicts with an existing
+unique local login.
+
+Profile update failures are logged without invalidating an otherwise successful OIDC authentication. Creation-time permissions are never reapplied
+to an existing user.
+
+## Administrator role mapping
+
+When `options.adminRoleOrGroup` is configured, Sync-in searches the top-level UserInfo `groups` and `roles` arrays for that exact value. Matching is
+case-sensitive.
+
+- A match assigns the administrator role.
+- No match assigns the regular-user role, including demotion of a previously mapped administrator.
+- When no mapping is configured, existing local administrators keep their role and OIDC profile synchronization cannot demote them.
+
+Nested or provider-specific role structures are not interpreted. They must be mapped by the IdP to a supported top-level array.
+
+## Storage quota mapping
+
+`options.storageQuotaClaim` selects the UserInfo claim containing the quota in bytes. Its default name is `storageQuota`.
+
+- A non-negative safe integer or a decimal integer string is accepted.
+- `null` or `0` sets the local quota to `null`, meaning unlimited storage.
+- A missing claim leaves the current local quota unchanged.
+- A negative, fractional, non-numeric, or unsafe value is ignored.
+
+## Avatar synchronization
+
+When `options.autoSyncAvatar` is enabled, Sync-in reads the UserInfo `picture` URL after a successful login. The URL must use HTTP or HTTPS.
+
+Before installing the avatar, Sync-in checks the content type and enforces a 5 MiB maximum. The image is downloaded to a temporary location,
+converted to PNG, and stored as the local user avatar. Source URL, size, and last-modified metadata are retained so an unchanged remote avatar can be
+skipped on subsequent logins.
+
+Downloads from private or internal IP ranges are blocked by default to limit server-side request forgery exposure.
+`security.allowPrivateIpAvatarDownload` should be enabled only when the IdP returns trusted internal URLs.
+
+## Local password authentication and MFA
+
+OIDC login trusts the authentication policy enforced by the identity provider. Sync-in does not add its local TOTP challenge after a successful OIDC
+callback. Administrators must require MFA, when needed, in the IdP policy assigned to the Sync-in client or application.
+
+A successful IdP authentication does not override local account access: an existing user disabled in Sync-in is rejected before external identity
+binding or profile synchronization.
+
+Sync-in TOTP still applies to interactive local password authentication. With the OIDC provider selected, local passwords are accepted for:
+
+- guest users;
+- administrators as break-glass access;
+- scoped application or app-password authentication;
+- regular users when `options.enablePasswordAuth` is enabled.
+
+Scoped application authentication is non-interactive and does not invoke a TOTP challenge.
+
+The Sync-in logout endpoint clears only the local session cookies. It does not currently call the IdP end-session or token revocation endpoints, so an
+existing IdP SSO session can authenticate the browser again without prompting for credentials.
+
+## Configuration reference
+
+### Client settings
+
+| Setting | Default | Description |
+| --- | --- | --- |
+| `issuerUrl` | Required | Provider issuer URL used for discovery. |
+| `clientId` | Required | OIDC client identifier. |
+| `clientSecret` | Required | OIDC confidential-client secret. |
+| `redirectUri` | Required | Web callback URI registered at the provider. |
+
+### Functional options
+
+| Setting | Default | Description |
+| --- | --- | --- |
+| `options.autoCreateUser` | `true` | Create a local account when no compatible user exists. |
+| `options.autoCreatePermissions` | `[]` | Permissions assigned only when automatically creating an account. |
+| `options.autoRedirect` | `false` | Tell the login UI to start OIDC automatically. |
+| `options.enablePasswordAuth` | `false` | Permit regular users to use their local password alongside OIDC. |
+| `options.autoSyncAvatar` | `false` | Synchronize the UserInfo `picture` at login. |
+| `options.adminRoleOrGroup` | Unset | Exact top-level role or group value granting administrator access. |
+| `options.storageQuotaClaim` | `storageQuota` | UserInfo claim containing the quota in bytes. |
+| `options.buttonText` | `Continue with OpenID Connect` | Label exposed to the login UI. |
+
+### Security options
+
+| Setting | Default | Description |
+| --- | --- | --- |
+| `security.scope` | `openid email profile` | Space-separated scopes; `openid` is mandatory. |
+| `security.supportPKCE` | `true` | Use PKCE S256 when the provider metadata advertises support. |
+| `security.allowInsecureRequests` | `false` | Permit HTTP discovery and OIDC requests. Intended only for controlled environments. |
+| `security.tokenEndpointAuthMethod` | `client_secret_basic` | Token endpoint authentication; supports `client_secret_basic` or `client_secret_post`. |
+| `security.tokenSigningAlg` | `RS256` | Expected ID token signing algorithm. |
+| `security.userInfoSigningAlg` | Unset | Request and validate a signed UserInfo response with the configured algorithm. |
+| `security.skipSubjectCheck` | `false` | Skip the UserInfo-to-ID-token subject comparison for a legacy provider. |
+| `security.requireVerifiedEmail` | `true` | Require UserInfo `email_verified` to be exactly `true`. |
+| `security.allowPrivateIpAvatarDownload` | `false` | Permit avatar URLs resolving to private or internal addresses. |
+
+## Current boundaries
+
+- A UserInfo endpoint is required; profile claims are not taken from the ID token.
+- Only one IdP and one global OIDC client configuration are supported.
+- External identities are keyed by the ID token `sub` as received, not by an `(iss, sub)` pair.
+- Public clients without a client secret are not exposed by the current validated configuration.
+- IdP tokens are not retained or refreshed; Sync-in issues and refreshes its own local tokens.
+- RP-initiated logout, front-channel logout, back-channel logout, and IdP token revocation are not implemented.
+- Login renaming and automatic login collision resolution are not implemented.
diff --git a/environment/environment.dist.yaml b/environment/environment.dist.yaml
index 1b28f7e1..e220b727 100755
--- a/environment/environment.dist.yaml
+++ b/environment/environment.dist.yaml
@@ -205,6 +205,11 @@ auth:
# default: false
enablePasswordAuthFallback: false
oidc:
+ # OIDC authentication, including MFA, is delegated to the identity provider.
+ # Sync-in TOTP applies only to local password authentication.
+ # Users are resolved by the OIDC `sub` first, then by email only when no external identity is linked yet.
+ # The first successful email match stores `sub` as the user's external identity for subsequent logins.
+ # `preferred_username` initializes the local login for a new user but does not rename an existing local login.
# issuerUrl: The URL of the OIDC provider's discovery endpoint
# e.g.:
# - Keycloak: https://auth.example.com/realms/my-realm
@@ -233,7 +238,7 @@ auth:
redirectUri: https://sync-in.domain.com/api/auth/oidc/callback
options:
# autoCreateUser: Automatically create a local user account on first successful OIDC login.
- # When enabled, the user `login` is derived from OIDC claims: preferred_username, then the email local-part, with `sub` as a last-resort fallback.
+ # When enabled, the user `login` is derived from `preferred_username`, or from the email local-part when that claim is absent.
# When disabled, only existing users are allowed to authenticate via OIDC.
# default: true
autoCreateUser: true
@@ -316,8 +321,8 @@ auth:
# requireVerifiedEmail: Require the OIDC provider to mark profile emails as verified before account linking or profile synchronization.
# Recommended when your provider exposes a reliable `email_verified` claim.
# Some providers omit this claim unless specific scopes/mappers are configured.
- # default: false
- requireVerifiedEmail: false
+ # default: true
+ requireVerifiedEmail: true
# allowPrivateIpAvatarDownload: Allow OIDC avatar downloads from private/internal IP ranges.
# Set to true only when the OIDC provider returns trusted internal avatar URLs.
# default: false