Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/stores/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { getClient } from '~/util/awclient';
import { Category, CategorySet, defaultCategories, cleanCategory } from '~/util/classes';
import { SavedQuery } from '~/util/savedQueries';
import { View, defaultViews } from '~/stores/views';
import type { PrivacyFilterRule } from '~/util/privacyFilters';
import { isEqual } from 'lodash';

function jsonEq(a: any, b: any) {
Expand Down Expand Up @@ -39,6 +40,7 @@ interface State {
timesPollIsShown: number;
};
always_active_pattern: string;
privacy_filters: PrivacyFilterRule[];
classes: Category[];
// Named category sets — each set is an independent collection of category rules.
// The active_set_ids list controls which sets are combined (in priority order).
Expand Down Expand Up @@ -83,6 +85,7 @@ export const useSettingsStore = defineStore('settings', {
},

always_active_pattern: '',
privacy_filters: [],
classes: defaultCategories,
category_sets: [],
active_set_ids: ['default'],
Expand Down
163 changes: 163 additions & 0 deletions src/util/privacyFilters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
export type PrivacyFilterAction = 'drop' | 'redact';

export interface PrivacyFilterRule {
enabled: boolean;
bucket_prefix?: string;
field: string;
pattern: string;
action: PrivacyFilterAction;
replacement?: string;
}

export interface PrivacyFilterValidationResult {
rules: PrivacyFilterRule[] | null;
errors: string[];
}

export const DEFAULT_PRIVACY_FILTERS: PrivacyFilterRule[] = [
{
enabled: true,
bucket_prefix: 'aw-watcher-window',
field: 'title',
pattern: '(?i)(private browsing|incognito)',
action: 'drop',
},
{
enabled: true,
bucket_prefix: 'aw-watcher-window',
field: 'title',
pattern: '(?i).*banking.*',
action: 'redact',
replacement: 'REDACTED',
},
];

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}

function optionalString(
value: unknown,
fieldName: string,
ruleNumber: number,
errors: string[]
): string | undefined {
if (value === undefined || value === null) {
return undefined;
}
if (typeof value !== 'string') {
errors.push(`Rule ${ruleNumber}: \`${fieldName}\` must be a string when provided.`);
return undefined;
}
if (value.trim() === '') {
errors.push(`Rule ${ruleNumber}: \`${fieldName}\` cannot be empty when provided.`);
return undefined;
}
return value;
}

export function formatPrivacyFilters(rules: PrivacyFilterRule[]): string {
return JSON.stringify(rules, null, 2);
}

export function validatePrivacyFiltersInput(input: string): PrivacyFilterValidationResult {
const trimmed = input.trim();
if (trimmed === '') {
return { rules: [], errors: [] };
}

let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
rules: null,
errors: [`Invalid JSON: ${message}`],
};
}

if (!Array.isArray(parsed)) {
return {
rules: null,
errors: ['Top-level value must be a JSON array of privacy filter rules.'],
};
}

const errors: string[] = [];
const rules: PrivacyFilterRule[] = [];

parsed.forEach((candidate, index) => {
const ruleNumber = index + 1;
if (!isRecord(candidate)) {
errors.push(`Rule ${ruleNumber}: each rule must be a JSON object.`);
return;
}

const errorCountBefore = errors.length;
const enabled = candidate.enabled;
if (typeof enabled !== 'boolean') {
errors.push(`Rule ${ruleNumber}: \`enabled\` must be a boolean.`);
}

const pattern = candidate.pattern;
if (typeof pattern !== 'string') {
errors.push(`Rule ${ruleNumber}: \`pattern\` must be a string.`);
} else if (pattern.trim() === '') {
errors.push(`Rule ${ruleNumber}: \`pattern\` cannot be an empty string.`);
}
Comment on lines +103 to +108
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Empty pattern strings pass client-side validation (only the type is checked, not the value), so a user can save {"pattern": ""} — a rule that silently matches every event. Adding a non-empty check here catches the mistake before the server applies the rule.

Suggested change
const pattern = candidate.pattern;
if (typeof pattern !== 'string') {
errors.push(`Rule ${ruleNumber}: \`pattern\` must be a string.`);
}
const pattern = candidate.pattern;
if (typeof pattern !== 'string') {
errors.push(`Rule ${ruleNumber}: \`pattern\` must be a string.`);
} else if (pattern.trim() === '') {
errors.push(`Rule ${ruleNumber}: \`pattern\` cannot be an empty string.`);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 0b6fb9c: added else if (pattern.trim() === '') check so an empty pattern string is rejected with a clear error instead of silently passing through.


const bucketPrefix = optionalString(
candidate.bucket_prefix,
'bucket_prefix',
ruleNumber,
errors
);
let field: string | undefined;
if (candidate.field === undefined || candidate.field === null) {
errors.push(
`Rule ${ruleNumber}: \`field\` is required so the rule only matches the intended event data.`
);
} else if (typeof candidate.field !== 'string') {
errors.push(`Rule ${ruleNumber}: \`field\` must be a string.`);
} else if (candidate.field.trim() === '') {
errors.push(`Rule ${ruleNumber}: \`field\` cannot be an empty string.`);
} else {
field = candidate.field;
}
const replacement = optionalString(candidate.replacement, 'replacement', ruleNumber, errors);

const action = candidate.action;
if (action !== 'drop' && action !== 'redact') {
errors.push(`Rule ${ruleNumber}: \`action\` must be either "drop" or "redact".`);
}

if (action === 'redact' && replacement === undefined) {
errors.push(`Rule ${ruleNumber}: redact rules need a non-empty \`replacement\` string.`);
}

if (
errors.length > errorCountBefore ||
typeof enabled !== 'boolean' ||
typeof pattern !== 'string' ||
field === undefined ||
(action !== 'drop' && action !== 'redact')
) {
return;
}

rules.push({
enabled,
bucket_prefix: bucketPrefix,
field,
pattern,
action,
replacement,
});
});

return {
rules: errors.length === 0 ? rules : null,
errors,
};
}
129 changes: 129 additions & 0 deletions src/views/settings/PrivacyFilterSettings.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<template lang="pug">
div
div.d-sm-flex.justify-content-between
div
h5.mt-1.mb-2.mb-sm-0 Privacy filters
div
b-btn.ml-1(@click="resetEditor" variant="outline-warning" size="sm" :disabled="!hasUnsavedChanges || isSaving")
| Discard
b-btn.ml-1(@click="savePrivacyFilters" variant="success" size="sm" :disabled="!canSave")
| Save
p.mt-2.mb-2
| Regex-based rules that drop or redact sensitive event data before it is stored.
| Rules are saved to the server setting #[code privacy_filters] and used by aw-server-rust.
small.text-muted
| Leave the editor empty or save #[code []] to disable the feature.

b-alert.mt-3(:show="saveError !== ''" variant="danger")
| {{ saveError }}

b-alert.mt-3(:show="validationErrors.length > 0" variant="danger")
div(v-for="error in validationErrors" :key="error")
| {{ error }}

b-alert.mt-3(:show="hasUnsavedChanges && validationErrors.length === 0" variant="warning")
| You have unsaved changes.

b-form-textarea.mt-3(
v-model="editorText"
rows="14"
max-rows="24"
:state="editorState"
style="font-family: monospace"
)

small.d-block.text-muted.mt-2
| Each rule needs #[code enabled], #[code pattern], #[code action], and #[code field].
| Redact rules also need #[code replacement].
| Regex syntax is validated by the server when you save.

small.d-block.text-muted.mt-3 Example
pre.mt-3.mb-0.small(style="white-space: pre-wrap") {{ exampleText }}
</template>

<script lang="ts">
import { useSettingsStore } from '~/stores/settings';
import {
DEFAULT_PRIVACY_FILTERS,
formatPrivacyFilters,
validatePrivacyFiltersInput,
} from '~/util/privacyFilters';

export default {
name: 'PrivacyFilterSettings',
data() {
return {
settingsStore: useSettingsStore(),
editorText: '',
savedText: '',
saveError: '',
isSaving: false,
};
},
computed: {
validationResult() {
return validatePrivacyFiltersInput(this.editorText);
},
validationErrors() {
return this.validationResult.errors;
},
canSave() {
return this.hasUnsavedChanges && this.validationErrors.length === 0 && !this.isSaving;
},
hasUnsavedChanges() {
return this.editorText !== this.savedText;
},
editorState() {
if (!this.hasUnsavedChanges) {
return null;
}
return this.validationErrors.length === 0;
},
exampleText() {
return formatPrivacyFilters(DEFAULT_PRIVACY_FILTERS);
},
},
watch: {
'settingsStore.privacy_filters': {
deep: true,
handler() {
this.syncFromStore(false);
},
},
},
mounted() {
this.syncFromStore(true);
},
methods: {
syncFromStore(overwriteEditor: boolean) {
const serialized = formatPrivacyFilters(this.settingsStore.privacy_filters);
if (overwriteEditor || this.editorText === this.savedText) {
this.editorText = serialized;
}
this.savedText = serialized;
},
resetEditor() {
this.saveError = '';
this.syncFromStore(true);
},
async savePrivacyFilters() {
if (!this.canSave) {
return;
}

this.isSaving = true;
this.saveError = '';
try {
await this.settingsStore.update({
privacy_filters: this.validationResult.rules || [],
});
this.syncFromStore(true);
} catch (error) {
this.saveError = error instanceof Error ? error.message : String(error);
} finally {
this.isSaving = false;
}
},
},
};
</script>
6 changes: 6 additions & 0 deletions src/views/settings/Settings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ div

hr

PrivacyFilterSettings

hr

CategorizationSettings

hr
Expand All @@ -52,6 +56,7 @@ import DeveloperSettings from '~/views/settings/DeveloperSettings.vue';
import Theme from '~/views/settings/Theme.vue';
import ColorSettings from '~/views/settings/ColorSettings.vue';
import ActivePatternSettings from '~/views/settings/ActivePatternSettings.vue';
import PrivacyFilterSettings from '~/views/settings/PrivacyFilterSettings.vue';

export default {
name: 'Settings',
Expand All @@ -65,6 +70,7 @@ export default {
ColorSettings,
DeveloperSettings,
ActivePatternSettings,
PrivacyFilterSettings,
},
beforeRouteLeave(to, from, next) {
const categoryStore = useCategoryStore();
Expand Down
Loading
Loading