appPassword: add expiry

This commit is contained in:
Girish Ramakrishnan
2026-02-12 12:58:50 +01:00
parent 93a0063941
commit e9c3e42aa6
16 changed files with 226 additions and 62 deletions
+1
View File
@@ -3136,4 +3136,5 @@
* Fix fonts on chrome * Fix fonts on chrome
* applinks: fix acl UI * applinks: fix acl UI
* services: rename sftp to filemanager, graphite to metrics * services: rename sftp to filemanager, graphite to metrics
* app passwords: add expiry
+7 -7
View File
@@ -6,7 +6,7 @@
"packages": { "packages": {
"": { "": {
"dependencies": { "dependencies": {
"@cloudron/pankow": "^3.6.7", "@cloudron/pankow": "^3.7.0",
"@fontsource/inter": "^5.2.8", "@fontsource/inter": "^5.2.8",
"@fortawesome/fontawesome-free": "^7.1.0", "@fortawesome/fontawesome-free": "^7.1.0",
"@vitejs/plugin-vue": "^6.0.4", "@vitejs/plugin-vue": "^6.0.4",
@@ -92,9 +92,9 @@
} }
}, },
"node_modules/@cloudron/pankow": { "node_modules/@cloudron/pankow": {
"version": "3.6.7", "version": "3.7.0",
"resolved": "https://registry.npmjs.org/@cloudron/pankow/-/pankow-3.6.7.tgz", "resolved": "https://registry.npmjs.org/@cloudron/pankow/-/pankow-3.7.0.tgz",
"integrity": "sha512-Ce41AXeAKjZemXYmOANkSW+667SR3CkM046YSjUvk+PU5m8Vrs8oXGUqZka+ze8QZpDUfGtlCmkyBy8YTPINLQ==", "integrity": "sha512-HIa2xAJdHNttie6DRADPKfxhlx91VZ+AU7YFe6Tc3zlx6cI6aTCyb+uow+w2XYUlllU9g6EkR1dGrPgVhM2ViQ==",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@fontsource/inter": "^5.2.8", "@fontsource/inter": "^5.2.8",
@@ -3277,9 +3277,9 @@
} }
}, },
"@cloudron/pankow": { "@cloudron/pankow": {
"version": "3.6.7", "version": "3.7.0",
"resolved": "https://registry.npmjs.org/@cloudron/pankow/-/pankow-3.6.7.tgz", "resolved": "https://registry.npmjs.org/@cloudron/pankow/-/pankow-3.7.0.tgz",
"integrity": "sha512-Ce41AXeAKjZemXYmOANkSW+667SR3CkM046YSjUvk+PU5m8Vrs8oXGUqZka+ze8QZpDUfGtlCmkyBy8YTPINLQ==", "integrity": "sha512-HIa2xAJdHNttie6DRADPKfxhlx91VZ+AU7YFe6Tc3zlx6cI6aTCyb+uow+w2XYUlllU9g6EkR1dGrPgVhM2ViQ==",
"requires": { "requires": {
"@fontsource/inter": "^5.2.8", "@fontsource/inter": "^5.2.8",
"@fortawesome/fontawesome-free": "^7.1.0", "@fortawesome/fontawesome-free": "^7.1.0",
+1 -1
View File
@@ -7,7 +7,7 @@
}, },
"type": "module", "type": "module",
"dependencies": { "dependencies": {
"@cloudron/pankow": "^3.6.7", "@cloudron/pankow": "^3.7.0",
"@fontsource/inter": "^5.2.8", "@fontsource/inter": "^5.2.8",
"@fortawesome/fontawesome-free": "^7.1.0", "@fortawesome/fontawesome-free": "^7.1.0",
"@vitejs/plugin-vue": "^6.0.4", "@vitejs/plugin-vue": "^6.0.4",
+4 -2
View File
@@ -298,7 +298,8 @@
"app": "App", "app": "App",
"name": "Name", "name": "Name",
"noPasswordsPlaceholder": "No app passwords", "noPasswordsPlaceholder": "No app passwords",
"description": "App passwords are a security measure to protect your Cloudron user account. If you need to access a Cloudron app from an untrusted mobile app or client, you can log in with your username and the alternate password generated here." "description": "App passwords are a security measure to protect your Cloudron user account. If you need to access a Cloudron app from an untrusted mobile app or client, you can log in with your username and the alternate password generated here.",
"expires": "Expires"
}, },
"apiTokens": { "apiTokens": {
"title": "API Tokens", "title": "API Tokens",
@@ -331,7 +332,8 @@
"name": "Password name", "name": "Password name",
"app": "App", "app": "App",
"description": "Use the following password to authenticate against the app:", "description": "Use the following password to authenticate against the app:",
"copyNow": "Please copy the password now. It won't be shown again for security purposes." "copyNow": "Please copy the password now. It won't be shown again for security purposes.",
"expiresAt": "Expiry date"
}, },
"createApiToken": { "createApiToken": {
"title": "Add API Token", "title": "Add API Token",
+19 -9
View File
@@ -105,7 +105,10 @@
}, },
"unstable": "Tidak stabil", "unstable": "Tidak stabil",
"title": "Toko Aplikasi", "title": "Toko Aplikasi",
"searchPlaceholder": "Cari alternatif seperti GitHub, Dropbox, Slack, Trello, …" "searchPlaceholder": "Cari alternatif seperti GitHub, Dropbox, Slack, Trello, …",
"action": {
"addCustomApp": "Tambahkan aplikasi kustom"
}
}, },
"users": { "users": {
"users": { "users": {
@@ -373,7 +376,9 @@
"title": "Detail Cadangan", "title": "Detail Cadangan",
"id": "ID Cadangan", "id": "ID Cadangan",
"date": "Dibuat", "date": "Dibuat",
"size": "Ukuran" "size": "Ukuran",
"lastIntegrityCheck": "Pemeriksaan integritas terakhir",
"integrityNever": "tidak pernah"
}, },
"configureBackupSchedule": { "configureBackupSchedule": {
"hours": "Jam", "hours": "Jam",
@@ -500,7 +505,8 @@
"title": "Konfigurasi Konten Cadangan" "title": "Konfigurasi Konten Cadangan"
}, },
"useFileAndFileNameEncryption": "Enkripsi berkas dan nama berkas digunakan", "useFileAndFileNameEncryption": "Enkripsi berkas dan nama berkas digunakan",
"useFileEncryption": "Enkripsi berkas digunakan" "useFileEncryption": "Enkripsi berkas digunakan",
"checkIntegrity": "Periksa integritas"
}, },
"branding": { "branding": {
"logo": "Logo", "logo": "Logo",
@@ -891,11 +897,11 @@
"reallyDelete": "Apakah Anda yakin ingin menghapus?" "reallyDelete": "Apakah Anda yakin ingin menghapus?"
}, },
"newDirectoryDialog": { "newDirectoryDialog": {
"title": "Nama Folder Baru", "title": "Folder Baru",
"create": "Buat" "create": "Buat"
}, },
"newFileDialog": { "newFileDialog": {
"title": "Nama berkas Baru", "title": "Nama berkas baru",
"create": "Buat" "create": "Buat"
}, },
"renameDialog": { "renameDialog": {
@@ -919,10 +925,10 @@
"pasteInProgress": "Penempelan sedang berlangsung", "pasteInProgress": "Penempelan sedang berlangsung",
"deleteInProgress": "Penghapusan sedang berlangsung", "deleteInProgress": "Penghapusan sedang berlangsung",
"chownDialog": { "chownDialog": {
"title": "Ubah kepemilikan", "title": "Ubah pemilik",
"newOwner": "Pemilik baru", "newOwner": "Pemilik baru",
"change": "Ubah Pemilik", "change": "Ubah pemilik",
"recursiveCheckbox": "Ubah kepemilikan secara rekursif" "recursiveCheckbox": "Ubah pemilik secara rekursif"
}, },
"uploadingDialog": { "uploadingDialog": {
"title": "Mengunggah berkas ({{ countDone }}/{{ count }})", "title": "Mengunggah berkas ({{ countDone }}/{{ count }})",
@@ -1370,7 +1376,8 @@
"packageVersion": "Paket", "packageVersion": "Paket",
"lastUpdated": "Terakhir diperbarui", "lastUpdated": "Terakhir diperbarui",
"customAppUpdateInfo": "Pembaruan otomatis tidak tersedia untuk aplikasi khusus.", "customAppUpdateInfo": "Pembaruan otomatis tidak tersedia untuk aplikasi khusus.",
"installedAt": "Terpasang" "installedAt": "Terpasang",
"packager": "Pengemas"
}, },
"auto": { "auto": {
"description": "Pembaruan aplikasi diterapkan secara berkala berdasarkan <a href=\"/#/system-update\">jadwal pembaruan</a>", "description": "Pembaruan aplikasi diterapkan secara berkala berdasarkan <a href=\"/#/system-update\">jadwal pembaruan</a>",
@@ -1684,5 +1691,8 @@
"title": "Kata sandi telah diubah", "title": "Kata sandi telah diubah",
"openDashboardAction": "Buka dasbor" "openDashboardAction": "Buka dasbor"
} }
},
"communityapp": {
"installwarning": "Aplikasi komunitas tidak ditinjau oleh Cloudron. Hanya instal aplikasi dari pengembang tepercaya. Kode pihak ketiga dapat membahayakan sistem Anda."
} }
} }
+7 -3
View File
@@ -385,7 +385,9 @@
"date": "Aangemaakt", "date": "Aangemaakt",
"version": "Package versie", "version": "Package versie",
"size": "Grootte", "size": "Grootte",
"duration": "Backup duur" "duration": "Backup duur",
"lastIntegrityCheck": "Laatste integriteitscontrole",
"integrityNever": "nooit"
}, },
"configureBackupSchedule": { "configureBackupSchedule": {
"title": "Configureer Backup Planning & Bewaartermijn", "title": "Configureer Backup Planning & Bewaartermijn",
@@ -503,7 +505,8 @@
"title": "Configureer Backup Inhoud" "title": "Configureer Backup Inhoud"
}, },
"useFileAndFileNameEncryption": "Bestand en bestandsnaam encryptie gebruikt", "useFileAndFileNameEncryption": "Bestand en bestandsnaam encryptie gebruikt",
"useFileEncryption": "Bestand encryptie gebruikt" "useFileEncryption": "Bestand encryptie gebruikt",
"checkIntegrity": "Controleer integriteit"
}, },
"branding": { "branding": {
"title": "Huisstijl", "title": "Huisstijl",
@@ -859,7 +862,8 @@
"packageVersion": "Pakket", "packageVersion": "Pakket",
"lastUpdated": "Laatst geüpdatet", "lastUpdated": "Laatst geüpdatet",
"customAppUpdateInfo": "Auto-update is niet beschikbaar voor maatwerk apps.", "customAppUpdateInfo": "Auto-update is niet beschikbaar voor maatwerk apps.",
"installedAt": "Geïnstalleerd" "installedAt": "Geïnstalleerd",
"packager": "Pakketmaker"
}, },
"auto": { "auto": {
"description": "App updates worden uitgevoerd op basis van de <a href=\"/#/system-update\">update planning</a>.", "description": "App updates worden uitgevoerd op basis van de <a href=\"/#/system-update\">update planning</a>.",
+34 -8
View File
@@ -105,6 +105,9 @@
"appNotFoundDialog": { "appNotFoundDialog": {
"title": "Приложение не найдено", "title": "Приложение не найдено",
"description": "Не найдено приложения <b>{{ appId }}</b> версии <b>{{ version }}</b>." "description": "Не найдено приложения <b>{{ appId }}</b> версии <b>{{ version }}</b>."
},
"action": {
"addCustomApp": "Добавить стороннее приложение"
} }
}, },
"users": { "users": {
@@ -366,7 +369,8 @@
"appId": "ID приложения", "appId": "ID приложения",
"packageVersion": "Пакет", "packageVersion": "Пакет",
"lastUpdated": "Обновлен", "lastUpdated": "Обновлен",
"installedAt": "Установлено" "installedAt": "Установлено",
"packager": "Сборщик"
}, },
"auto": { "auto": {
"title": "Автоматические обновления", "title": "Автоматические обновления",
@@ -555,11 +559,27 @@
"csp": { "csp": {
"title": "Политика безопасности контента", "title": "Политика безопасности контента",
"saveAction": "Сохранить", "saveAction": "Сохранить",
"description": "Перезаписать любые CSP заголовки, отправляемые приложением" "description": "Перезаписать любые CSP заголовки, отправляемые приложением",
"insertCommonCsp": "Вставить стандартный CSP",
"commonPattern": {
"allowEmbedding": "Разрешить встраивание",
"sameOriginEmbedding": "Разрешить встраивание (только поддомены)",
"allowCdnAssets": "Разрешить использование ресурсов CDN",
"reportOnly": "Сообщить о нарушениях CSP",
"strictBaseline": "Строгий базовый уровень"
}
}, },
"robots": { "robots": {
"title": "Robots.txt", "title": "Robots.txt",
"description": "По умолчанию, роботы могут индексировать это приложение" "description": "По умолчанию, роботы могут индексировать это приложение",
"commonPattern": {
"allowAll": "Разрешить все (по умолчанию)",
"disallowAll": "Запретить все",
"disallowCommonBots": "Запретить известных ботов",
"disallowAdminPaths": "Запретить пути админа",
"disallowApiPaths": "Запретить пути API"
},
"insertCommonRobotsTxt": "Вставить стандартный robots.txt"
}, },
"hstsPreload": "Активировать предзагрузку HSTS (в том числе для поддоменов)" "hstsPreload": "Активировать предзагрузку HSTS (в том числе для поддоменов)"
}, },
@@ -779,7 +799,9 @@
"date": "Создано", "date": "Создано",
"version": "Версия пакета", "version": "Версия пакета",
"size": "Размер", "size": "Размер",
"duration": "Продолжительность резервного копирования" "duration": "Продолжительность резервного копирования",
"lastIntegrityCheck": "Последняя проверка целостности",
"integrityNever": "никогда"
}, },
"backupEdit": { "backupEdit": {
"title": "Редактировать резервную копию", "title": "Редактировать резервную копию",
@@ -821,7 +843,8 @@
"title": "Настроить содержание резервной копии" "title": "Настроить содержание резервной копии"
}, },
"useFileAndFileNameEncryption": "Используется шифрование файлов и их имён", "useFileAndFileNameEncryption": "Используется шифрование файлов и их имён",
"useFileEncryption": "Используется шифрование файлов" "useFileEncryption": "Используется шифрование файлов",
"checkIntegrity": "Проверить целостность"
}, },
"branding": { "branding": {
"title": "Брендирование", "title": "Брендирование",
@@ -1218,7 +1241,7 @@
"filemanager": { "filemanager": {
"title": "Файловый менеджер", "title": "Файловый менеджер",
"newDirectoryDialog": { "newDirectoryDialog": {
"title": "Имя новой папки", "title": "Новая папка",
"create": "Создать" "create": "Создать"
}, },
"newFileDialog": { "newFileDialog": {
@@ -1249,7 +1272,7 @@
"pasteInProgress": "Выполняется копирование / перемещение", "pasteInProgress": "Выполняется копирование / перемещение",
"deleteInProgress": "Выполняется удаление", "deleteInProgress": "Выполняется удаление",
"chownDialog": { "chownDialog": {
"title": "Смена владельца", "title": "Изменить владельца",
"newOwner": "Новый владелец", "newOwner": "Новый владелец",
"change": "Изменить владельца", "change": "Изменить владельца",
"recursiveCheckbox": "Изменить владельца рекурсивно" "recursiveCheckbox": "Изменить владельца рекурсивно"
@@ -1280,7 +1303,7 @@
"symlink": "Символическая ссылка на {{ target }}", "symlink": "Символическая ссылка на {{ target }}",
"menu": { "menu": {
"rename": "Переименовать", "rename": "Переименовать",
"chown": "Изменить владельца", "chown": "Смена владельца",
"extract": "Распаковать здесь", "extract": "Распаковать здесь",
"download": "Скачать", "download": "Скачать",
"delete": "Удалить", "delete": "Удалить",
@@ -1668,5 +1691,8 @@
}, },
"server": { "server": {
"title": "Сервер" "title": "Сервер"
},
"communityapp": {
"installwarning": "Cloudron не проводит аудит приложений, созданных сообществом. Устанавливайте приложения только от проверенных разработчиков. Сторонний код может поставить под угрозу безопасности вашей системы."
} }
} }
+42 -14
View File
@@ -4,9 +4,8 @@ import { useI18n } from 'vue-i18n';
const i18n = useI18n(); const i18n = useI18n();
const t = i18n.t; const t = i18n.t;
import moment from 'moment-timezone';
import { ref, onMounted, useTemplateRef } from 'vue'; import { ref, onMounted, useTemplateRef } from 'vue';
import { Button, ClipboardButton, Dialog, SingleSelect, FormGroup, TextInput, TableView, InputDialog, InputGroup } from '@cloudron/pankow'; import { Button, ClipboardButton, DateTimeInput, Dialog, SingleSelect, FormGroup, TextInput, TableView, InputDialog, InputGroup } from '@cloudron/pankow';
import { prettyLongDate } from '@cloudron/pankow/utils'; import { prettyLongDate } from '@cloudron/pankow/utils';
import ActionBar from './ActionBar.vue'; import ActionBar from './ActionBar.vue';
import Section from './Section.vue'; import Section from './Section.vue';
@@ -35,7 +34,16 @@ const columns = {
sort(a, b) { sort(a, b) {
if (!a) return 1; if (!a) return 1;
if (!b) return -1; if (!b) return -1;
return moment(a).isBefore(b) ? 1 : -1; return new Date(a) - new Date(b);
}
},
expiresAt: {
label: t('profile.appPasswords.expires'),
hideMobile: true,
sort(a, b) {
if (!a) return 1;
if (!b) return -1;
return new Date(a) - new Date(b);
} }
}, },
actions: {} actions: {}
@@ -54,6 +62,8 @@ const addedPassword = ref('');
const passwordName = ref(''); const passwordName = ref('');
const identifiers = ref([]); const identifiers = ref([]);
const identifier = ref(''); const identifier = ref('');
const expiresAtDate = ref('');
const minExpiresAt = new Date().toISOString().slice(0, 16);
const addError = ref(''); const addError = ref('');
const busy = ref(false); const busy = ref(false);
@@ -62,16 +72,20 @@ async function refresh() {
const [error, result] = await appPasswordsModel.list(); const [error, result] = await appPasswordsModel.list();
if (error) return console.error(error); if (error) return console.error(error);
// setup label for the table UI for (const password of result) {
result.forEach(function (password) { if (password.identifier === 'mail') {
if (password.identifier === 'mail') return password.label = password.identifier; password.label = password.identifier;
const app = appsById[password.identifier]; } else {
if (!app) return password.label = password.identifier + ' (App not found)'; const app = appsById[password.identifier];
if (!app) return password.label = password.identifier + ' (App not found)';
const ftp = app.manifest.addons && app.manifest.addons.localstorage && app.manifest.addons.localstorage.ftp; const ftp = app.manifest.addons && app.manifest.addons.localstorage && app.manifest.addons.localstorage.ftp;
const labelSuffix = ftp ? ' - SFTP' : ''; const labelSuffix = ftp ? ' - SFTP' : '';
password.label = app.label ? app.label + ' (' + app.fqdn + ')' + labelSuffix : app.fqdn + labelSuffix; password.label = app.label ? app.label + ' (' + app.fqdn + ')' + labelSuffix : app.fqdn + labelSuffix;
}); }
password.expired = password.expiresAt && new Date(password.expiresAt) < new Date();
}
passwords.value = result; passwords.value = result;
} }
@@ -86,6 +100,7 @@ function onReset() {
setTimeout(() => { setTimeout(() => {
passwordName.value = ''; passwordName.value = '';
identifier.value = ''; identifier.value = '';
expiresAtDate.value = '';
addedPassword.value = ''; addedPassword.value = '';
addError.value = ''; addError.value = '';
busy.value = false; busy.value = false;
@@ -100,7 +115,8 @@ async function onSubmit() {
addError.value = ''; addError.value = '';
addedPassword.value = ''; addedPassword.value = '';
const [error, result] = await appPasswordsModel.add(identifier.value, passwordName.value); const expiresAt = expiresAtDate.value ? new Date(expiresAtDate.value).toISOString() : null;
const [error, result] = await appPasswordsModel.add(identifier.value, passwordName.value, expiresAt);
if (error) { if (error) {
busy.value = false; busy.value = false;
addError.value = error.body ? error.body.message : 'Internal error'; addError.value = error.body ? error.body.message : 'Internal error';
@@ -110,6 +126,7 @@ async function onSubmit() {
addedPassword.value = result.password; addedPassword.value = result.password;
passwordName.value = ''; passwordName.value = '';
identifier.value = ''; identifier.value = '';
expiresAtDate.value = '';
await refresh(); await refresh();
@@ -197,6 +214,11 @@ onMounted(async () => {
<label>{{ $t('profile.createAppPassword.app') }}</label> <label>{{ $t('profile.createAppPassword.app') }}</label>
<SingleSelect outline v-model="identifier" :options="identifiers" option-label="label" option-key="id" required/> <SingleSelect outline v-model="identifier" :options="identifiers" option-label="label" option-key="id" required/>
</FormGroup> </FormGroup>
<FormGroup>
<label for="expiresAt">{{ $t('profile.createAppPassword.expiresAt') }} (optional)</label>
<DateTimeInput id="expiresAt" v-model="expiresAtDate" :min="minExpiresAt"/>
</FormGroup>
</fieldset> </fieldset>
</form> </form>
</div> </div>
@@ -221,7 +243,13 @@ onMounted(async () => {
<br/> <br/>
<TableView :columns="columns" :model="passwords" :placeholder="$t('profile.appPasswords.noPasswordsPlaceholder')"> <TableView :columns="columns" :model="passwords" :placeholder="$t('profile.appPasswords.noPasswordsPlaceholder')">
<template #creationTime="password">{{ prettyLongDate(password.creationTime) }}</template> <template #name="password"><span :class="{ 'text-muted': password.expired }">{{ password.name }}</span></template>
<template #label="password"><span :class="{ 'text-muted': password.expired }">{{ password.label }}</span></template>
<template #creationTime="password"><span :class="{ 'text-muted': password.expired }">{{ prettyLongDate(password.creationTime) }}</span></template>
<template #expiresAt="password">
<span :class="{ 'text-muted': password.expired }" v-if="!password.expiresAt">-</span>
<span :class="{ 'text-muted': password.expired }" v-else>{{ prettyLongDate(password.expiresAt) }}</span>
</template>
<template #actions="password"> <template #actions="password">
<ActionBar :actions="createActionMenu(password)" /> <ActionBar :actions="createActionMenu(password)" />
</template> </template>
+2 -2
View File
@@ -18,10 +18,10 @@ function create() {
if (error || result.status !== 200) return [error || result]; if (error || result.status !== 200) return [error || result];
return [null, result.body.appPasswords]; return [null, result.body.appPasswords];
}, },
async add(identifier, name) { async add(identifier, name, expiresAt) {
let error, result; let error, result;
try { try {
result = await fetcher.post(`${API_ORIGIN}/api/v1/app_passwords`, { identifier, name }, { access_token: accessToken }); result = await fetcher.post(`${API_ORIGIN}/api/v1/app_passwords`, { identifier, name, expiresAt }, { access_token: accessToken });
} catch (e) { } catch (e) {
error = e; error = e;
} }
@@ -0,0 +1,15 @@
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE appPasswords ADD COLUMN expiresAt TIMESTAMP NULL DEFAULT NULL', function (error) {
if (error) console.error(error);
callback(error);
});
};
exports.down = function(db, callback) {
db.runSql('ALTER TABLE appPasswords DROP COLUMN expiresAt', function (error) {
if (error) console.error(error);
callback(error);
});
};
+1
View File
@@ -293,6 +293,7 @@ CREATE TABLE IF NOT EXISTS appPasswords(
identifier VARCHAR(128) NOT NULL, // resourceId: app id or mail or webadmin identifier VARCHAR(128) NOT NULL, // resourceId: app id or mail or webadmin
hashedPassword VARCHAR(1024) NOT NULL, hashedPassword VARCHAR(1024) NOT NULL,
creationTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, creationTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
expiresAt TIMESTAMP NULL DEFAULT NULL,
UNIQUE KEY appPasswords_name_appId_identifier (name, userId, identifier) UNIQUE KEY appPasswords_name_appId_identifier (name, userId, identifier)
FOREIGN KEY(userId) REFERENCES users(id), FOREIGN KEY(userId) REFERENCES users(id),
+8 -6
View File
@@ -17,7 +17,7 @@ const assert = require('node:assert'),
safe = require('safetydance'), safe = require('safetydance'),
_ = require('./underscore.js'); _ = require('./underscore.js');
const APP_PASSWORD_FIELDS = [ 'id', 'name', 'userId', 'identifier', 'hashedPassword', 'creationTime' ].join(','); const APP_PASSWORD_FIELDS = [ 'id', 'name', 'userId', 'identifier', 'hashedPassword', 'creationTime', 'expiresAt' ].join(',');
function validateAppPasswordName(name) { function validateAppPasswordName(name) {
assert.strictEqual(typeof name, 'string'); assert.strictEqual(typeof name, 'string');
@@ -29,7 +29,7 @@ function validateAppPasswordName(name) {
} }
function removePrivateFields(appPassword) { function removePrivateFields(appPassword) {
return _.pick(appPassword, ['id', 'name', 'userId', 'identifier', 'creationTime']); return _.pick(appPassword, ['id', 'name', 'userId', 'identifier', 'creationTime', 'expiresAt']);
} }
async function get(id) { async function get(id) {
@@ -40,10 +40,11 @@ async function get(id) {
return result[0]; return result[0];
} }
async function add(userId, identifier, name) { async function add(userId, identifier, name, expiresAt) {
assert.strictEqual(typeof userId, 'string'); assert.strictEqual(typeof userId, 'string');
assert.strictEqual(typeof identifier, 'string'); assert.strictEqual(typeof identifier, 'string');
assert.strictEqual(typeof name, 'string'); assert.strictEqual(typeof name, 'string');
assert(expiresAt === null || typeof expiresAt === 'string');
let error = validateAppPasswordName(name); let error = validateAppPasswordName(name);
if (error) throw error; if (error) throw error;
@@ -59,11 +60,12 @@ async function add(userId, identifier, name) {
userId, userId,
identifier, identifier,
password, password,
hashedPassword hashedPassword,
expiresAt
}; };
const query = 'INSERT INTO appPasswords (id, userId, identifier, name, hashedPassword) VALUES (?, ?, ?, ?, ?)'; const query = 'INSERT INTO appPasswords (id, userId, identifier, name, hashedPassword, expiresAt) VALUES (?, ?, ?, ?, ?, ?)';
const args = [ appPassword.id, appPassword.userId, appPassword.identifier, appPassword.name, appPassword.hashedPassword ]; const args = [ appPassword.id, appPassword.userId, appPassword.identifier, appPassword.name, appPassword.hashedPassword, appPassword.expiresAt ? new Date(appPassword.expiresAt) : null ];
[error] = await safe(database.query(query, args)); [error] = await safe(database.query(query, args));
if (error && error.sqlCode === 'ER_DUP_ENTRY' && error.sqlMessage.indexOf('appPasswords_name_userId_identifier') !== -1) throw new BoxError(BoxError.ALREADY_EXISTS, 'name/app combination already exists'); if (error && error.sqlCode === 'ER_DUP_ENTRY' && error.sqlMessage.indexOf('appPasswords_name_userId_identifier') !== -1) throw new BoxError(BoxError.ALREADY_EXISTS, 'name/app combination already exists');
+4 -4
View File
@@ -31,8 +31,9 @@ async function add(req, res, next) {
if (typeof req.body.name !== 'string') return next(new HttpError(400, 'name must be string')); if (typeof req.body.name !== 'string') return next(new HttpError(400, 'name must be string'));
if (typeof req.body.identifier !== 'string') return next(new HttpError(400, 'identifier must be string')); if (typeof req.body.identifier !== 'string') return next(new HttpError(400, 'identifier must be string'));
if (req.body.expiresAt !== null && (typeof req.body.expiresAt !== 'string' || isNaN(new Date(req.body.expiresAt).getTime()))) return next(new HttpError(400, 'expiresAt must be null or a valid date string'));
const [error, result] = await safe(appPasswords.add(req.user.id, req.body.identifier, req.body.name)); const [error, result] = await safe(appPasswords.add(req.user.id, req.body.identifier, req.body.name, req.body.expiresAt));
if (error) return next(BoxError.toHttpError(error)); if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(201, { id: result.id, password: result.password })); next(new HttpSuccess(201, { id: result.id, password: result.password }));
@@ -41,11 +42,10 @@ async function add(req, res, next) {
async function list(req, res, next) { async function list(req, res, next) {
assert.strictEqual(typeof req.user, 'object'); assert.strictEqual(typeof req.user, 'object');
let [error, result] = await safe(appPasswords.list(req.user.id)); const [error, result] = await safe(appPasswords.list(req.user.id));
if (error) return next(BoxError.toHttpError(error)); if (error) return next(BoxError.toHttpError(error));
result = result.map(appPasswords.removePrivateFields); next(new HttpSuccess(200, { appPasswords: result.map(appPasswords.removePrivateFields) }));
next(new HttpSuccess(200, { appPasswords: result }));
} }
async function del(req, res, next) { async function del(req, res, next) {
+43 -3
View File
@@ -29,7 +29,34 @@ describe('App Passwords', function () {
it('cannot add app password without name', async function () { it('cannot add app password without name', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/app_passwords`) const response = await superagent.post(`${serverUrl}/api/v1/app_passwords`)
.query({ access_token: user.token }) .query({ access_token: user.token })
.send({ identifier: 'someapp' }) .send({ identifier: 'someapp', expiresAt: null })
.ok(() => true);
expect(response.status).to.equal(400);
});
it('cannot add app password without expiresAt', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/app_passwords`)
.query({ access_token: user.token })
.send({ name: 'my-device', identifier: 'someapp' })
.ok(() => true);
expect(response.status).to.equal(400);
});
it('cannot add app password with invalid expiresAt type', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/app_passwords`)
.query({ access_token: user.token })
.send({ name: 'my-device', identifier: 'someapp', expiresAt: 12345 })
.ok(() => true);
expect(response.status).to.equal(400);
});
it('cannot add app password with invalid expiresAt date', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/app_passwords`)
.query({ access_token: user.token })
.send({ name: 'my-device', identifier: 'someapp', expiresAt: 'not-a-date' })
.ok(() => true); .ok(() => true);
expect(response.status).to.equal(400); expect(response.status).to.equal(400);
@@ -39,24 +66,36 @@ describe('App Passwords', function () {
it('can add app password', async function () { it('can add app password', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/app_passwords`) const response = await superagent.post(`${serverUrl}/api/v1/app_passwords`)
.query({ access_token: user.token }) .query({ access_token: user.token })
.send({ name: 'my-device', identifier: 'someapp' }); .send({ name: 'my-device', identifier: 'someapp', expiresAt: null });
expect(response.status).to.equal(201); expect(response.status).to.equal(201);
expect(response.body.password).to.be.a('string'); expect(response.body.password).to.be.a('string');
pwd = response.body; pwd = response.body;
}); });
it('can add app password with expiresAt', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/app_passwords`)
.query({ access_token: user.token })
.send({ name: 'expiring-device', identifier: 'someapp', expiresAt: new Date(Date.now() + 86400000).toISOString() });
expect(response.status).to.equal(201);
expect(response.body.password).to.be.a('string');
});
it('can get app passwords', async function () { it('can get app passwords', async function () {
const response = await superagent.get(`${serverUrl}/api/v1/app_passwords`) const response = await superagent.get(`${serverUrl}/api/v1/app_passwords`)
.query({ access_token: user.token }); .query({ access_token: user.token });
expect(response.status).to.equal(200); expect(response.status).to.equal(200);
expect(response.body.appPasswords).to.be.an(Array); expect(response.body.appPasswords).to.be.an(Array);
expect(response.body.appPasswords.length).to.be(1); expect(response.body.appPasswords.length).to.be(2);
expect(response.body.appPasswords[0].name).to.be('my-device'); expect(response.body.appPasswords[0].name).to.be('my-device');
expect(response.body.appPasswords[0].identifier).to.be('someapp'); expect(response.body.appPasswords[0].identifier).to.be('someapp');
expect(response.body.appPasswords[0].expiresAt).to.be(null);
expect(response.body.appPasswords[0].hashedPassword).to.be(undefined); expect(response.body.appPasswords[0].hashedPassword).to.be(undefined);
expect(response.body.appPasswords[0].password).to.be(undefined); expect(response.body.appPasswords[0].password).to.be(undefined);
expect(response.body.appPasswords[1].name).to.be('expiring-device');
expect(response.body.appPasswords[1].expiresAt).to.be.a('string');
}); });
it('can get app password', async function () { it('can get app password', async function () {
@@ -66,6 +105,7 @@ describe('App Passwords', function () {
expect(response.status).to.equal(200); expect(response.status).to.equal(200);
expect(response.body.name).to.be('my-device'); expect(response.body.name).to.be('my-device');
expect(response.body.identifier).to.be('someapp'); expect(response.body.identifier).to.be('someapp');
expect(response.body.expiresAt).to.be(null);
expect(response.body.hashedPassword).to.be(undefined); expect(response.body.hashedPassword).to.be(undefined);
expect(response.body.password).to.be(undefined); expect(response.body.password).to.be(undefined);
}); });
+36 -2
View File
@@ -21,12 +21,12 @@ describe('App passwords', function () {
let id, password; let id, password;
it('cannot add bad app password', async function () { it('cannot add bad app password', async function () {
const [error] = await safe(appPasswords.add(admin.id, 'appid', 'x'.repeat(201))); const [error] = await safe(appPasswords.add(admin.id, 'appid', 'x'.repeat(201), null));
expect(error.reason).to.be(BoxError.BAD_FIELD); expect(error.reason).to.be(BoxError.BAD_FIELD);
}); });
it('can add app password', async function () { it('can add app password', async function () {
const result = await appPasswords.add(admin.id, 'appid', 'spark'); const result = await appPasswords.add(admin.id, 'appid', 'spark', null);
expect(result.id).to.be.a('string'); expect(result.id).to.be.a('string');
expect(result.password).to.be.a('string'); expect(result.password).to.be.a('string');
id = result.id; id = result.id;
@@ -90,4 +90,38 @@ describe('App passwords', function () {
const [error] = await safe(appPasswords.del('random')); const [error] = await safe(appPasswords.del('random'));
expect(error.reason).to.be(BoxError.NOT_FOUND); expect(error.reason).to.be(BoxError.NOT_FOUND);
}); });
// expiry tests
let expiredPassword;
it('can add app password with expiry', async function () {
const result = await appPasswords.add(admin.id, 'appid', 'expiring', new Date(Date.now() + 60000).toISOString());
expect(result.id).to.be.a('string');
expect(result.password).to.be.a('string');
expiredPassword = result.password;
});
it('can verify non-expired app password', async function () {
const result = await users.verifyWithId(admin.id, expiredPassword, 'appid', {});
expect(result).to.be.ok();
expect(result.appPassword).to.be(true);
});
let pastId, pastPassword;
it('can add app password with past expiry', async function () {
const result = await appPasswords.add(admin.id, 'appid', 'expired', new Date(Date.now() - 60000).toISOString());
expect(result.id).to.be.a('string');
expect(result.password).to.be.a('string');
pastId = result.id;
pastPassword = result.password;
});
it('cannot verify expired app password', async function () {
const [error, result] = await safe(users.verifyWithId(admin.id, pastPassword, 'appid', {}));
expect(result).to.not.be.ok();
expect(error.reason).to.be(BoxError.INVALID_CREDENTIALS);
});
it('can del expired app password', async function () {
await appPasswords.del(pastId);
});
}); });
+2 -1
View File
@@ -619,7 +619,8 @@ async function verifyAppPassword(userId, password, identifier) {
const results = await appPasswords.list(userId); const results = await appPasswords.list(userId);
const hashedPasswords = results.filter(r => r.identifier === identifier).map(r => r.hashedPassword); const now = new Date();
const hashedPasswords = results.filter(r => r.identifier === identifier).filter(r => !r.expiresAt || new Date(r.expiresAt) > now).map(r => r.hashedPassword);
const hash = crypto.createHash('sha256').update(password).digest('base64'); const hash = crypto.createHash('sha256').update(password).digest('base64');
if (hashedPasswords.includes(hash)) return; if (hashedPasswords.includes(hash)) return;