appPassword: add expiry
This commit is contained in:
1
CHANGES
1
CHANGES
@@ -3136,4 +3136,5 @@
|
||||
* Fix fonts on chrome
|
||||
* applinks: fix acl UI
|
||||
* services: rename sftp to filemanager, graphite to metrics
|
||||
* app passwords: add expiry
|
||||
|
||||
|
||||
14
dashboard/package-lock.json
generated
14
dashboard/package-lock.json
generated
@@ -6,7 +6,7 @@
|
||||
"packages": {
|
||||
"": {
|
||||
"dependencies": {
|
||||
"@cloudron/pankow": "^3.6.7",
|
||||
"@cloudron/pankow": "^3.7.0",
|
||||
"@fontsource/inter": "^5.2.8",
|
||||
"@fortawesome/fontawesome-free": "^7.1.0",
|
||||
"@vitejs/plugin-vue": "^6.0.4",
|
||||
@@ -92,9 +92,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@cloudron/pankow": {
|
||||
"version": "3.6.7",
|
||||
"resolved": "https://registry.npmjs.org/@cloudron/pankow/-/pankow-3.6.7.tgz",
|
||||
"integrity": "sha512-Ce41AXeAKjZemXYmOANkSW+667SR3CkM046YSjUvk+PU5m8Vrs8oXGUqZka+ze8QZpDUfGtlCmkyBy8YTPINLQ==",
|
||||
"version": "3.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@cloudron/pankow/-/pankow-3.7.0.tgz",
|
||||
"integrity": "sha512-HIa2xAJdHNttie6DRADPKfxhlx91VZ+AU7YFe6Tc3zlx6cI6aTCyb+uow+w2XYUlllU9g6EkR1dGrPgVhM2ViQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@fontsource/inter": "^5.2.8",
|
||||
@@ -3277,9 +3277,9 @@
|
||||
}
|
||||
},
|
||||
"@cloudron/pankow": {
|
||||
"version": "3.6.7",
|
||||
"resolved": "https://registry.npmjs.org/@cloudron/pankow/-/pankow-3.6.7.tgz",
|
||||
"integrity": "sha512-Ce41AXeAKjZemXYmOANkSW+667SR3CkM046YSjUvk+PU5m8Vrs8oXGUqZka+ze8QZpDUfGtlCmkyBy8YTPINLQ==",
|
||||
"version": "3.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@cloudron/pankow/-/pankow-3.7.0.tgz",
|
||||
"integrity": "sha512-HIa2xAJdHNttie6DRADPKfxhlx91VZ+AU7YFe6Tc3zlx6cI6aTCyb+uow+w2XYUlllU9g6EkR1dGrPgVhM2ViQ==",
|
||||
"requires": {
|
||||
"@fontsource/inter": "^5.2.8",
|
||||
"@fortawesome/fontawesome-free": "^7.1.0",
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
},
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@cloudron/pankow": "^3.6.7",
|
||||
"@cloudron/pankow": "^3.7.0",
|
||||
"@fontsource/inter": "^5.2.8",
|
||||
"@fortawesome/fontawesome-free": "^7.1.0",
|
||||
"@vitejs/plugin-vue": "^6.0.4",
|
||||
|
||||
@@ -298,7 +298,8 @@
|
||||
"app": "App",
|
||||
"name": "Name",
|
||||
"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": {
|
||||
"title": "API Tokens",
|
||||
@@ -331,7 +332,8 @@
|
||||
"name": "Password name",
|
||||
"app": "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": {
|
||||
"title": "Add API Token",
|
||||
|
||||
@@ -105,7 +105,10 @@
|
||||
},
|
||||
"unstable": "Tidak stabil",
|
||||
"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": {
|
||||
@@ -373,7 +376,9 @@
|
||||
"title": "Detail Cadangan",
|
||||
"id": "ID Cadangan",
|
||||
"date": "Dibuat",
|
||||
"size": "Ukuran"
|
||||
"size": "Ukuran",
|
||||
"lastIntegrityCheck": "Pemeriksaan integritas terakhir",
|
||||
"integrityNever": "tidak pernah"
|
||||
},
|
||||
"configureBackupSchedule": {
|
||||
"hours": "Jam",
|
||||
@@ -500,7 +505,8 @@
|
||||
"title": "Konfigurasi Konten Cadangan"
|
||||
},
|
||||
"useFileAndFileNameEncryption": "Enkripsi berkas dan nama berkas digunakan",
|
||||
"useFileEncryption": "Enkripsi berkas digunakan"
|
||||
"useFileEncryption": "Enkripsi berkas digunakan",
|
||||
"checkIntegrity": "Periksa integritas"
|
||||
},
|
||||
"branding": {
|
||||
"logo": "Logo",
|
||||
@@ -891,11 +897,11 @@
|
||||
"reallyDelete": "Apakah Anda yakin ingin menghapus?"
|
||||
},
|
||||
"newDirectoryDialog": {
|
||||
"title": "Nama Folder Baru",
|
||||
"title": "Folder Baru",
|
||||
"create": "Buat"
|
||||
},
|
||||
"newFileDialog": {
|
||||
"title": "Nama berkas Baru",
|
||||
"title": "Nama berkas baru",
|
||||
"create": "Buat"
|
||||
},
|
||||
"renameDialog": {
|
||||
@@ -919,10 +925,10 @@
|
||||
"pasteInProgress": "Penempelan sedang berlangsung",
|
||||
"deleteInProgress": "Penghapusan sedang berlangsung",
|
||||
"chownDialog": {
|
||||
"title": "Ubah kepemilikan",
|
||||
"title": "Ubah pemilik",
|
||||
"newOwner": "Pemilik baru",
|
||||
"change": "Ubah Pemilik",
|
||||
"recursiveCheckbox": "Ubah kepemilikan secara rekursif"
|
||||
"change": "Ubah pemilik",
|
||||
"recursiveCheckbox": "Ubah pemilik secara rekursif"
|
||||
},
|
||||
"uploadingDialog": {
|
||||
"title": "Mengunggah berkas ({{ countDone }}/{{ count }})",
|
||||
@@ -1370,7 +1376,8 @@
|
||||
"packageVersion": "Paket",
|
||||
"lastUpdated": "Terakhir diperbarui",
|
||||
"customAppUpdateInfo": "Pembaruan otomatis tidak tersedia untuk aplikasi khusus.",
|
||||
"installedAt": "Terpasang"
|
||||
"installedAt": "Terpasang",
|
||||
"packager": "Pengemas"
|
||||
},
|
||||
"auto": {
|
||||
"description": "Pembaruan aplikasi diterapkan secara berkala berdasarkan <a href=\"/#/system-update\">jadwal pembaruan</a>",
|
||||
@@ -1684,5 +1691,8 @@
|
||||
"title": "Kata sandi telah diubah",
|
||||
"openDashboardAction": "Buka dasbor"
|
||||
}
|
||||
},
|
||||
"communityapp": {
|
||||
"installwarning": "Aplikasi komunitas tidak ditinjau oleh Cloudron. Hanya instal aplikasi dari pengembang tepercaya. Kode pihak ketiga dapat membahayakan sistem Anda."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,7 +385,9 @@
|
||||
"date": "Aangemaakt",
|
||||
"version": "Package versie",
|
||||
"size": "Grootte",
|
||||
"duration": "Backup duur"
|
||||
"duration": "Backup duur",
|
||||
"lastIntegrityCheck": "Laatste integriteitscontrole",
|
||||
"integrityNever": "nooit"
|
||||
},
|
||||
"configureBackupSchedule": {
|
||||
"title": "Configureer Backup Planning & Bewaartermijn",
|
||||
@@ -503,7 +505,8 @@
|
||||
"title": "Configureer Backup Inhoud"
|
||||
},
|
||||
"useFileAndFileNameEncryption": "Bestand en bestandsnaam encryptie gebruikt",
|
||||
"useFileEncryption": "Bestand encryptie gebruikt"
|
||||
"useFileEncryption": "Bestand encryptie gebruikt",
|
||||
"checkIntegrity": "Controleer integriteit"
|
||||
},
|
||||
"branding": {
|
||||
"title": "Huisstijl",
|
||||
@@ -859,7 +862,8 @@
|
||||
"packageVersion": "Pakket",
|
||||
"lastUpdated": "Laatst geüpdatet",
|
||||
"customAppUpdateInfo": "Auto-update is niet beschikbaar voor maatwerk apps.",
|
||||
"installedAt": "Geïnstalleerd"
|
||||
"installedAt": "Geïnstalleerd",
|
||||
"packager": "Pakketmaker"
|
||||
},
|
||||
"auto": {
|
||||
"description": "App updates worden uitgevoerd op basis van de <a href=\"/#/system-update\">update planning</a>.",
|
||||
|
||||
@@ -105,6 +105,9 @@
|
||||
"appNotFoundDialog": {
|
||||
"title": "Приложение не найдено",
|
||||
"description": "Не найдено приложения <b>{{ appId }}</b> версии <b>{{ version }}</b>."
|
||||
},
|
||||
"action": {
|
||||
"addCustomApp": "Добавить стороннее приложение"
|
||||
}
|
||||
},
|
||||
"users": {
|
||||
@@ -366,7 +369,8 @@
|
||||
"appId": "ID приложения",
|
||||
"packageVersion": "Пакет",
|
||||
"lastUpdated": "Обновлен",
|
||||
"installedAt": "Установлено"
|
||||
"installedAt": "Установлено",
|
||||
"packager": "Сборщик"
|
||||
},
|
||||
"auto": {
|
||||
"title": "Автоматические обновления",
|
||||
@@ -555,11 +559,27 @@
|
||||
"csp": {
|
||||
"title": "Политика безопасности контента",
|
||||
"saveAction": "Сохранить",
|
||||
"description": "Перезаписать любые CSP заголовки, отправляемые приложением"
|
||||
"description": "Перезаписать любые CSP заголовки, отправляемые приложением",
|
||||
"insertCommonCsp": "Вставить стандартный CSP",
|
||||
"commonPattern": {
|
||||
"allowEmbedding": "Разрешить встраивание",
|
||||
"sameOriginEmbedding": "Разрешить встраивание (только поддомены)",
|
||||
"allowCdnAssets": "Разрешить использование ресурсов CDN",
|
||||
"reportOnly": "Сообщить о нарушениях CSP",
|
||||
"strictBaseline": "Строгий базовый уровень"
|
||||
}
|
||||
},
|
||||
"robots": {
|
||||
"title": "Robots.txt",
|
||||
"description": "По умолчанию, роботы могут индексировать это приложение"
|
||||
"description": "По умолчанию, роботы могут индексировать это приложение",
|
||||
"commonPattern": {
|
||||
"allowAll": "Разрешить все (по умолчанию)",
|
||||
"disallowAll": "Запретить все",
|
||||
"disallowCommonBots": "Запретить известных ботов",
|
||||
"disallowAdminPaths": "Запретить пути админа",
|
||||
"disallowApiPaths": "Запретить пути API"
|
||||
},
|
||||
"insertCommonRobotsTxt": "Вставить стандартный robots.txt"
|
||||
},
|
||||
"hstsPreload": "Активировать предзагрузку HSTS (в том числе для поддоменов)"
|
||||
},
|
||||
@@ -779,7 +799,9 @@
|
||||
"date": "Создано",
|
||||
"version": "Версия пакета",
|
||||
"size": "Размер",
|
||||
"duration": "Продолжительность резервного копирования"
|
||||
"duration": "Продолжительность резервного копирования",
|
||||
"lastIntegrityCheck": "Последняя проверка целостности",
|
||||
"integrityNever": "никогда"
|
||||
},
|
||||
"backupEdit": {
|
||||
"title": "Редактировать резервную копию",
|
||||
@@ -821,7 +843,8 @@
|
||||
"title": "Настроить содержание резервной копии"
|
||||
},
|
||||
"useFileAndFileNameEncryption": "Используется шифрование файлов и их имён",
|
||||
"useFileEncryption": "Используется шифрование файлов"
|
||||
"useFileEncryption": "Используется шифрование файлов",
|
||||
"checkIntegrity": "Проверить целостность"
|
||||
},
|
||||
"branding": {
|
||||
"title": "Брендирование",
|
||||
@@ -1218,7 +1241,7 @@
|
||||
"filemanager": {
|
||||
"title": "Файловый менеджер",
|
||||
"newDirectoryDialog": {
|
||||
"title": "Имя новой папки",
|
||||
"title": "Новая папка",
|
||||
"create": "Создать"
|
||||
},
|
||||
"newFileDialog": {
|
||||
@@ -1249,7 +1272,7 @@
|
||||
"pasteInProgress": "Выполняется копирование / перемещение",
|
||||
"deleteInProgress": "Выполняется удаление",
|
||||
"chownDialog": {
|
||||
"title": "Смена владельца",
|
||||
"title": "Изменить владельца",
|
||||
"newOwner": "Новый владелец",
|
||||
"change": "Изменить владельца",
|
||||
"recursiveCheckbox": "Изменить владельца рекурсивно"
|
||||
@@ -1280,7 +1303,7 @@
|
||||
"symlink": "Символическая ссылка на {{ target }}",
|
||||
"menu": {
|
||||
"rename": "Переименовать",
|
||||
"chown": "Изменить владельца",
|
||||
"chown": "Смена владельца",
|
||||
"extract": "Распаковать здесь",
|
||||
"download": "Скачать",
|
||||
"delete": "Удалить",
|
||||
@@ -1668,5 +1691,8 @@
|
||||
},
|
||||
"server": {
|
||||
"title": "Сервер"
|
||||
},
|
||||
"communityapp": {
|
||||
"installwarning": "Cloudron не проводит аудит приложений, созданных сообществом. Устанавливайте приложения только от проверенных разработчиков. Сторонний код может поставить под угрозу безопасности вашей системы."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,8 @@ import { useI18n } from 'vue-i18n';
|
||||
const i18n = useI18n();
|
||||
const t = i18n.t;
|
||||
|
||||
import moment from 'moment-timezone';
|
||||
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 ActionBar from './ActionBar.vue';
|
||||
import Section from './Section.vue';
|
||||
@@ -35,7 +34,16 @@ const columns = {
|
||||
sort(a, b) {
|
||||
if (!a) 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: {}
|
||||
@@ -54,6 +62,8 @@ const addedPassword = ref('');
|
||||
const passwordName = ref('');
|
||||
const identifiers = ref([]);
|
||||
const identifier = ref('');
|
||||
const expiresAtDate = ref('');
|
||||
const minExpiresAt = new Date().toISOString().slice(0, 16);
|
||||
const addError = ref('');
|
||||
const busy = ref(false);
|
||||
|
||||
@@ -62,16 +72,20 @@ async function refresh() {
|
||||
const [error, result] = await appPasswordsModel.list();
|
||||
if (error) return console.error(error);
|
||||
|
||||
// setup label for the table UI
|
||||
result.forEach(function (password) {
|
||||
if (password.identifier === 'mail') return password.label = password.identifier;
|
||||
const app = appsById[password.identifier];
|
||||
if (!app) return password.label = password.identifier + ' (App not found)';
|
||||
for (const password of result) {
|
||||
if (password.identifier === 'mail') {
|
||||
password.label = password.identifier;
|
||||
} else {
|
||||
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 labelSuffix = ftp ? ' - SFTP' : '';
|
||||
password.label = app.label ? app.label + ' (' + app.fqdn + ')' + labelSuffix : app.fqdn + labelSuffix;
|
||||
});
|
||||
const ftp = app.manifest.addons && app.manifest.addons.localstorage && app.manifest.addons.localstorage.ftp;
|
||||
const labelSuffix = ftp ? ' - SFTP' : '';
|
||||
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;
|
||||
}
|
||||
@@ -86,6 +100,7 @@ function onReset() {
|
||||
setTimeout(() => {
|
||||
passwordName.value = '';
|
||||
identifier.value = '';
|
||||
expiresAtDate.value = '';
|
||||
addedPassword.value = '';
|
||||
addError.value = '';
|
||||
busy.value = false;
|
||||
@@ -100,7 +115,8 @@ async function onSubmit() {
|
||||
addError.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) {
|
||||
busy.value = false;
|
||||
addError.value = error.body ? error.body.message : 'Internal error';
|
||||
@@ -110,6 +126,7 @@ async function onSubmit() {
|
||||
addedPassword.value = result.password;
|
||||
passwordName.value = '';
|
||||
identifier.value = '';
|
||||
expiresAtDate.value = '';
|
||||
|
||||
await refresh();
|
||||
|
||||
@@ -197,6 +214,11 @@ onMounted(async () => {
|
||||
<label>{{ $t('profile.createAppPassword.app') }}</label>
|
||||
<SingleSelect outline v-model="identifier" :options="identifiers" option-label="label" option-key="id" required/>
|
||||
</FormGroup>
|
||||
|
||||
<FormGroup>
|
||||
<label for="expiresAt">{{ $t('profile.createAppPassword.expiresAt') }} (optional)</label>
|
||||
<DateTimeInput id="expiresAt" v-model="expiresAtDate" :min="minExpiresAt"/>
|
||||
</FormGroup>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
@@ -221,7 +243,13 @@ onMounted(async () => {
|
||||
<br/>
|
||||
|
||||
<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">
|
||||
<ActionBar :actions="createActionMenu(password)" />
|
||||
</template>
|
||||
|
||||
@@ -18,10 +18,10 @@ function create() {
|
||||
if (error || result.status !== 200) return [error || result];
|
||||
return [null, result.body.appPasswords];
|
||||
},
|
||||
async add(identifier, name) {
|
||||
async add(identifier, name, expiresAt) {
|
||||
let error, result;
|
||||
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) {
|
||||
error = e;
|
||||
}
|
||||
|
||||
15
migrations/20260212000000-appPasswords-add-expiresAt.js
Normal file
15
migrations/20260212000000-appPasswords-add-expiresAt.js
Normal file
@@ -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);
|
||||
});
|
||||
};
|
||||
@@ -293,6 +293,7 @@ CREATE TABLE IF NOT EXISTS appPasswords(
|
||||
identifier VARCHAR(128) NOT NULL, // resourceId: app id or mail or webadmin
|
||||
hashedPassword VARCHAR(1024) NOT NULL,
|
||||
creationTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expiresAt TIMESTAMP NULL DEFAULT NULL,
|
||||
UNIQUE KEY appPasswords_name_appId_identifier (name, userId, identifier)
|
||||
FOREIGN KEY(userId) REFERENCES users(id),
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ const assert = require('node:assert'),
|
||||
safe = require('safetydance'),
|
||||
_ = 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) {
|
||||
assert.strictEqual(typeof name, 'string');
|
||||
@@ -29,7 +29,7 @@ function validateAppPasswordName(name) {
|
||||
}
|
||||
|
||||
function removePrivateFields(appPassword) {
|
||||
return _.pick(appPassword, ['id', 'name', 'userId', 'identifier', 'creationTime']);
|
||||
return _.pick(appPassword, ['id', 'name', 'userId', 'identifier', 'creationTime', 'expiresAt']);
|
||||
}
|
||||
|
||||
async function get(id) {
|
||||
@@ -40,10 +40,11 @@ async function get(id) {
|
||||
return result[0];
|
||||
}
|
||||
|
||||
async function add(userId, identifier, name) {
|
||||
async function add(userId, identifier, name, expiresAt) {
|
||||
assert.strictEqual(typeof userId, 'string');
|
||||
assert.strictEqual(typeof identifier, 'string');
|
||||
assert.strictEqual(typeof name, 'string');
|
||||
assert(expiresAt === null || typeof expiresAt === 'string');
|
||||
|
||||
let error = validateAppPasswordName(name);
|
||||
if (error) throw error;
|
||||
@@ -59,11 +60,12 @@ async function add(userId, identifier, name) {
|
||||
userId,
|
||||
identifier,
|
||||
password,
|
||||
hashedPassword
|
||||
hashedPassword,
|
||||
expiresAt
|
||||
};
|
||||
|
||||
const query = 'INSERT INTO appPasswords (id, userId, identifier, name, hashedPassword) VALUES (?, ?, ?, ?, ?)';
|
||||
const args = [ appPassword.id, appPassword.userId, appPassword.identifier, appPassword.name, appPassword.hashedPassword ];
|
||||
const query = 'INSERT INTO appPasswords (id, userId, identifier, name, hashedPassword, expiresAt) VALUES (?, ?, ?, ?, ?, ?)';
|
||||
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));
|
||||
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');
|
||||
|
||||
@@ -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.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));
|
||||
|
||||
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) {
|
||||
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));
|
||||
|
||||
result = result.map(appPasswords.removePrivateFields);
|
||||
next(new HttpSuccess(200, { appPasswords: result }));
|
||||
next(new HttpSuccess(200, { appPasswords: result.map(appPasswords.removePrivateFields) }));
|
||||
}
|
||||
|
||||
async function del(req, res, next) {
|
||||
|
||||
@@ -29,7 +29,34 @@ describe('App Passwords', function () {
|
||||
it('cannot add app password without name', async function () {
|
||||
const response = await superagent.post(`${serverUrl}/api/v1/app_passwords`)
|
||||
.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);
|
||||
|
||||
expect(response.status).to.equal(400);
|
||||
@@ -39,24 +66,36 @@ describe('App Passwords', function () {
|
||||
it('can add app password', async function () {
|
||||
const response = await superagent.post(`${serverUrl}/api/v1/app_passwords`)
|
||||
.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.body.password).to.be.a('string');
|
||||
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 () {
|
||||
const response = await superagent.get(`${serverUrl}/api/v1/app_passwords`)
|
||||
.query({ access_token: user.token });
|
||||
|
||||
expect(response.status).to.equal(200);
|
||||
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].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].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 () {
|
||||
@@ -66,6 +105,7 @@ describe('App Passwords', function () {
|
||||
expect(response.status).to.equal(200);
|
||||
expect(response.body.name).to.be('my-device');
|
||||
expect(response.body.identifier).to.be('someapp');
|
||||
expect(response.body.expiresAt).to.be(null);
|
||||
expect(response.body.hashedPassword).to.be(undefined);
|
||||
expect(response.body.password).to.be(undefined);
|
||||
});
|
||||
|
||||
@@ -21,12 +21,12 @@ describe('App passwords', function () {
|
||||
|
||||
let id, password;
|
||||
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);
|
||||
});
|
||||
|
||||
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.password).to.be.a('string');
|
||||
id = result.id;
|
||||
@@ -90,4 +90,38 @@ describe('App passwords', function () {
|
||||
const [error] = await safe(appPasswords.del('random'));
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -619,7 +619,8 @@ async function verifyAppPassword(userId, password, identifier) {
|
||||
|
||||
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');
|
||||
|
||||
if (hashedPasswords.includes(hash)) return;
|
||||
|
||||
Reference in New Issue
Block a user