2020-05-07 00:13:02 +00:00
|
|
|
import argparse
|
2020-05-23 20:27:23 +00:00
|
|
|
import base64
|
2020-04-28 02:21:36 +00:00
|
|
|
import io
|
2020-04-05 01:30:53 +00:00
|
|
|
import json
|
2022-01-25 19:28:06 +00:00
|
|
|
import os
|
2020-06-02 18:54:47 +00:00
|
|
|
import pickle
|
2020-02-21 23:52:29 +00:00
|
|
|
import urllib.parse as urlparse
|
2020-06-02 18:54:47 +00:00
|
|
|
import uuid
|
2022-02-14 19:19:02 +00:00
|
|
|
from datetime import datetime, timedelta
|
2020-06-11 18:14:57 +00:00
|
|
|
from functools import wraps
|
|
|
|
|
2020-05-12 23:14:55 +00:00
|
|
|
import waitress
|
2020-06-11 18:14:57 +00:00
|
|
|
from app import app
|
|
|
|
from app.models.config import Config
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
from app.models.endpoint import Endpoint
|
Add tor and http/socks proxy support (#137)
* Add tor and http/socks proxy support
Allows users to enable/disable tor from the config menu, which will
forward all requests through Tor.
Also adds support for setting environment variables for alternative
proxy support. Setting the following variables will forward requests
through the proxy:
- WHOOGLE_PROXY_USER (optional)
- WHOOGLE_PROXY_PASS (optional)
- WHOOGLE_PROXY_TYPE (required)
- Can be "http", "socks4", or "socks5"
- WHOOGLE_PROXY_LOC (required)
- Format: "<ip address>:<port>"
See #30
* Refactor acquire_tor_conn -> acquire_tor_identity
Also updated travis CI to set up tor
* Add check for Tor socket on init, improve Tor error handling
Initializing the app sends a heartbeat request to Tor to check for
availability, and updates the home page config options accordingly. This
heartbeat is sent on every request, to ensure Tor support can be
reconfigured without restarting the entire app.
If Tor support is enabled, and a subsequent request fails, then a new
TorError exception is raised, and the Tor feature is disabled until a
valid connection is restored.
The max attempts has been updated to 10, since 5 seemed a bit too low
for how quickly the attempts go by.
* Change send_tor_signal arg type, update function doc
send_tor_signal now accepts a stem.Signal arg (a bit cleaner tbh). Also
added the doc string for the "disable" attribute in TorError.
* Fix tor identity logic in Request.send
* Update proxy init, change proxyloc var name
Proxy is now only initialized if both type and location are specified,
as neither have a default fallback and both are required. I suppose the
type could fall back to http, but seems safer this way.
Also refactored proxyurl -> proxyloc for the runtime args in order to
match the Dockerfile args.
* Add tor/proxy support for Docker builds, fix opensearch/init
The Dockerfile is now updated to include support for Tor configuration,
with a working torrc file included in the repo.
An issue with opensearch was fixed as well, which was uncovered during
testing and was simple enough to fix here. Likewise, DDG bang gen was
updated to only ever happen if the file didn't exist previously, as
testing with the file being regenerated every time was tedious.
* Add missing "@" for socks proxy requests
2020-10-29 00:47:42 +00:00
|
|
|
from app.request import Request, TorError
|
2021-03-08 17:22:04 +00:00
|
|
|
from app.utils.bangs import resolve_bang
|
2022-04-13 17:29:07 +00:00
|
|
|
from app.filter import Filter
|
2022-02-14 19:19:02 +00:00
|
|
|
from app.utils.misc import read_config_bool, get_client_ip, get_request_url, \
|
|
|
|
check_for_update
|
2021-12-07 05:56:13 +00:00
|
|
|
from app.utils.results import add_ip_card, bold_search_terms,\
|
2022-02-07 17:47:25 +00:00
|
|
|
add_currency_card, check_currency, get_tabs_content
|
|
|
|
from app.utils.search import Search, needs_https, has_captcha
|
2021-10-21 16:42:31 +00:00
|
|
|
from app.utils.session import generate_user_key, valid_user_session
|
|
|
|
from bs4 import BeautifulSoup as bsoup
|
|
|
|
from flask import jsonify, make_response, request, redirect, render_template, \
|
2022-02-07 17:47:25 +00:00
|
|
|
send_file, session, url_for, g
|
2021-11-02 16:35:40 +00:00
|
|
|
from requests import exceptions, get
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
from requests.models import PreparedRequest
|
2022-04-18 19:06:44 +00:00
|
|
|
from cryptography.fernet import Fernet, InvalidToken
|
|
|
|
from cryptography.exceptions import InvalidSignature
|
2020-01-21 20:26:49 +00:00
|
|
|
|
2020-10-10 19:55:14 +00:00
|
|
|
# Load DDG bang json files only on init
|
2022-01-25 19:28:06 +00:00
|
|
|
bang_json = json.load(open(app.config['BANG_FILE'])) or {}
|
2020-10-10 19:55:14 +00:00
|
|
|
|
2022-01-18 20:39:56 +00:00
|
|
|
ac_var = 'WHOOGLE_AUTOCOMPLETE'
|
|
|
|
autocomplete_enabled = os.getenv(ac_var, '1')
|
|
|
|
|
2021-11-02 16:35:40 +00:00
|
|
|
|
2020-05-18 16:30:32 +00:00
|
|
|
def auth_required(f):
|
|
|
|
@wraps(f)
|
|
|
|
def decorated(*args, **kwargs):
|
|
|
|
auth = request.authorization
|
|
|
|
|
|
|
|
# Skip if username/password not set
|
|
|
|
whoogle_user = os.getenv('WHOOGLE_USER', '')
|
|
|
|
whoogle_pass = os.getenv('WHOOGLE_PASS', '')
|
2020-12-17 21:06:47 +00:00
|
|
|
if (not whoogle_user or not whoogle_pass) or (
|
|
|
|
auth
|
|
|
|
and whoogle_user == auth.username
|
|
|
|
and whoogle_pass == auth.password):
|
2020-05-18 16:30:32 +00:00
|
|
|
return f(*args, **kwargs)
|
|
|
|
else:
|
2020-12-17 21:06:47 +00:00
|
|
|
return make_response('Not logged in', 401, {
|
|
|
|
'WWW-Authenticate': 'Basic realm="Login Required"'})
|
|
|
|
|
2020-05-18 16:30:32 +00:00
|
|
|
return decorated
|
|
|
|
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
def session_required(f):
|
|
|
|
@wraps(f)
|
|
|
|
def decorated(*args, **kwargs):
|
|
|
|
if (valid_user_session(session) and
|
|
|
|
'cookies_disabled' not in request.args):
|
|
|
|
g.session_key = session['key']
|
|
|
|
else:
|
|
|
|
session.pop('_permanent', None)
|
|
|
|
g.session_key = app.default_key
|
|
|
|
|
|
|
|
# Clear out old sessions
|
|
|
|
invalid_sessions = []
|
|
|
|
for user_session in os.listdir(app.config['SESSION_FILE_DIR']):
|
|
|
|
session_path = os.path.join(
|
|
|
|
app.config['SESSION_FILE_DIR'],
|
|
|
|
user_session)
|
|
|
|
try:
|
|
|
|
with open(session_path, 'rb') as session_file:
|
|
|
|
_ = pickle.load(session_file)
|
|
|
|
data = pickle.load(session_file)
|
|
|
|
if isinstance(data, dict) and 'valid' in data:
|
|
|
|
continue
|
|
|
|
invalid_sessions.append(session_path)
|
2022-06-03 20:29:57 +00:00
|
|
|
except (EOFError, FileNotFoundError, pickle.UnpicklingError):
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
for invalid_session in invalid_sessions:
|
2021-12-21 21:03:24 +00:00
|
|
|
try:
|
|
|
|
os.remove(invalid_session)
|
|
|
|
except FileNotFoundError:
|
|
|
|
# Don't throw error if the invalid session has been removed
|
|
|
|
pass
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
|
|
|
|
return f(*args, **kwargs)
|
|
|
|
|
|
|
|
return decorated
|
|
|
|
|
|
|
|
|
2020-04-24 02:59:43 +00:00
|
|
|
@app.before_request
|
|
|
|
def before_request_func():
|
2022-01-25 19:28:06 +00:00
|
|
|
global bang_json
|
|
|
|
|
2022-02-14 19:19:02 +00:00
|
|
|
# Check for latest version if needed
|
|
|
|
now = datetime.now()
|
|
|
|
if now - timedelta(hours=24) > app.config['LAST_UPDATE_CHECK']:
|
|
|
|
app.config['LAST_UPDATE_CHECK'] = now
|
|
|
|
app.config['HAS_UPDATE'] = check_for_update(
|
|
|
|
app.config['RELEASES_URL'],
|
|
|
|
app.config['VERSION_NUMBER'])
|
|
|
|
|
2020-12-17 21:06:47 +00:00
|
|
|
g.request_params = (
|
|
|
|
request.args if request.method == 'GET' else request.form
|
|
|
|
)
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
|
|
|
|
# Skip pre-request actions if verifying session
|
|
|
|
if '/session' in request.path and not valid_user_session(session):
|
|
|
|
return
|
|
|
|
|
|
|
|
default_config = json.load(open(app.config['DEFAULT_CONFIG'])) \
|
|
|
|
if os.path.exists(app.config['DEFAULT_CONFIG']) else {}
|
2020-06-05 21:24:44 +00:00
|
|
|
|
|
|
|
# Generate session values for user if unavailable
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
if (not valid_user_session(session) and
|
|
|
|
'cookies_disabled' not in request.args):
|
|
|
|
session['config'] = default_config
|
2020-06-02 18:54:47 +00:00
|
|
|
session['uuid'] = str(uuid.uuid4())
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
session['key'] = generate_user_key()
|
|
|
|
|
2021-11-22 07:26:25 +00:00
|
|
|
# Skip checking for session on any searches that don't
|
|
|
|
# require a valid session
|
|
|
|
if (not Endpoint.autocomplete.in_path(request.path) and
|
2022-01-11 17:50:35 +00:00
|
|
|
not Endpoint.healthz.in_path(request.path) and
|
|
|
|
not Endpoint.opensearch.in_path(request.path)):
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
return redirect(url_for(
|
|
|
|
'session_check',
|
|
|
|
session_id=session['uuid'],
|
2021-11-22 06:21:04 +00:00
|
|
|
follow=get_request_url(request.url)), code=307)
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
else:
|
|
|
|
g.user_config = Config(**session['config'])
|
|
|
|
elif 'cookies_disabled' not in request.args:
|
|
|
|
# Set session as permanent
|
|
|
|
session.permanent = True
|
|
|
|
app.permanent_session_lifetime = timedelta(days=365)
|
|
|
|
g.user_config = Config(**session['config'])
|
|
|
|
else:
|
|
|
|
# User has cookies disabled, fall back to immutable default config
|
|
|
|
session.pop('_permanent', None)
|
|
|
|
g.user_config = Config(**default_config)
|
2020-06-02 18:54:47 +00:00
|
|
|
|
2020-05-12 23:15:53 +00:00
|
|
|
if not g.user_config.url:
|
2021-11-22 06:21:04 +00:00
|
|
|
g.user_config.url = get_request_url(request.url_root)
|
2020-05-10 19:27:02 +00:00
|
|
|
|
Add tor and http/socks proxy support (#137)
* Add tor and http/socks proxy support
Allows users to enable/disable tor from the config menu, which will
forward all requests through Tor.
Also adds support for setting environment variables for alternative
proxy support. Setting the following variables will forward requests
through the proxy:
- WHOOGLE_PROXY_USER (optional)
- WHOOGLE_PROXY_PASS (optional)
- WHOOGLE_PROXY_TYPE (required)
- Can be "http", "socks4", or "socks5"
- WHOOGLE_PROXY_LOC (required)
- Format: "<ip address>:<port>"
See #30
* Refactor acquire_tor_conn -> acquire_tor_identity
Also updated travis CI to set up tor
* Add check for Tor socket on init, improve Tor error handling
Initializing the app sends a heartbeat request to Tor to check for
availability, and updates the home page config options accordingly. This
heartbeat is sent on every request, to ensure Tor support can be
reconfigured without restarting the entire app.
If Tor support is enabled, and a subsequent request fails, then a new
TorError exception is raised, and the Tor feature is disabled until a
valid connection is restored.
The max attempts has been updated to 10, since 5 seemed a bit too low
for how quickly the attempts go by.
* Change send_tor_signal arg type, update function doc
send_tor_signal now accepts a stem.Signal arg (a bit cleaner tbh). Also
added the doc string for the "disable" attribute in TorError.
* Fix tor identity logic in Request.send
* Update proxy init, change proxyloc var name
Proxy is now only initialized if both type and location are specified,
as neither have a default fallback and both are required. I suppose the
type could fall back to http, but seems safer this way.
Also refactored proxyurl -> proxyloc for the runtime args in order to
match the Dockerfile args.
* Add tor/proxy support for Docker builds, fix opensearch/init
The Dockerfile is now updated to include support for Tor configuration,
with a working torrc file included in the repo.
An issue with opensearch was fixed as well, which was uncovered during
testing and was simple enough to fix here. Likewise, DDG bang gen was
updated to only ever happen if the file didn't exist previously, as
testing with the file being regenerated every time was tedious.
* Add missing "@" for socks proxy requests
2020-10-29 00:47:42 +00:00
|
|
|
g.user_request = Request(
|
|
|
|
request.headers.get('User-Agent'),
|
2021-11-22 06:21:04 +00:00
|
|
|
get_request_url(request.url_root),
|
Add tor and http/socks proxy support (#137)
* Add tor and http/socks proxy support
Allows users to enable/disable tor from the config menu, which will
forward all requests through Tor.
Also adds support for setting environment variables for alternative
proxy support. Setting the following variables will forward requests
through the proxy:
- WHOOGLE_PROXY_USER (optional)
- WHOOGLE_PROXY_PASS (optional)
- WHOOGLE_PROXY_TYPE (required)
- Can be "http", "socks4", or "socks5"
- WHOOGLE_PROXY_LOC (required)
- Format: "<ip address>:<port>"
See #30
* Refactor acquire_tor_conn -> acquire_tor_identity
Also updated travis CI to set up tor
* Add check for Tor socket on init, improve Tor error handling
Initializing the app sends a heartbeat request to Tor to check for
availability, and updates the home page config options accordingly. This
heartbeat is sent on every request, to ensure Tor support can be
reconfigured without restarting the entire app.
If Tor support is enabled, and a subsequent request fails, then a new
TorError exception is raised, and the Tor feature is disabled until a
valid connection is restored.
The max attempts has been updated to 10, since 5 seemed a bit too low
for how quickly the attempts go by.
* Change send_tor_signal arg type, update function doc
send_tor_signal now accepts a stem.Signal arg (a bit cleaner tbh). Also
added the doc string for the "disable" attribute in TorError.
* Fix tor identity logic in Request.send
* Update proxy init, change proxyloc var name
Proxy is now only initialized if both type and location are specified,
as neither have a default fallback and both are required. I suppose the
type could fall back to http, but seems safer this way.
Also refactored proxyurl -> proxyloc for the runtime args in order to
match the Dockerfile args.
* Add tor/proxy support for Docker builds, fix opensearch/init
The Dockerfile is now updated to include support for Tor configuration,
with a working torrc file included in the repo.
An issue with opensearch was fixed as well, which was uncovered during
testing and was simple enough to fix here. Likewise, DDG bang gen was
updated to only ever happen if the file didn't exist previously, as
testing with the file being regenerated every time was tedious.
* Add missing "@" for socks proxy requests
2020-10-29 00:47:42 +00:00
|
|
|
config=g.user_config)
|
|
|
|
|
2020-05-12 23:15:53 +00:00
|
|
|
g.app_location = g.user_config.url
|
2020-01-22 05:51:02 +00:00
|
|
|
|
2022-01-25 19:28:06 +00:00
|
|
|
# Attempt to reload bangs json if not generated yet
|
|
|
|
if not bang_json and os.path.getsize(app.config['BANG_FILE']) > 4:
|
|
|
|
try:
|
|
|
|
bang_json = json.load(open(app.config['BANG_FILE']))
|
|
|
|
except json.decoder.JSONDecodeError:
|
2022-01-25 19:31:19 +00:00
|
|
|
# Ignore decoding error, can occur if file is still
|
2022-01-25 19:28:06 +00:00
|
|
|
# being written
|
|
|
|
pass
|
|
|
|
|
2020-01-21 20:26:49 +00:00
|
|
|
|
2020-06-02 18:54:47 +00:00
|
|
|
@app.after_request
|
2021-03-07 19:04:05 +00:00
|
|
|
def after_request_func(resp):
|
2021-11-26 15:38:26 +00:00
|
|
|
resp.headers['X-Content-Type-Options'] = 'nosniff'
|
|
|
|
resp.headers['X-Frame-Options'] = 'DENY'
|
2021-11-29 22:49:35 +00:00
|
|
|
|
|
|
|
if os.getenv('WHOOGLE_CSP', False):
|
|
|
|
resp.headers['Content-Security-Policy'] = app.config['CSP']
|
|
|
|
if os.environ.get('HTTPS_ONLY', False):
|
2021-11-29 22:58:19 +00:00
|
|
|
resp.headers['Content-Security-Policy'] += \
|
|
|
|
'upgrade-insecure-requests'
|
2021-03-07 19:04:05 +00:00
|
|
|
|
|
|
|
return resp
|
2020-06-02 18:54:47 +00:00
|
|
|
|
|
|
|
|
2020-05-06 00:28:43 +00:00
|
|
|
@app.errorhandler(404)
|
|
|
|
def unknown_page(e):
|
2020-12-17 21:06:47 +00:00
|
|
|
app.logger.warn(e)
|
2020-05-10 19:27:02 +00:00
|
|
|
return redirect(g.app_location)
|
2020-05-06 00:28:43 +00:00
|
|
|
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
@app.route(f'/{Endpoint.healthz}', methods=['GET'])
|
2021-05-18 15:48:15 +00:00
|
|
|
def healthz():
|
|
|
|
return ''
|
|
|
|
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
@app.route(f'/{Endpoint.session}/<session_id>', methods=['GET', 'PUT', 'POST'])
|
|
|
|
def session_check(session_id):
|
|
|
|
if 'uuid' in session and session['uuid'] == session_id:
|
|
|
|
session['valid'] = True
|
|
|
|
return redirect(request.args.get('follow'), code=307)
|
|
|
|
else:
|
|
|
|
follow_url = request.args.get('follow')
|
|
|
|
req = PreparedRequest()
|
|
|
|
req.prepare_url(follow_url, {'cookies_disabled': 1})
|
|
|
|
session.pop('_permanent', None)
|
|
|
|
return redirect(req.url, code=307)
|
2021-10-14 02:55:26 +00:00
|
|
|
|
|
|
|
|
2020-01-21 20:26:49 +00:00
|
|
|
@app.route('/', methods=['GET'])
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
@app.route(f'/{Endpoint.home}', methods=['GET'])
|
2020-05-18 16:30:32 +00:00
|
|
|
@auth_required
|
2020-01-21 20:26:49 +00:00
|
|
|
def index():
|
2021-03-07 19:04:05 +00:00
|
|
|
# Redirect if an error was raised
|
|
|
|
if 'error_message' in session and session['error_message']:
|
|
|
|
error_message = session['error_message']
|
|
|
|
session['error_message'] = ''
|
|
|
|
return render_template('error.html', error_message=error_message)
|
2020-06-05 21:24:44 +00:00
|
|
|
|
2020-05-12 23:15:53 +00:00
|
|
|
return render_template('index.html',
|
2022-02-14 19:19:02 +00:00
|
|
|
has_update=app.config['HAS_UPDATE'],
|
2020-12-17 21:39:35 +00:00
|
|
|
languages=app.config['LANGUAGES'],
|
|
|
|
countries=app.config['COUNTRIES'],
|
2021-06-28 14:26:51 +00:00
|
|
|
themes=app.config['THEMES'],
|
2022-01-18 20:39:56 +00:00
|
|
|
autocomplete_enabled=autocomplete_enabled,
|
2021-05-24 21:03:02 +00:00
|
|
|
translation=app.config['TRANSLATIONS'][
|
|
|
|
g.user_config.get_localization_lang()
|
|
|
|
],
|
2021-04-05 14:37:39 +00:00
|
|
|
logo=render_template(
|
|
|
|
'logo.html',
|
2021-04-09 15:00:02 +00:00
|
|
|
dark=g.user_config.dark),
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
config_disabled=(
|
2021-11-22 07:26:25 +00:00
|
|
|
app.config['CONFIG_DISABLE'] or
|
|
|
|
not valid_user_session(session) or
|
|
|
|
'cookies_disabled' in request.args),
|
2020-06-02 18:54:47 +00:00
|
|
|
config=g.user_config,
|
Add tor and http/socks proxy support (#137)
* Add tor and http/socks proxy support
Allows users to enable/disable tor from the config menu, which will
forward all requests through Tor.
Also adds support for setting environment variables for alternative
proxy support. Setting the following variables will forward requests
through the proxy:
- WHOOGLE_PROXY_USER (optional)
- WHOOGLE_PROXY_PASS (optional)
- WHOOGLE_PROXY_TYPE (required)
- Can be "http", "socks4", or "socks5"
- WHOOGLE_PROXY_LOC (required)
- Format: "<ip address>:<port>"
See #30
* Refactor acquire_tor_conn -> acquire_tor_identity
Also updated travis CI to set up tor
* Add check for Tor socket on init, improve Tor error handling
Initializing the app sends a heartbeat request to Tor to check for
availability, and updates the home page config options accordingly. This
heartbeat is sent on every request, to ensure Tor support can be
reconfigured without restarting the entire app.
If Tor support is enabled, and a subsequent request fails, then a new
TorError exception is raised, and the Tor feature is disabled until a
valid connection is restored.
The max attempts has been updated to 10, since 5 seemed a bit too low
for how quickly the attempts go by.
* Change send_tor_signal arg type, update function doc
send_tor_signal now accepts a stem.Signal arg (a bit cleaner tbh). Also
added the doc string for the "disable" attribute in TorError.
* Fix tor identity logic in Request.send
* Update proxy init, change proxyloc var name
Proxy is now only initialized if both type and location are specified,
as neither have a default fallback and both are required. I suppose the
type could fall back to http, but seems safer this way.
Also refactored proxyurl -> proxyloc for the runtime args in order to
match the Dockerfile args.
* Add tor/proxy support for Docker builds, fix opensearch/init
The Dockerfile is now updated to include support for Tor configuration,
with a working torrc file included in the repo.
An issue with opensearch was fixed as well, which was uncovered during
testing and was simple enough to fix here. Likewise, DDG bang gen was
updated to only ever happen if the file didn't exist previously, as
testing with the file being regenerated every time was tedious.
* Add missing "@" for socks proxy requests
2020-10-29 00:47:42 +00:00
|
|
|
tor_available=int(os.environ.get('TOR_AVAILABLE')),
|
2020-06-02 18:54:47 +00:00
|
|
|
version_number=app.config['VERSION_NUMBER'])
|
2020-01-21 20:26:49 +00:00
|
|
|
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
@app.route(f'/{Endpoint.opensearch}', methods=['GET'])
|
2020-04-25 00:45:57 +00:00
|
|
|
def opensearch():
|
2020-05-10 19:27:02 +00:00
|
|
|
opensearch_url = g.app_location
|
|
|
|
if opensearch_url.endswith('/'):
|
|
|
|
opensearch_url = opensearch_url[:-1]
|
2020-04-25 00:45:57 +00:00
|
|
|
|
2021-01-23 19:50:30 +00:00
|
|
|
# Enforce https for opensearch template
|
|
|
|
if needs_https(opensearch_url):
|
|
|
|
opensearch_url = opensearch_url.replace('http://', 'https://', 1)
|
|
|
|
|
2020-12-17 21:06:47 +00:00
|
|
|
get_only = g.user_config.get_only or 'Chrome' in request.headers.get(
|
|
|
|
'User-Agent')
|
2020-11-18 15:31:19 +00:00
|
|
|
|
2020-08-15 19:02:17 +00:00
|
|
|
return render_template(
|
|
|
|
'opensearch.xml',
|
|
|
|
main_url=opensearch_url,
|
2020-11-18 15:31:19 +00:00
|
|
|
request_type='' if get_only else 'method="post"'
|
2022-04-07 19:52:17 +00:00
|
|
|
), 200, {'Content-Type': 'application/xml'}
|
2020-04-25 00:45:57 +00:00
|
|
|
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
@app.route(f'/{Endpoint.search_html}', methods=['GET'])
|
2021-05-21 14:35:46 +00:00
|
|
|
def search_html():
|
|
|
|
search_url = g.app_location
|
|
|
|
if search_url.endswith('/'):
|
|
|
|
search_url = search_url[:-1]
|
|
|
|
return render_template('search.html', url=search_url)
|
|
|
|
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
@app.route(f'/{Endpoint.autocomplete}', methods=['GET', 'POST'])
|
2020-05-24 20:03:11 +00:00
|
|
|
def autocomplete():
|
2021-10-15 00:58:13 +00:00
|
|
|
if os.getenv(ac_var) and not read_config_bool(ac_var):
|
|
|
|
return jsonify({})
|
|
|
|
|
2020-06-05 21:24:44 +00:00
|
|
|
q = g.request_params.get('q')
|
2020-10-29 03:02:41 +00:00
|
|
|
if not q:
|
|
|
|
# FF will occasionally (incorrectly) send the q field without a
|
|
|
|
# mimetype in the format "b'q=<query>'" through the request.data field
|
|
|
|
q = str(request.data).replace('q=', '')
|
2020-05-24 20:03:11 +00:00
|
|
|
|
2020-10-10 19:55:14 +00:00
|
|
|
# Search bangs if the query begins with "!", but not "! " (feeling lucky)
|
|
|
|
if q.startswith('!') and len(q) > 1 and not q.startswith('! '):
|
2020-12-17 21:06:47 +00:00
|
|
|
return jsonify([q, [bang_json[_]['suggestion'] for _ in bang_json if
|
|
|
|
_.startswith(q)]])
|
2020-10-10 19:55:14 +00:00
|
|
|
|
2020-05-24 20:03:11 +00:00
|
|
|
if not q and not request.data:
|
|
|
|
return jsonify({'?': []})
|
|
|
|
elif request.data:
|
2020-12-17 21:06:47 +00:00
|
|
|
q = urlparse.unquote_plus(
|
|
|
|
request.data.decode('utf-8').replace('q=', ''))
|
2020-05-24 20:03:11 +00:00
|
|
|
|
Add tor and http/socks proxy support (#137)
* Add tor and http/socks proxy support
Allows users to enable/disable tor from the config menu, which will
forward all requests through Tor.
Also adds support for setting environment variables for alternative
proxy support. Setting the following variables will forward requests
through the proxy:
- WHOOGLE_PROXY_USER (optional)
- WHOOGLE_PROXY_PASS (optional)
- WHOOGLE_PROXY_TYPE (required)
- Can be "http", "socks4", or "socks5"
- WHOOGLE_PROXY_LOC (required)
- Format: "<ip address>:<port>"
See #30
* Refactor acquire_tor_conn -> acquire_tor_identity
Also updated travis CI to set up tor
* Add check for Tor socket on init, improve Tor error handling
Initializing the app sends a heartbeat request to Tor to check for
availability, and updates the home page config options accordingly. This
heartbeat is sent on every request, to ensure Tor support can be
reconfigured without restarting the entire app.
If Tor support is enabled, and a subsequent request fails, then a new
TorError exception is raised, and the Tor feature is disabled until a
valid connection is restored.
The max attempts has been updated to 10, since 5 seemed a bit too low
for how quickly the attempts go by.
* Change send_tor_signal arg type, update function doc
send_tor_signal now accepts a stem.Signal arg (a bit cleaner tbh). Also
added the doc string for the "disable" attribute in TorError.
* Fix tor identity logic in Request.send
* Update proxy init, change proxyloc var name
Proxy is now only initialized if both type and location are specified,
as neither have a default fallback and both are required. I suppose the
type could fall back to http, but seems safer this way.
Also refactored proxyurl -> proxyloc for the runtime args in order to
match the Dockerfile args.
* Add tor/proxy support for Docker builds, fix opensearch/init
The Dockerfile is now updated to include support for Tor configuration,
with a working torrc file included in the repo.
An issue with opensearch was fixed as well, which was uncovered during
testing and was simple enough to fix here. Likewise, DDG bang gen was
updated to only ever happen if the file didn't exist previously, as
testing with the file being regenerated every time was tedious.
* Add missing "@" for socks proxy requests
2020-10-29 00:47:42 +00:00
|
|
|
# Return a list of suggestions for the query
|
2020-12-17 21:06:47 +00:00
|
|
|
#
|
|
|
|
# Note: If Tor is enabled, this returns nothing, as the request is
|
|
|
|
# almost always rejected
|
|
|
|
return jsonify([
|
|
|
|
q,
|
|
|
|
g.user_request.autocomplete(q) if not g.user_config.tor else []
|
|
|
|
])
|
2020-05-24 20:03:11 +00:00
|
|
|
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
@app.route(f'/{Endpoint.search}', methods=['GET', 'POST'])
|
|
|
|
@session_required
|
2020-05-18 16:30:32 +00:00
|
|
|
@auth_required
|
2020-01-21 20:26:49 +00:00
|
|
|
def search():
|
2020-11-11 05:40:49 +00:00
|
|
|
# Update user config if specified in search args
|
|
|
|
g.user_config = g.user_config.from_params(g.request_params)
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
search_util = Search(request, g.user_config, g.session_key)
|
2020-06-02 18:54:47 +00:00
|
|
|
query = search_util.new_search_query()
|
2020-05-18 16:28:23 +00:00
|
|
|
|
2022-04-20 20:50:32 +00:00
|
|
|
bang = resolve_bang(query, bang_json)
|
2022-03-01 19:06:59 +00:00
|
|
|
if bang:
|
2021-03-08 17:22:04 +00:00
|
|
|
return redirect(bang)
|
2020-06-25 22:26:02 +00:00
|
|
|
|
2020-06-02 18:54:47 +00:00
|
|
|
# Redirect to home if invalid/blank search
|
|
|
|
if not query:
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
return redirect(url_for('.index'))
|
2020-05-18 16:28:23 +00:00
|
|
|
|
2020-06-02 18:54:47 +00:00
|
|
|
# Generate response and number of external elements from the page
|
Add tor and http/socks proxy support (#137)
* Add tor and http/socks proxy support
Allows users to enable/disable tor from the config menu, which will
forward all requests through Tor.
Also adds support for setting environment variables for alternative
proxy support. Setting the following variables will forward requests
through the proxy:
- WHOOGLE_PROXY_USER (optional)
- WHOOGLE_PROXY_PASS (optional)
- WHOOGLE_PROXY_TYPE (required)
- Can be "http", "socks4", or "socks5"
- WHOOGLE_PROXY_LOC (required)
- Format: "<ip address>:<port>"
See #30
* Refactor acquire_tor_conn -> acquire_tor_identity
Also updated travis CI to set up tor
* Add check for Tor socket on init, improve Tor error handling
Initializing the app sends a heartbeat request to Tor to check for
availability, and updates the home page config options accordingly. This
heartbeat is sent on every request, to ensure Tor support can be
reconfigured without restarting the entire app.
If Tor support is enabled, and a subsequent request fails, then a new
TorError exception is raised, and the Tor feature is disabled until a
valid connection is restored.
The max attempts has been updated to 10, since 5 seemed a bit too low
for how quickly the attempts go by.
* Change send_tor_signal arg type, update function doc
send_tor_signal now accepts a stem.Signal arg (a bit cleaner tbh). Also
added the doc string for the "disable" attribute in TorError.
* Fix tor identity logic in Request.send
* Update proxy init, change proxyloc var name
Proxy is now only initialized if both type and location are specified,
as neither have a default fallback and both are required. I suppose the
type could fall back to http, but seems safer this way.
Also refactored proxyurl -> proxyloc for the runtime args in order to
match the Dockerfile args.
* Add tor/proxy support for Docker builds, fix opensearch/init
The Dockerfile is now updated to include support for Tor configuration,
with a working torrc file included in the repo.
An issue with opensearch was fixed as well, which was uncovered during
testing and was simple enough to fix here. Likewise, DDG bang gen was
updated to only ever happen if the file didn't exist previously, as
testing with the file being regenerated every time was tedious.
* Add missing "@" for socks proxy requests
2020-10-29 00:47:42 +00:00
|
|
|
try:
|
2021-04-01 04:23:30 +00:00
|
|
|
response = search_util.generate_response()
|
Add tor and http/socks proxy support (#137)
* Add tor and http/socks proxy support
Allows users to enable/disable tor from the config menu, which will
forward all requests through Tor.
Also adds support for setting environment variables for alternative
proxy support. Setting the following variables will forward requests
through the proxy:
- WHOOGLE_PROXY_USER (optional)
- WHOOGLE_PROXY_PASS (optional)
- WHOOGLE_PROXY_TYPE (required)
- Can be "http", "socks4", or "socks5"
- WHOOGLE_PROXY_LOC (required)
- Format: "<ip address>:<port>"
See #30
* Refactor acquire_tor_conn -> acquire_tor_identity
Also updated travis CI to set up tor
* Add check for Tor socket on init, improve Tor error handling
Initializing the app sends a heartbeat request to Tor to check for
availability, and updates the home page config options accordingly. This
heartbeat is sent on every request, to ensure Tor support can be
reconfigured without restarting the entire app.
If Tor support is enabled, and a subsequent request fails, then a new
TorError exception is raised, and the Tor feature is disabled until a
valid connection is restored.
The max attempts has been updated to 10, since 5 seemed a bit too low
for how quickly the attempts go by.
* Change send_tor_signal arg type, update function doc
send_tor_signal now accepts a stem.Signal arg (a bit cleaner tbh). Also
added the doc string for the "disable" attribute in TorError.
* Fix tor identity logic in Request.send
* Update proxy init, change proxyloc var name
Proxy is now only initialized if both type and location are specified,
as neither have a default fallback and both are required. I suppose the
type could fall back to http, but seems safer this way.
Also refactored proxyurl -> proxyloc for the runtime args in order to
match the Dockerfile args.
* Add tor/proxy support for Docker builds, fix opensearch/init
The Dockerfile is now updated to include support for Tor configuration,
with a working torrc file included in the repo.
An issue with opensearch was fixed as well, which was uncovered during
testing and was simple enough to fix here. Likewise, DDG bang gen was
updated to only ever happen if the file didn't exist previously, as
testing with the file being regenerated every time was tedious.
* Add missing "@" for socks proxy requests
2020-10-29 00:47:42 +00:00
|
|
|
except TorError as e:
|
2020-12-17 21:06:47 +00:00
|
|
|
session['error_message'] = e.message + (
|
|
|
|
"\\n\\nTor config is now disabled!" if e.disable else "")
|
|
|
|
session['config']['tor'] = False if e.disable else session['config'][
|
|
|
|
'tor']
|
Add tor and http/socks proxy support (#137)
* Add tor and http/socks proxy support
Allows users to enable/disable tor from the config menu, which will
forward all requests through Tor.
Also adds support for setting environment variables for alternative
proxy support. Setting the following variables will forward requests
through the proxy:
- WHOOGLE_PROXY_USER (optional)
- WHOOGLE_PROXY_PASS (optional)
- WHOOGLE_PROXY_TYPE (required)
- Can be "http", "socks4", or "socks5"
- WHOOGLE_PROXY_LOC (required)
- Format: "<ip address>:<port>"
See #30
* Refactor acquire_tor_conn -> acquire_tor_identity
Also updated travis CI to set up tor
* Add check for Tor socket on init, improve Tor error handling
Initializing the app sends a heartbeat request to Tor to check for
availability, and updates the home page config options accordingly. This
heartbeat is sent on every request, to ensure Tor support can be
reconfigured without restarting the entire app.
If Tor support is enabled, and a subsequent request fails, then a new
TorError exception is raised, and the Tor feature is disabled until a
valid connection is restored.
The max attempts has been updated to 10, since 5 seemed a bit too low
for how quickly the attempts go by.
* Change send_tor_signal arg type, update function doc
send_tor_signal now accepts a stem.Signal arg (a bit cleaner tbh). Also
added the doc string for the "disable" attribute in TorError.
* Fix tor identity logic in Request.send
* Update proxy init, change proxyloc var name
Proxy is now only initialized if both type and location are specified,
as neither have a default fallback and both are required. I suppose the
type could fall back to http, but seems safer this way.
Also refactored proxyurl -> proxyloc for the runtime args in order to
match the Dockerfile args.
* Add tor/proxy support for Docker builds, fix opensearch/init
The Dockerfile is now updated to include support for Tor configuration,
with a working torrc file included in the repo.
An issue with opensearch was fixed as well, which was uncovered during
testing and was simple enough to fix here. Likewise, DDG bang gen was
updated to only ever happen if the file didn't exist previously, as
testing with the file being regenerated every time was tedious.
* Add missing "@" for socks proxy requests
2020-10-29 00:47:42 +00:00
|
|
|
return redirect(url_for('.index'))
|
|
|
|
|
2021-04-01 04:23:30 +00:00
|
|
|
if search_util.feeling_lucky:
|
2020-06-02 18:54:47 +00:00
|
|
|
return redirect(response, code=303)
|
2020-05-18 16:28:23 +00:00
|
|
|
|
2021-06-15 14:14:42 +00:00
|
|
|
# If the user is attempting to translate a string, determine the correct
|
|
|
|
# string for formatting the lingva.ml url
|
|
|
|
localization_lang = g.user_config.get_localization_lang()
|
|
|
|
translation = app.config['TRANSLATIONS'][localization_lang]
|
|
|
|
translate_to = localization_lang.replace('lang_', '')
|
|
|
|
|
2021-03-21 01:51:24 +00:00
|
|
|
# Return 503 if temporarily blocked by captcha
|
Use farside.link for frontend alternatives in results (#560)
* Integrate Farside into Whoogle
When instances are ratelimited (when a captcha is returned instead of
the user's search results) the user can now hop to a new instance via
Farside, a new backend service that redirects users to working instances
of a particular frontend. In this case, it presents a user with a
Farside link to a new Whoogle (or Searx) instance instead, so that the
user can resume their search.
For the generated Farside->Whoogle link, the generated link includes the
user's current Whoogle configuration settings as URL params, to ensure a
more seamless transition between instances. This doesn't translate to
the Farside->Searx link, but potentially could with some changes.
* Expand conversion of config<->url params
Config settings can now be translated to and from URL params using a
predetermined set of "safe" keys (i.e. config settings that easily
translate to URL params).
* Allow jumping instances via Farside when ratelimited
When instances are ratelimited (when a captcha is returned instead of
the user's search results) the user can now hop to a new instance via
Farside, a new backend service that redirects users to working instances
of a particular frontend. In this case, it presents a user with a
Farside link to a new Whoogle (or Searx) instance instead, so that the
user can resume their search.
For the generated Farside->Whoogle link, the generated link includes the
user's current Whoogle configuration settings as URL params, to ensure a
more seamless transition between instances. This doesn't translate to
the Farside->Searx link, but potentially could with some changes.
Closes #554
Closes #559
2021-12-09 00:27:33 +00:00
|
|
|
if has_captcha(str(response)):
|
|
|
|
return render_template(
|
|
|
|
'error.html',
|
|
|
|
blocked=True,
|
|
|
|
error_message=translation['ratelimit'],
|
|
|
|
translation=translation,
|
|
|
|
farside='https://farside.link',
|
|
|
|
config=g.user_config,
|
|
|
|
query=urlparse.unquote(query),
|
|
|
|
params=g.user_config.to_params()), 503
|
2021-10-26 20:59:23 +00:00
|
|
|
response = bold_search_terms(response, query)
|
2021-10-29 03:21:21 +00:00
|
|
|
|
2021-10-21 16:42:31 +00:00
|
|
|
# Feature to display IP address
|
|
|
|
if search_util.check_kw_ip():
|
2021-10-29 03:21:21 +00:00
|
|
|
html_soup = bsoup(str(response), 'html.parser')
|
2021-10-29 03:31:24 +00:00
|
|
|
response = add_ip_card(html_soup, get_client_ip(request))
|
2021-10-21 16:42:31 +00:00
|
|
|
|
2022-02-07 17:47:25 +00:00
|
|
|
# Update tabs content
|
|
|
|
tabs = get_tabs_content(app.config['HEADER_TABS'],
|
|
|
|
search_util.full_query,
|
|
|
|
search_util.search_type,
|
|
|
|
translation)
|
|
|
|
|
2021-12-07 05:56:13 +00:00
|
|
|
# Feature to display currency_card
|
|
|
|
conversion = check_currency(str(response))
|
|
|
|
if conversion:
|
|
|
|
html_soup = bsoup(str(response), 'html.parser')
|
|
|
|
response = add_currency_card(html_soup, conversion)
|
|
|
|
|
2020-05-24 20:03:11 +00:00
|
|
|
return render_template(
|
|
|
|
'display.html',
|
2022-02-14 19:19:02 +00:00
|
|
|
has_update=app.config['HAS_UPDATE'],
|
2020-06-02 18:54:47 +00:00
|
|
|
query=urlparse.unquote(query),
|
|
|
|
search_type=search_util.search_type,
|
2021-03-21 01:21:41 +00:00
|
|
|
config=g.user_config,
|
2022-01-18 20:39:56 +00:00
|
|
|
autocomplete_enabled=autocomplete_enabled,
|
2021-06-15 14:14:42 +00:00
|
|
|
lingva_url=app.config['TRANSLATE_URL'],
|
|
|
|
translation=translation,
|
|
|
|
translate_to=translate_to,
|
|
|
|
translate_str=query.replace(
|
|
|
|
'translate', ''
|
|
|
|
).replace(
|
|
|
|
translation['translate'], ''
|
|
|
|
),
|
|
|
|
is_translation=any(
|
|
|
|
_ in query.lower() for _ in [translation['translate'], 'translate']
|
|
|
|
) and not search_util.search_type, # Standard search queries only
|
2021-11-01 21:34:59 +00:00
|
|
|
response=response,
|
2020-06-11 19:25:23 +00:00
|
|
|
version_number=app.config['VERSION_NUMBER'],
|
2022-02-07 17:47:25 +00:00
|
|
|
search_header=render_template(
|
2020-05-24 20:03:11 +00:00
|
|
|
'header.html',
|
2021-03-21 01:21:41 +00:00
|
|
|
config=g.user_config,
|
2021-04-09 15:00:02 +00:00
|
|
|
logo=render_template('logo.html', dark=g.user_config.dark),
|
2021-06-04 15:09:30 +00:00
|
|
|
query=urlparse.unquote(query),
|
2020-06-02 18:54:47 +00:00
|
|
|
search_type=search_util.search_type,
|
2022-02-07 17:47:25 +00:00
|
|
|
mobile=g.user_request.mobile,
|
|
|
|
tabs=tabs))
|
2020-01-21 20:26:49 +00:00
|
|
|
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
@app.route(f'/{Endpoint.config}', methods=['GET', 'POST', 'PUT'])
|
|
|
|
@session_required
|
2020-05-18 16:30:32 +00:00
|
|
|
@auth_required
|
2020-04-05 23:59:50 +00:00
|
|
|
def config():
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
config_disabled = (
|
|
|
|
app.config['CONFIG_DISABLE'] or
|
|
|
|
not valid_user_session(session))
|
2020-04-15 23:41:53 +00:00
|
|
|
if request.method == 'GET':
|
2020-05-12 23:15:53 +00:00
|
|
|
return json.dumps(g.user_config.__dict__)
|
2021-04-27 14:36:03 +00:00
|
|
|
elif request.method == 'PUT' and not config_disabled:
|
2020-06-02 18:54:47 +00:00
|
|
|
if 'name' in request.args:
|
2020-12-17 21:06:47 +00:00
|
|
|
config_pkl = os.path.join(
|
|
|
|
app.config['CONFIG_PATH'],
|
|
|
|
request.args.get('name'))
|
|
|
|
session['config'] = (pickle.load(open(config_pkl, 'rb'))
|
|
|
|
if os.path.exists(config_pkl)
|
|
|
|
else session['config'])
|
2020-06-02 18:54:47 +00:00
|
|
|
return json.dumps(session['config'])
|
|
|
|
else:
|
|
|
|
return json.dumps({})
|
2021-04-27 14:36:03 +00:00
|
|
|
elif not config_disabled:
|
2020-04-29 02:50:12 +00:00
|
|
|
config_data = request.form.to_dict()
|
2020-05-10 19:27:02 +00:00
|
|
|
if 'url' not in config_data or not config_data['url']:
|
2020-05-15 22:29:22 +00:00
|
|
|
config_data['url'] = g.user_config.url
|
2020-05-10 19:27:02 +00:00
|
|
|
|
2020-06-05 21:24:44 +00:00
|
|
|
# Save config by name to allow a user to easily load later
|
2020-06-02 18:54:47 +00:00
|
|
|
if 'name' in request.args:
|
2020-12-17 21:06:47 +00:00
|
|
|
pickle.dump(
|
|
|
|
config_data,
|
|
|
|
open(os.path.join(
|
|
|
|
app.config['CONFIG_PATH'],
|
|
|
|
request.args.get('name')), 'wb'))
|
2020-06-05 21:24:44 +00:00
|
|
|
|
2020-06-02 18:54:47 +00:00
|
|
|
session['config'] = config_data
|
2020-05-10 19:27:02 +00:00
|
|
|
return redirect(config_data['url'])
|
2021-04-27 14:36:03 +00:00
|
|
|
else:
|
|
|
|
return redirect(url_for('.index'), code=403)
|
2020-04-05 23:59:50 +00:00
|
|
|
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
@app.route(f'/{Endpoint.imgres}')
|
|
|
|
@session_required
|
2020-05-18 16:30:32 +00:00
|
|
|
@auth_required
|
2020-01-23 06:19:17 +00:00
|
|
|
def imgres():
|
|
|
|
return redirect(request.args.get('imgurl'))
|
|
|
|
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
@app.route(f'/{Endpoint.element}')
|
|
|
|
@session_required
|
2020-05-18 16:30:32 +00:00
|
|
|
@auth_required
|
2020-06-02 18:54:47 +00:00
|
|
|
def element():
|
2022-04-13 17:29:07 +00:00
|
|
|
element_url = src_url = request.args.get('url')
|
|
|
|
if element_url.startswith('gAAAAA'):
|
2022-04-18 19:06:44 +00:00
|
|
|
try:
|
|
|
|
cipher_suite = Fernet(g.session_key)
|
|
|
|
src_url = cipher_suite.decrypt(element_url.encode()).decode()
|
|
|
|
except (InvalidSignature, InvalidToken) as e:
|
|
|
|
return render_template(
|
|
|
|
'error.html',
|
|
|
|
error_message=str(e)), 401
|
2022-04-13 17:29:07 +00:00
|
|
|
|
2020-06-02 18:54:47 +00:00
|
|
|
src_type = request.args.get('type')
|
2020-05-23 20:27:23 +00:00
|
|
|
|
|
|
|
try:
|
2020-06-02 18:54:47 +00:00
|
|
|
file_data = g.user_request.send(base_url=src_url).content
|
2020-05-23 20:27:23 +00:00
|
|
|
tmp_mem = io.BytesIO()
|
|
|
|
tmp_mem.write(file_data)
|
|
|
|
tmp_mem.seek(0)
|
|
|
|
|
2020-06-02 18:54:47 +00:00
|
|
|
return send_file(tmp_mem, mimetype=src_type)
|
|
|
|
except exceptions.RequestException:
|
2020-05-23 20:27:23 +00:00
|
|
|
pass
|
|
|
|
|
2020-12-17 21:06:47 +00:00
|
|
|
empty_gif = base64.b64decode(
|
|
|
|
'R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==')
|
2020-05-23 20:27:23 +00:00
|
|
|
return send_file(io.BytesIO(empty_gif), mimetype='image/gif')
|
2020-04-28 02:21:36 +00:00
|
|
|
|
|
|
|
|
Improve public instance session management (#480)
This introduces a new approach to handling user sessions, which should
allow for users to set more reliable config settings on public instances.
Previously, when a user with cookies disabled would update their config,
this would modify the app's default config file, which would in turn
cause new users to inherit these settings when visiting the app for the
first time and cause users to inherit these settings when their current
session cookie expired (which was after 30 days by default I believe).
There was also some half-baked logic for determining on the backend
whether or not a user had cookies disabled, which lead to some issues
with out of control session file creation by Flask.
Now, when a user visits the site, their initial request is forwarded to
a session/<session id> endpoint, and during that subsequent request
their current session id is matched against the one found in the url. If
the ids match, the user has cookies enabled. If not, their original
request is modified with a 'cookies_disabled' query param that tells
Flask not to bother trying to set up a new session for that user, and
instead just use the app's fallback Fernet key for encryption and the
default config.
Since attempting to create a session for a user with cookies disabled
creates a new session file, there is now also a clean-up routine included
in the new session decorator, which will remove all sessions that don't
include a valid key in the dict. NOTE!!! This means that current user
sessions on public instances will be cleared once this update is merged
in. In the long run that's a good thing though, since this will allow session
mgmt to be a lot more reliable overall for users regardless of their cookie
preference.
Individual user sessions still use a unique Fernet key for encrypting queries,
but users with cookies disabled will use the default app key for encryption
and decryption.
Sessions are also now (semi)permanent and have a lifetime of 1 year.
2021-11-18 02:35:30 +00:00
|
|
|
@app.route(f'/{Endpoint.window}')
|
2022-04-13 17:29:07 +00:00
|
|
|
@session_required
|
2020-05-18 16:30:32 +00:00
|
|
|
@auth_required
|
2020-02-21 23:52:29 +00:00
|
|
|
def window():
|
2022-04-13 17:29:07 +00:00
|
|
|
target_url = request.args.get('location')
|
|
|
|
if target_url.startswith('gAAAAA'):
|
|
|
|
cipher_suite = Fernet(g.session_key)
|
|
|
|
target_url = cipher_suite.decrypt(target_url.encode()).decode()
|
|
|
|
|
|
|
|
content_filter = Filter(
|
|
|
|
g.session_key,
|
|
|
|
root_url=request.url_root,
|
|
|
|
config=g.user_config)
|
|
|
|
target = urlparse.urlparse(target_url)
|
|
|
|
host_url = f'{target.scheme}://{target.netloc}'
|
|
|
|
|
|
|
|
get_body = g.user_request.send(base_url=target_url).text
|
2020-02-21 23:52:29 +00:00
|
|
|
|
2020-12-17 21:06:47 +00:00
|
|
|
results = bsoup(get_body, 'html.parser')
|
2022-04-13 17:29:07 +00:00
|
|
|
src_attrs = ['src', 'href', 'srcset', 'data-srcset', 'data-src']
|
|
|
|
|
|
|
|
# Parse HTML response and replace relative links w/ absolute
|
|
|
|
for element in results.find_all():
|
|
|
|
for attr in src_attrs:
|
|
|
|
if not element.has_attr(attr) or not element[attr].startswith('/'):
|
|
|
|
continue
|
|
|
|
|
|
|
|
element[attr] = host_url + element[attr]
|
|
|
|
|
|
|
|
# Replace or remove javascript sources
|
|
|
|
for script in results.find_all('script', {'src': True}):
|
|
|
|
if 'nojs' in request.args:
|
|
|
|
script.decompose()
|
|
|
|
else:
|
|
|
|
content_filter.update_element_src(script, 'application/javascript')
|
|
|
|
|
|
|
|
# Replace all possible image attributes
|
|
|
|
img_sources = ['src', 'data-src', 'data-srcset', 'srcset']
|
|
|
|
for img in results.find_all('img'):
|
|
|
|
_ = [
|
|
|
|
content_filter.update_element_src(img, 'image/png', attr=_)
|
|
|
|
for _ in img_sources if img.has_attr(_)
|
|
|
|
]
|
|
|
|
|
|
|
|
# Replace all stylesheet sources
|
|
|
|
for link in results.find_all('link', {'href': True}):
|
|
|
|
content_filter.update_element_src(link, 'text/css', attr='href')
|
|
|
|
|
|
|
|
# Use anonymous view for all links on page
|
|
|
|
for a in results.find_all('a', {'href': True}):
|
2022-05-10 22:06:57 +00:00
|
|
|
a['href'] = f'{Endpoint.window}?location=' + a['href'] + (
|
2022-04-13 17:29:07 +00:00
|
|
|
'&nojs=1' if 'nojs' in request.args else '')
|
2020-02-21 23:52:29 +00:00
|
|
|
|
2022-04-13 17:29:07 +00:00
|
|
|
# Remove all iframes -- these are commonly used inside of <noscript> tags
|
|
|
|
# to enforce loading Google Analytics
|
|
|
|
for iframe in results.find_all('iframe'):
|
|
|
|
iframe.decompose()
|
2020-02-21 23:52:29 +00:00
|
|
|
|
2021-10-29 03:06:52 +00:00
|
|
|
return render_template(
|
|
|
|
'display.html',
|
|
|
|
response=results,
|
|
|
|
translation=app.config['TRANSLATIONS'][
|
|
|
|
g.user_config.get_localization_lang()
|
|
|
|
]
|
|
|
|
)
|
2020-02-21 23:52:29 +00:00
|
|
|
|
|
|
|
|
2021-03-24 19:13:52 +00:00
|
|
|
def run_app() -> None:
|
2020-12-17 21:06:47 +00:00
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
description='Whoogle Search console runner')
|
|
|
|
parser.add_argument(
|
|
|
|
'--port',
|
|
|
|
default=5000,
|
|
|
|
metavar='<port number>',
|
|
|
|
help='Specifies a port to run on (default 5000)')
|
|
|
|
parser.add_argument(
|
|
|
|
'--host',
|
|
|
|
default='127.0.0.1',
|
|
|
|
metavar='<ip address>',
|
|
|
|
help='Specifies the host address to use (default 127.0.0.1)')
|
2022-04-06 20:11:52 +00:00
|
|
|
parser.add_argument(
|
|
|
|
'--unix-socket',
|
|
|
|
default='',
|
|
|
|
metavar='</path/to/unix.sock>',
|
|
|
|
help='Listen for app on unix socket instead of host:port')
|
2020-12-17 21:06:47 +00:00
|
|
|
parser.add_argument(
|
|
|
|
'--debug',
|
|
|
|
default=False,
|
|
|
|
action='store_true',
|
|
|
|
help='Activates debug mode for the server (default False)')
|
|
|
|
parser.add_argument(
|
|
|
|
'--https-only',
|
|
|
|
default=False,
|
|
|
|
action='store_true',
|
|
|
|
help='Enforces HTTPS redirects for all requests')
|
|
|
|
parser.add_argument(
|
|
|
|
'--userpass',
|
|
|
|
default='',
|
|
|
|
metavar='<username:password>',
|
|
|
|
help='Sets a username/password basic auth combo (default None)')
|
|
|
|
parser.add_argument(
|
|
|
|
'--proxyauth',
|
|
|
|
default='',
|
|
|
|
metavar='<username:password>',
|
|
|
|
help='Sets a username/password for a HTTP/SOCKS proxy (default None)')
|
|
|
|
parser.add_argument(
|
|
|
|
'--proxytype',
|
|
|
|
default='',
|
|
|
|
metavar='<socks4|socks5|http>',
|
|
|
|
help='Sets a proxy type for all connections (default None)')
|
|
|
|
parser.add_argument(
|
|
|
|
'--proxyloc',
|
|
|
|
default='',
|
|
|
|
metavar='<location:port>',
|
|
|
|
help='Sets a proxy location for all connections (default None)')
|
2020-05-07 00:13:02 +00:00
|
|
|
args = parser.parse_args()
|
2020-05-18 16:30:32 +00:00
|
|
|
|
|
|
|
if args.userpass:
|
|
|
|
user_pass = args.userpass.split(':')
|
|
|
|
os.environ['WHOOGLE_USER'] = user_pass[0]
|
|
|
|
os.environ['WHOOGLE_PASS'] = user_pass[1]
|
|
|
|
|
Add tor and http/socks proxy support (#137)
* Add tor and http/socks proxy support
Allows users to enable/disable tor from the config menu, which will
forward all requests through Tor.
Also adds support for setting environment variables for alternative
proxy support. Setting the following variables will forward requests
through the proxy:
- WHOOGLE_PROXY_USER (optional)
- WHOOGLE_PROXY_PASS (optional)
- WHOOGLE_PROXY_TYPE (required)
- Can be "http", "socks4", or "socks5"
- WHOOGLE_PROXY_LOC (required)
- Format: "<ip address>:<port>"
See #30
* Refactor acquire_tor_conn -> acquire_tor_identity
Also updated travis CI to set up tor
* Add check for Tor socket on init, improve Tor error handling
Initializing the app sends a heartbeat request to Tor to check for
availability, and updates the home page config options accordingly. This
heartbeat is sent on every request, to ensure Tor support can be
reconfigured without restarting the entire app.
If Tor support is enabled, and a subsequent request fails, then a new
TorError exception is raised, and the Tor feature is disabled until a
valid connection is restored.
The max attempts has been updated to 10, since 5 seemed a bit too low
for how quickly the attempts go by.
* Change send_tor_signal arg type, update function doc
send_tor_signal now accepts a stem.Signal arg (a bit cleaner tbh). Also
added the doc string for the "disable" attribute in TorError.
* Fix tor identity logic in Request.send
* Update proxy init, change proxyloc var name
Proxy is now only initialized if both type and location are specified,
as neither have a default fallback and both are required. I suppose the
type could fall back to http, but seems safer this way.
Also refactored proxyurl -> proxyloc for the runtime args in order to
match the Dockerfile args.
* Add tor/proxy support for Docker builds, fix opensearch/init
The Dockerfile is now updated to include support for Tor configuration,
with a working torrc file included in the repo.
An issue with opensearch was fixed as well, which was uncovered during
testing and was simple enough to fix here. Likewise, DDG bang gen was
updated to only ever happen if the file didn't exist previously, as
testing with the file being regenerated every time was tedious.
* Add missing "@" for socks proxy requests
2020-10-29 00:47:42 +00:00
|
|
|
if args.proxytype and args.proxyloc:
|
|
|
|
if args.proxyauth:
|
|
|
|
proxy_user_pass = args.proxyauth.split(':')
|
|
|
|
os.environ['WHOOGLE_PROXY_USER'] = proxy_user_pass[0]
|
|
|
|
os.environ['WHOOGLE_PROXY_PASS'] = proxy_user_pass[1]
|
|
|
|
os.environ['WHOOGLE_PROXY_TYPE'] = args.proxytype
|
|
|
|
os.environ['WHOOGLE_PROXY_LOC'] = args.proxyloc
|
|
|
|
|
2021-11-20 23:34:37 +00:00
|
|
|
if args.https_only:
|
|
|
|
os.environ['HTTPS_ONLY'] = '1'
|
2020-05-15 21:44:50 +00:00
|
|
|
|
2020-05-12 23:14:55 +00:00
|
|
|
if args.debug:
|
|
|
|
app.run(host=args.host, port=args.port, debug=args.debug)
|
2022-04-06 20:11:52 +00:00
|
|
|
elif args.unix_socket:
|
|
|
|
waitress.serve(app, unix_socket=args.unix_socket)
|
2020-05-12 23:14:55 +00:00
|
|
|
else:
|
2022-04-18 21:27:45 +00:00
|
|
|
waitress.serve(
|
|
|
|
app,
|
|
|
|
listen="{}:{}".format(args.host, args.port),
|
|
|
|
url_prefix=os.environ.get('WHOOGLE_URL_PREFIX', ''))
|