mirror of
https://github.com/Gimanh/taskview-community.git
synced 2026-09-12 05:49:01 +00:00
Compare commits
28 Commits
v1.51.0
...
fix/issues
| Author | SHA1 | Date | |
|---|---|---|---|
| 5976a03ce0 | |||
| 3403e1a71d | |||
| e9fb4f6f1e | |||
| a173a870d7 | |||
| 171f269ee2 | |||
| f79614ebc5 | |||
| a4c465469d | |||
| f3e2663ebe | |||
| 5ce2fe99f0 | |||
| e11aba4d79 | |||
| 0b6f95ec3d | |||
| a596e023db | |||
| c1685e42b8 | |||
| 9635120e66 | |||
| 19e0212edf | |||
| 5dc5b387de | |||
| 8011da1259 | |||
| a6329e998d | |||
| b372854636 | |||
| a243f9ec56 | |||
| ebd25a94ea | |||
| 4b142619c0 | |||
| 6f576e7297 | |||
| 15050541fa | |||
| 3afdca99d9 | |||
| aaa876412d | |||
| 915e8d9f9f | |||
| 55ded8bac9 |
@@ -428,7 +428,7 @@ For commercial licensing questions, hosted service permissions, or other use cas
|
||||
|
||||
Do not publish security vulnerabilities in public GitHub issues.
|
||||
|
||||
Report security issues privately using the contact information provided in the repository or on the TaskView website.
|
||||
Report security issues privately — see [SECURITY.md](SECURITY.md) for the reporting channels, response times, scope, and safe-harbor terms.
|
||||
|
||||
When running TaskView in production:
|
||||
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
# Security Policy
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.
|
||||
|
||||
Report them privately using one of these channels:
|
||||
|
||||
- **GitHub private vulnerability reporting** (preferred): open the **Security** tab of this repository and click **Report a vulnerability**.
|
||||
- **Email**: [support@taskview.tech](mailto:support@taskview.tech) with `[security]` in the subject.
|
||||
|
||||
Please include as much of the following as you can:
|
||||
|
||||
- A description of the issue and its impact
|
||||
- Affected component (API, web app, MCP server, mobile app) and version
|
||||
- Steps to reproduce, or a proof of concept
|
||||
- Any suggested mitigation
|
||||
|
||||
## What to expect
|
||||
|
||||
- We will acknowledge your report within **5 business days**.
|
||||
- We will keep you informed about progress and aim to release a fix for confirmed issues within **90 days** of the report, sooner for critical issues.
|
||||
- Once a fix is released, we publish a GitHub Security Advisory for the affected versions and credit the reporter, unless they prefer to stay anonymous.
|
||||
- We ask that you give us a reasonable time to fix the issue before disclosing it publicly.
|
||||
|
||||
## Supported versions
|
||||
|
||||
Security fixes are released for the latest minor version line only. Self-hosted installations should upgrade to the latest release to receive them.
|
||||
|
||||
## Scope
|
||||
|
||||
In scope:
|
||||
|
||||
- The TaskView API server, web app, MCP server, and mobile app in this repository
|
||||
- The hosted service at `app.taskview.tech`
|
||||
|
||||
Out of scope:
|
||||
|
||||
- Vulnerabilities in third-party dependencies that are not exploitable in TaskView (report them upstream)
|
||||
- Findings that require a compromised admin account or physical access to the server
|
||||
- Missing security headers, rate limiting, or best-practice recommendations without a demonstrated impact
|
||||
- Denial-of-service testing against the hosted service
|
||||
|
||||
## Safe harbor
|
||||
|
||||
We will not pursue legal action against researchers who act in good faith: test only against their own self-hosted instance or their own accounts on the hosted service, avoid accessing or modifying other users' data, and report findings privately as described above.
|
||||
@@ -19,6 +19,18 @@ ACCESS_LIFE_TIME=1d
|
||||
REFRESH_LIFE_TIME=2d
|
||||
JWT_ALG=HS256
|
||||
|
||||
# SSO: comma-separated email domains that skip DNS/HTTP ownership proof (air-gapped installs)
|
||||
#SSO_TRUSTED_DOMAINS=company.com,corp.local
|
||||
|
||||
# OAuth 2.1 for third-party MCP clients (ChatGPT, Claude connectors).
|
||||
# Dynamic Client Registration is on by default; a cloud client cannot connect
|
||||
# without it, since it has no way to pre-register with your instance. Turn it
|
||||
# off on a private install that only uses manually seeded clients.
|
||||
#OAUTH_DYNAMIC_REGISTRATION=false
|
||||
# Public URL of this API. Used as the OAuth issuer in the discovery documents,
|
||||
# so it must be the URL clients actually reach — set it behind a proxy.
|
||||
#API_PUBLIC_URL=https://api.taskview.tech
|
||||
|
||||
# SMTP Configuration
|
||||
SMTP_HOST=smtp.domain.com
|
||||
SMTP_PORT=465
|
||||
|
||||
+3
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "taskview-ce-api-server",
|
||||
"version": "1.51.0",
|
||||
"version": "1.53.0",
|
||||
"scripts": {
|
||||
"dev": "bun run --watch ./server.ts",
|
||||
"start": "NODE_ENV=production node ./dist/taskview-server.js",
|
||||
@@ -27,6 +27,7 @@
|
||||
"@types/luxon": "^3.7.1",
|
||||
"@types/node": "^22.10.3",
|
||||
"@types/passport-apple": "^2.0.3",
|
||||
"@types/pdfmake": "^0.3.3",
|
||||
"@types/pg": "^8.15.5",
|
||||
"@types/semver": "^7.5.8",
|
||||
"@types/ua-parser-js": "^0.7.39",
|
||||
@@ -68,6 +69,7 @@
|
||||
"passport-apple": "^2.0.2",
|
||||
"passport-github2": "^0.1.12",
|
||||
"passport-google-oauth20": "^2.0.0",
|
||||
"pdfmake": "^0.3.11",
|
||||
"pg": "^8.16.3",
|
||||
"pg-boss": "^12.14.0",
|
||||
"pino": "^9.4.0",
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import type { Request, Response } from 'express';
|
||||
import { RequireTokenPermission } from '../require-token-permission';
|
||||
import { GoalPermissions } from '../../types/auth.types';
|
||||
|
||||
const runWith = (tokenPermissions: string[] | undefined) => {
|
||||
const next = vi.fn();
|
||||
const end = vi.fn();
|
||||
const res = { status: vi.fn(() => ({ end })), end } as unknown as Response;
|
||||
const req = { appUser: { getTokenPermissions: () => tokenPermissions } } as unknown as Request;
|
||||
|
||||
RequireTokenPermission(GoalPermissions.ORG_CAN_MANAGE)(req, res, next);
|
||||
return { next, res };
|
||||
};
|
||||
|
||||
describe('RequireTokenPermission', () => {
|
||||
it('lets a browser session through — it carries no token permissions', () => {
|
||||
const { next, res } = runWith(undefined);
|
||||
expect(next).toHaveBeenCalled();
|
||||
expect(res.status).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lets an unrestricted token through, keeping existing integrations working', () => {
|
||||
const { next } = runWith([]);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lets a token holding the permission through', () => {
|
||||
const { next } = runWith([GoalPermissions.ORG_CAN_MANAGE]);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('blocks a restricted token that was not given the permission', () => {
|
||||
const { next, res } = runWith([GoalPermissions.TIMETRACKING_CAN_VIEW]);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res.status).toHaveBeenCalledWith(403);
|
||||
});
|
||||
|
||||
it('does not accept a neighbouring permission from the same group', () => {
|
||||
const { next, res } = runWith([GoalPermissions.ORG_CAN_MANAGE_MEMBERS]);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res.status).toHaveBeenCalledWith(403);
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import { $logger } from '../modules/logget';
|
||||
import AuthController from '../tv-modules/auth/AuthController';
|
||||
import { getApiTokensManager } from '../tv-modules/api-tokens/ApiTokensManager';
|
||||
import { TOKEN_PREFIX } from '../tv-modules/api-tokens/types';
|
||||
import { OAUTH_ACCESS_TOKEN_PREFIX } from '../tv-modules/oauth/types';
|
||||
|
||||
export const appUserMiddleware = async (req: Request, res: Response, next: NextFunction) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
@@ -13,7 +14,7 @@ export const appUserMiddleware = async (req: Request, res: Response, next: NextF
|
||||
|
||||
const token = req.headers['authorization']?.split(' ')[1];
|
||||
|
||||
if (token && token.startsWith(TOKEN_PREFIX)) {
|
||||
if (token && (token.startsWith(TOKEN_PREFIX) || token.startsWith(OAUTH_ACCESS_TOKEN_PREFIX))) {
|
||||
const record = await getApiTokensManager().validateToken(token);
|
||||
if (record) {
|
||||
const authManager = new AppUser().authManager;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import type { GoalPermissionType } from '../types/auth.types';
|
||||
|
||||
/**
|
||||
* Narrows what a restricted API / OAuth token may do on surfaces that are guarded
|
||||
* by an organization role or by project ownership rather than by the project RBAC
|
||||
* — organizations, SSO configuration, webhooks. Those checks never consult
|
||||
* GoalPermissionsFetcher, so without this the scope chosen when the token was
|
||||
* issued would simply not apply to them.
|
||||
*
|
||||
* It only ever removes access. Put it AFTER the role or ownership guard, so that
|
||||
* guard still has the final say on what the human behind the token may do:
|
||||
*
|
||||
* [IsLoggedIn, IsOrgAdmin, RequireTokenPermission(GoalPermissions.ORG_CAN_MANAGE)]
|
||||
*
|
||||
* A browser session has no token permissions and passes. A token issued with an
|
||||
* empty permission list is unrestricted by design — the same meaning it carries
|
||||
* everywhere else — and also passes, which keeps existing integrations working.
|
||||
*/
|
||||
export const RequireTokenPermission = (permission: GoalPermissionType) => {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
const tokenPermissions = req.appUser.getTokenPermissions();
|
||||
|
||||
if (!tokenPermissions || tokenPermissions.length === 0) {
|
||||
return next();
|
||||
}
|
||||
|
||||
if (tokenPermissions.includes(permission)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
};
|
||||
@@ -737,5 +737,68 @@
|
||||
"description": [
|
||||
"Log of sent project-invite emails (collaboration.invite_emails) backing the per-recipient cooldown and the hourly per-initiator sending cap"
|
||||
]
|
||||
},
|
||||
"58": {
|
||||
"version": "1.63.0",
|
||||
"name": "SSO domain verification",
|
||||
"releaseDate": "20260813",
|
||||
"scripts": [
|
||||
"/1.63.0/0.sso-domain-verification.sql",
|
||||
"/1.63.0/1.sso-domain-verified-unique.sql"
|
||||
],
|
||||
"description": [
|
||||
"SSO configs require proving ownership of email_domain_restriction before login is allowed: DNS TXT taskview-sso-verify=<token> or https://<domain>/.well-known/taskview-sso-verify.txt. Air-gapped installs can skip this for listed domains via SSO_TRUSTED_DOMAINS.",
|
||||
"Replaces the plain UNIQUE(email_domain_restriction) with a partial unique index over verified configs only, so an unverified config can no longer squat a domain and block its real owner — multiple orgs may hold a pending config for the same domain, but only one can verify it (first-to-verify wins)."
|
||||
]
|
||||
},
|
||||
"59": {
|
||||
"version": "1.64.0",
|
||||
"name": "OAuth 2.1 authorization server",
|
||||
"releaseDate": "20260830",
|
||||
"scripts": [
|
||||
"/1.64.0/0.create-oauth-clients.sql",
|
||||
"/1.64.0/1.create-oauth-auth-codes.sql",
|
||||
"/1.64.0/2.create-oauth-grants.sql",
|
||||
"/1.64.0/3.alter-api-tokens-grant-id.sql"
|
||||
],
|
||||
"description": [
|
||||
"OAuth 2.1 authorization server so third-party MCP clients (ChatGPT, Claude connectors) can act on a user's behalf without the user pasting a permanent tvk_ API token into them.",
|
||||
"tv_auth.oauth_clients holds the client registry (manually seeded or created via RFC 7591 Dynamic Client Registration); public clients carry no secret and are authenticated by PKCE S256 alone.",
|
||||
"tv_auth.oauth_auth_codes holds single-use 60-second authorization codes; tv_auth.oauth_grants is one row per connected app and owns the rotating refresh token, with the previous hash kept to detect replay.",
|
||||
"Access tokens reuse tv_auth.api_tokens (new grant_id column) so validation, permission intersection and RejectApiTokenAuth all keep working unchanged; revoking a grant cascades to its live access tokens."
|
||||
]
|
||||
},
|
||||
"60": {
|
||||
"version": "1.65.0",
|
||||
"name": "Organization-level permissions",
|
||||
"releaseDate": "20260830",
|
||||
"scripts": [
|
||||
"/1.65.0/0.organization-permissions.sql"
|
||||
],
|
||||
"description": [
|
||||
"New permission group 'organization' with org_can_view, org_can_manage, org_can_manage_members, sso_can_manage and webhooks_can_manage.",
|
||||
"These surfaces were guarded only by an organization role or by project ownership, so they ignored the scope of an API or OAuth token: a token issued with a single permission could still create organizations, add admins, change SSO settings and create webhooks. The new keys make those actions narrowable like every other permission.",
|
||||
"Backwards compatible: a token with an empty permission list stays unrestricted, so existing integrations keep working."
|
||||
]
|
||||
},
|
||||
"61": {
|
||||
"version": "1.66.0",
|
||||
"name": "Billing: currencies, sellers, clients, invoices",
|
||||
"releaseDate": "20260904",
|
||||
"scripts": [
|
||||
"/1.66.0/0.create-currencies.sql",
|
||||
"/1.66.0/1.create-billing-sellers.sql",
|
||||
"/1.66.0/2.create-billing-counterparties.sql",
|
||||
"/1.66.0/3.create-invoices.sql",
|
||||
"/1.66.0/4.create-invoice-lines.sql",
|
||||
"/1.66.0/5.billing-permission.sql",
|
||||
"/1.66.0/6.alter-invoices-lifecycle.sql"
|
||||
],
|
||||
"description": [
|
||||
"New schema tv_billing with the reference table currencies (ISO 4217, seeded with 20 currencies), sellers (the organization's own companies that issue invoices, with bank details and free-form requisites), counterparties (clients that are invoiced) and invoices with invoice_lines.",
|
||||
"Invoices keep JSONB snapshots of the seller and the client plus the project name, so editing a company, a client or deleting a project never changes an issued document. Companies and clients are archived rather than deleted once they have invoices.",
|
||||
"New organization-level permission billing_can_manage (group 6) narrows what an API or OAuth token may do on the billing surfaces; access itself requires the organization owner or admin role.",
|
||||
"Invoice lifecycle: issued_at, paid_at, voided_at, replaces_invoice_id (void and reissue chain), template_version and totals frozen at issue time (subtotal, discount_amount, tax_amount, total). Status transitions are validated by the API; only drafts can be edited or deleted."
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE tv_auth.sso_configs
|
||||
ADD COLUMN IF NOT EXISTS domain_verify_token VARCHAR,
|
||||
ADD COLUMN IF NOT EXISTS domain_verified_at TIMESTAMP;
|
||||
@@ -0,0 +1,6 @@
|
||||
ALTER TABLE tv_auth.sso_configs
|
||||
DROP CONSTRAINT IF EXISTS sso_configs_email_domain_restriction_key;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS sso_configs_verified_domain_uniq
|
||||
ON tv_auth.sso_configs (email_domain_restriction)
|
||||
WHERE domain_verified_at IS NOT NULL;
|
||||
@@ -0,0 +1,16 @@
|
||||
-- OAuth 2.1 client registry. Clients are either seeded manually by an operator
|
||||
-- or created through Dynamic Client Registration (RFC 7591) when it is enabled.
|
||||
-- Public clients (MCP clients such as ChatGPT or Claude) hold no secret and are
|
||||
-- authenticated by PKCE alone, so client_secret_hash stays NULL for them.
|
||||
CREATE TABLE IF NOT EXISTS tv_auth.oauth_clients (
|
||||
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
client_id VARCHAR(64) NOT NULL UNIQUE,
|
||||
client_secret_hash VARCHAR(64),
|
||||
name VARCHAR(200) NOT NULL,
|
||||
redirect_uris VARCHAR[] NOT NULL DEFAULT '{}',
|
||||
created_via VARCHAR(16) NOT NULL DEFAULT 'manual',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT oauth_clients_created_via_check CHECK (created_via IN ('manual', 'dcr'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_oauth_clients_client_id ON tv_auth.oauth_clients(client_id);
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Short-lived, single-use authorization codes issued by the consent screen and
|
||||
-- redeemed once at the token endpoint. Only the hash is stored, mirroring
|
||||
-- tv_auth.api_tokens. used_at is set on redemption: a second redemption of the
|
||||
-- same code is treated as replay and revokes the grant it produced.
|
||||
CREATE TABLE IF NOT EXISTS tv_auth.oauth_auth_codes (
|
||||
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
code_hash VARCHAR(64) NOT NULL UNIQUE,
|
||||
client_id VARCHAR(64) NOT NULL REFERENCES tv_auth.oauth_clients(client_id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES tv_auth.users(id) ON DELETE CASCADE,
|
||||
redirect_uri VARCHAR NOT NULL,
|
||||
code_challenge VARCHAR(128) NOT NULL,
|
||||
code_challenge_method VARCHAR(8) NOT NULL DEFAULT 'S256',
|
||||
allowed_permissions VARCHAR[] NOT NULL DEFAULT '{}',
|
||||
allowed_goal_ids INTEGER[] NOT NULL DEFAULT '{}',
|
||||
resource VARCHAR,
|
||||
expires_at TIMESTAMP NOT NULL,
|
||||
used_at TIMESTAMP,
|
||||
grant_id INTEGER,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT oauth_auth_codes_challenge_method_check CHECK (code_challenge_method = 'S256')
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_oauth_auth_codes_code_hash ON tv_auth.oauth_auth_codes(code_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_oauth_auth_codes_expires_at ON tv_auth.oauth_auth_codes(expires_at);
|
||||
@@ -0,0 +1,33 @@
|
||||
-- One row per (user, client) authorization — this is what the user sees and
|
||||
-- revokes as a "connected app". The refresh token hangs off the grant and is
|
||||
-- rotated on every use; refresh_token_prev_hash keeps the previous value so a
|
||||
-- replayed refresh token can be detected and the whole grant revoked.
|
||||
CREATE TABLE IF NOT EXISTS tv_auth.oauth_grants (
|
||||
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
user_id INTEGER NOT NULL REFERENCES tv_auth.users(id) ON DELETE CASCADE,
|
||||
client_id VARCHAR(64) NOT NULL REFERENCES tv_auth.oauth_clients(client_id) ON DELETE CASCADE,
|
||||
allowed_permissions VARCHAR[] NOT NULL DEFAULT '{}',
|
||||
allowed_goal_ids INTEGER[] NOT NULL DEFAULT '{}',
|
||||
resource VARCHAR,
|
||||
refresh_token_hash VARCHAR(64) UNIQUE,
|
||||
refresh_token_prev_hash VARCHAR(64),
|
||||
refresh_expires_at TIMESTAMP,
|
||||
last_used_at TIMESTAMP,
|
||||
revoked_at TIMESTAMP,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_oauth_grants_user_id ON tv_auth.oauth_grants(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_oauth_grants_refresh_token_hash ON tv_auth.oauth_grants(refresh_token_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_oauth_grants_prev_refresh_hash ON tv_auth.oauth_grants(refresh_token_prev_hash);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'oauth_auth_codes_grant_id_fkey'
|
||||
) THEN
|
||||
ALTER TABLE tv_auth.oauth_auth_codes
|
||||
ADD CONSTRAINT oauth_auth_codes_grant_id_fkey
|
||||
FOREIGN KEY (grant_id) REFERENCES tv_auth.oauth_grants(id) ON DELETE SET NULL;
|
||||
END IF;
|
||||
END $$;
|
||||
@@ -0,0 +1,19 @@
|
||||
-- OAuth access tokens live in tv_auth.api_tokens alongside manually issued
|
||||
-- tvk_ tokens: same opaque-token storage, same validation path, same permission
|
||||
-- intersection. grant_id ties an access token to the OAuth grant that minted it,
|
||||
-- so revoking a connected app deletes its live access tokens immediately.
|
||||
ALTER TABLE tv_auth.api_tokens
|
||||
ADD COLUMN IF NOT EXISTS grant_id INTEGER;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'api_tokens_grant_id_fkey'
|
||||
) THEN
|
||||
ALTER TABLE tv_auth.api_tokens
|
||||
ADD CONSTRAINT api_tokens_grant_id_fkey
|
||||
FOREIGN KEY (grant_id) REFERENCES tv_auth.oauth_grants(id) ON DELETE CASCADE;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_api_tokens_grant_id ON tv_auth.api_tokens(grant_id);
|
||||
@@ -0,0 +1,86 @@
|
||||
-- Permissions for the surfaces that were previously guarded only by an
|
||||
-- organization role or by project ownership, and therefore ignored the scope of
|
||||
-- an API / OAuth token entirely: a token issued with a single permission could
|
||||
-- still create organizations, add admins, configure SSO and create webhooks.
|
||||
--
|
||||
-- These keys let a token be narrowed on those actions too. They never grant
|
||||
-- anything: the role and ownership checks still run first, and RequireTokenPermission
|
||||
-- only removes what the token was not given.
|
||||
INSERT INTO tv_auth.permissions_group (id, name)
|
||||
VALUES (6, 'organization')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)
|
||||
VALUES (
|
||||
'org_can_view',
|
||||
'View the organization and its members',
|
||||
6,
|
||||
'{
|
||||
"en": "View organization. See the organization and the list of its members.",
|
||||
"ru": "Просмотр организации. Видеть организацию и список её участников.",
|
||||
"de": "Organisation ansehen. Die Organisation und ihre Mitglieder sehen.",
|
||||
"es": "Ver la organización. Ver la organización y la lista de sus miembros.",
|
||||
"pt-BR": "Ver a organização. Ver a organização e a lista de seus membros."
|
||||
}'::jsonb
|
||||
)
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)
|
||||
VALUES (
|
||||
'org_can_manage',
|
||||
'Create, rename and delete organizations',
|
||||
6,
|
||||
'{
|
||||
"en": "Manage organizations. Create, rename and delete organizations.",
|
||||
"ru": "Управление организациями. Создавать, переименовывать и удалять организации.",
|
||||
"de": "Organisationen verwalten. Organisationen erstellen, umbenennen und löschen.",
|
||||
"es": "Gestionar organizaciones. Crear, renombrar y eliminar organizaciones.",
|
||||
"pt-BR": "Gerenciar organizações. Criar, renomear e excluir organizações."
|
||||
}'::jsonb
|
||||
)
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)
|
||||
VALUES (
|
||||
'org_can_manage_members',
|
||||
'Add and remove organization members and change their roles',
|
||||
6,
|
||||
'{
|
||||
"en": "Manage members. Add and remove organization members and change their roles.",
|
||||
"ru": "Управление участниками. Добавлять и удалять участников организации, менять их роли.",
|
||||
"de": "Mitglieder verwalten. Mitglieder hinzufügen, entfernen und deren Rollen ändern.",
|
||||
"es": "Gestionar miembros. Añadir y quitar miembros de la organización y cambiar sus roles.",
|
||||
"pt-BR": "Gerenciar membros. Adicionar e remover membros da organização e alterar seus papéis."
|
||||
}'::jsonb
|
||||
)
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)
|
||||
VALUES (
|
||||
'sso_can_manage',
|
||||
'Create and change the single sign-on configuration',
|
||||
6,
|
||||
'{
|
||||
"en": "Manage SSO. Create and change the single sign-on configuration of the organization.",
|
||||
"ru": "Управление SSO. Создавать и изменять настройки единого входа организации.",
|
||||
"de": "SSO verwalten. Die Single-Sign-on-Konfiguration der Organisation erstellen und ändern.",
|
||||
"es": "Gestionar SSO. Crear y cambiar la configuración de inicio de sesión único de la organización.",
|
||||
"pt-BR": "Gerenciar SSO. Criar e alterar a configuração de login único da organização."
|
||||
}'::jsonb
|
||||
)
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)
|
||||
VALUES (
|
||||
'webhooks_can_manage',
|
||||
'Create, edit and delete project webhooks',
|
||||
6,
|
||||
'{
|
||||
"en": "Manage webhooks. Create, edit and delete webhooks of a project.",
|
||||
"ru": "Управление вебхуками. Создавать, изменять и удалять вебхуки проекта.",
|
||||
"de": "Webhooks verwalten. Webhooks eines Projekts erstellen, bearbeiten und löschen.",
|
||||
"es": "Gestionar webhooks. Crear, editar y eliminar webhooks de un proyecto.",
|
||||
"pt-BR": "Gerenciar webhooks. Criar, editar e excluir webhooks de um projeto."
|
||||
}'::jsonb
|
||||
)
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
@@ -0,0 +1,45 @@
|
||||
-- Reference list of currencies (ISO 4217) for anything that carries money:
|
||||
-- invoices, counterparties, seller profiles. Names are stored in English only;
|
||||
-- the UI localises them through Intl.DisplayNames by code. decimal_digits
|
||||
-- drives amount formatting (JPY and KRW have none). Rows are never deleted,
|
||||
-- only deactivated, so existing references stay valid.
|
||||
CREATE SCHEMA IF NOT EXISTS tv_billing;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tv_billing.currencies (
|
||||
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
code CHAR(3) NOT NULL UNIQUE,
|
||||
numeric_code SMALLINT NOT NULL UNIQUE,
|
||||
name VARCHAR(64) NOT NULL,
|
||||
symbol VARCHAR(8) NOT NULL,
|
||||
decimal_digits SMALLINT NOT NULL DEFAULT 2,
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT currencies_code_upper_check CHECK (code = UPPER(code)),
|
||||
CONSTRAINT currencies_decimal_digits_check CHECK (decimal_digits BETWEEN 0 AND 4)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_currencies_active_sort ON tv_billing.currencies(is_active, sort_order);
|
||||
|
||||
INSERT INTO tv_billing.currencies (code, numeric_code, name, symbol, decimal_digits, sort_order) VALUES
|
||||
('USD', 840, 'US Dollar', '$', 2, 10),
|
||||
('EUR', 978, 'Euro', '€', 2, 20),
|
||||
('GBP', 826, 'Pound Sterling', '£', 2, 30),
|
||||
('JPY', 392, 'Japanese Yen', '¥', 0, 40),
|
||||
('CNY', 156, 'Chinese Yuan', '¥', 2, 50),
|
||||
('CHF', 756, 'Swiss Franc', 'CHF', 2, 60),
|
||||
('CAD', 124, 'Canadian Dollar', 'CA$', 2, 70),
|
||||
('AUD', 36, 'Australian Dollar', 'A$', 2, 80),
|
||||
('RUB', 643, 'Russian Ruble', '₽', 2, 25),
|
||||
('INR', 356, 'Indian Rupee', '₹', 2, 100),
|
||||
('BRL', 986, 'Brazilian Real', 'R$', 2, 110),
|
||||
('KRW', 410, 'South Korean Won', '₩', 0, 120),
|
||||
('SGD', 702, 'Singapore Dollar', 'S$', 2, 130),
|
||||
('HKD', 344, 'Hong Kong Dollar', 'HK$', 2, 140),
|
||||
('SEK', 752, 'Swedish Krona', 'kr', 2, 150),
|
||||
('NOK', 578, 'Norwegian Krone', 'kr', 2, 160),
|
||||
('DKK', 208, 'Danish Krone', 'kr', 2, 170),
|
||||
('PLN', 985, 'Polish Zloty', 'zł', 2, 180),
|
||||
('TRY', 949, 'Turkish Lira', '₺', 2, 190),
|
||||
('AED', 784, 'UAE Dirham', 'د.إ', 2, 200)
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
@@ -0,0 +1,20 @@
|
||||
CREATE TABLE IF NOT EXISTS tv_billing.sellers (
|
||||
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
organization_id INTEGER NOT NULL REFERENCES tv_auth.organizations(id) ON DELETE CASCADE,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
legal_name VARCHAR(300) NOT NULL DEFAULT '',
|
||||
address VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
email VARCHAR(320) NOT NULL DEFAULT '',
|
||||
phone VARCHAR(50) NOT NULL DEFAULT '',
|
||||
logo_url VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
currency_code CHAR(3) NOT NULL DEFAULT 'USD' REFERENCES tv_billing.currencies(code),
|
||||
bank JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
requisites JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
default_terms VARCHAR(2000) NOT NULL DEFAULT '',
|
||||
tax_note VARCHAR(500) NOT NULL DEFAULT '',
|
||||
archived BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_billing_sellers_org ON tv_billing.sellers(organization_id, archived);
|
||||
@@ -0,0 +1,18 @@
|
||||
CREATE TABLE IF NOT EXISTS tv_billing.counterparties (
|
||||
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
organization_id INTEGER NOT NULL REFERENCES tv_auth.organizations(id) ON DELETE CASCADE,
|
||||
kind VARCHAR(20) NOT NULL DEFAULT 'organization',
|
||||
name VARCHAR(200) NOT NULL,
|
||||
legal_name VARCHAR(300) NOT NULL DEFAULT '',
|
||||
address VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
email VARCHAR(320) NOT NULL DEFAULT '',
|
||||
phone VARCHAR(50) NOT NULL DEFAULT '',
|
||||
contact_person VARCHAR(200) NOT NULL DEFAULT '',
|
||||
requisites JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
archived BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT counterparties_kind_check CHECK (kind IN ('organization', 'person'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_billing_counterparties_org ON tv_billing.counterparties(organization_id, archived);
|
||||
@@ -0,0 +1,37 @@
|
||||
CREATE TABLE IF NOT EXISTS tv_billing.invoices (
|
||||
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
organization_id INTEGER NOT NULL REFERENCES tv_auth.organizations(id) ON DELETE CASCADE,
|
||||
goal_id INTEGER REFERENCES tasks.goals(id) ON DELETE SET NULL,
|
||||
goal_name VARCHAR(500) NOT NULL DEFAULT '',
|
||||
seller_id INTEGER NOT NULL REFERENCES tv_billing.sellers(id) ON DELETE RESTRICT,
|
||||
counterparty_id INTEGER NOT NULL REFERENCES tv_billing.counterparties(id) ON DELETE RESTRICT,
|
||||
number VARCHAR(50) NOT NULL,
|
||||
status VARCHAR(10) NOT NULL DEFAULT 'draft',
|
||||
reference VARCHAR(200) NOT NULL DEFAULT '',
|
||||
currency_code CHAR(3) NOT NULL REFERENCES tv_billing.currencies(code),
|
||||
issue_date DATE NOT NULL,
|
||||
payment_terms VARCHAR(20) NOT NULL DEFAULT 'net14',
|
||||
due_date DATE,
|
||||
period_from DATE,
|
||||
period_to DATE,
|
||||
discount_type VARCHAR(10) NOT NULL DEFAULT 'percent',
|
||||
discount_value NUMERIC(12, 2) NOT NULL DEFAULT 0,
|
||||
tax_rate NUMERIC(5, 2) NOT NULL DEFAULT 0,
|
||||
tax_exempt BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
tax_note VARCHAR(500) NOT NULL DEFAULT '',
|
||||
notes VARCHAR(2000) NOT NULL DEFAULT '',
|
||||
terms VARCHAR(2000) NOT NULL DEFAULT '',
|
||||
seller_snapshot JSONB NOT NULL,
|
||||
counterparty_snapshot JSONB NOT NULL,
|
||||
created_by INTEGER REFERENCES tv_auth.users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT invoices_status_check CHECK (status IN ('draft', 'issued', 'paid', 'void')),
|
||||
CONSTRAINT invoices_discount_type_check CHECK (discount_type IN ('percent', 'amount')),
|
||||
CONSTRAINT invoices_payment_terms_check CHECK (payment_terms IN ('on_receipt', 'net7', 'net14', 'net30', 'custom')),
|
||||
CONSTRAINT invoices_number_per_org UNIQUE (organization_id, number)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_billing_invoices_org_issue ON tv_billing.invoices(organization_id, issue_date DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_billing_invoices_counterparty ON tv_billing.invoices(counterparty_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_billing_invoices_seller ON tv_billing.invoices(seller_id);
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE IF NOT EXISTS tv_billing.invoice_lines (
|
||||
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
invoice_id INTEGER NOT NULL REFERENCES tv_billing.invoices(id) ON DELETE CASCADE,
|
||||
position SMALLINT NOT NULL DEFAULT 0,
|
||||
task_id INTEGER REFERENCES tasks.tasks(id) ON DELETE SET NULL,
|
||||
description VARCHAR(1000) NOT NULL,
|
||||
unit VARCHAR(20) NOT NULL DEFAULT 'service',
|
||||
quantity NUMERIC(12, 2) NOT NULL DEFAULT 1,
|
||||
unit_price NUMERIC(12, 2) NOT NULL DEFAULT 0,
|
||||
CONSTRAINT invoice_lines_unit_check CHECK (unit IN ('service', 'hours', 'pcs'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_billing_invoice_lines_invoice ON tv_billing.invoice_lines(invoice_id, position);
|
||||
@@ -0,0 +1,14 @@
|
||||
INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)
|
||||
VALUES (
|
||||
'billing_can_manage',
|
||||
'Manage invoices, clients and seller companies of the organization',
|
||||
6,
|
||||
'{
|
||||
"en": "Manage billing. Create and edit invoices, clients and seller companies of the organization.",
|
||||
"ru": "Управление биллингом. Создавать и редактировать инвойсы, клиентов и компании-продавцы организации.",
|
||||
"de": "Abrechnung verwalten. Rechnungen, Kunden und Firmen der Organisation erstellen und bearbeiten.",
|
||||
"es": "Gestionar facturación. Crear y editar facturas, clientes y empresas de la organización.",
|
||||
"pt-BR": "Gerenciar faturamento. Criar e editar faturas, clientes e empresas da organização."
|
||||
}'::jsonb
|
||||
)
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
@@ -0,0 +1,11 @@
|
||||
ALTER TABLE tv_billing.invoices ADD COLUMN IF NOT EXISTS issued_at TIMESTAMP;
|
||||
ALTER TABLE tv_billing.invoices ADD COLUMN IF NOT EXISTS paid_at TIMESTAMP;
|
||||
ALTER TABLE tv_billing.invoices ADD COLUMN IF NOT EXISTS voided_at TIMESTAMP;
|
||||
ALTER TABLE tv_billing.invoices ADD COLUMN IF NOT EXISTS replaces_invoice_id INTEGER REFERENCES tv_billing.invoices(id) ON DELETE SET NULL;
|
||||
ALTER TABLE tv_billing.invoices ADD COLUMN IF NOT EXISTS template_version SMALLINT NOT NULL DEFAULT 1;
|
||||
ALTER TABLE tv_billing.invoices ADD COLUMN IF NOT EXISTS subtotal NUMERIC(12, 2);
|
||||
ALTER TABLE tv_billing.invoices ADD COLUMN IF NOT EXISTS discount_amount NUMERIC(12, 2);
|
||||
ALTER TABLE tv_billing.invoices ADD COLUMN IF NOT EXISTS tax_amount NUMERIC(12, 2);
|
||||
ALTER TABLE tv_billing.invoices ADD COLUMN IF NOT EXISTS total NUMERIC(12, 2);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_billing_invoices_replaces ON tv_billing.invoices(replaces_invoice_id);
|
||||
@@ -8,6 +8,8 @@ import NotificationsRoutes from '../tv-modules/notifications/NotificationsRoutes
|
||||
import WebhooksRoutes from '../tv-modules/webhooks/WebhooksRoutes';
|
||||
import MessagingRoutes from '../tv-modules/messaging/MessagingRoutes';
|
||||
import ApiTokensRoutes from '../tv-modules/api-tokens/ApiTokensRoutes';
|
||||
import OAuthRoutes from '../tv-modules/oauth/OAuthRoutes';
|
||||
import OAuthWellKnownRoutes from '../tv-modules/oauth/OAuthWellKnownRoutes';
|
||||
import SessionsRoutes from '../tv-modules/sessions/SessionsRoutes';
|
||||
import KanbanRoutes from '../tv-modules/kanban/KanbanRoutes';
|
||||
import GoalListRoutes from '../tv-modules/lists/GoalListRoutes';
|
||||
@@ -22,6 +24,8 @@ import TimeTrackingRoutes from '../tv-modules/time-tracking/TimeTrackingRoutes';
|
||||
import UiPreferencesRoutes from '../tv-modules/ui-preferences/UiPreferencesRoutes';
|
||||
import SprintsRoutes from '../tv-modules/sprints/SprintsRoutes';
|
||||
import RecurrenceRoutes from '../tv-modules/recurrence/RecurrenceRoutes';
|
||||
import BillingRoutes from '../tv-modules/billing/BillingRoutes';
|
||||
import InvoicesRoutes from '../tv-modules/invoices/InvoicesRoutes';
|
||||
import type { Routable } from '../types/routable.type';
|
||||
|
||||
type RoutableConstructor = new (...args: any[]) => Routable;
|
||||
@@ -42,6 +46,7 @@ const routes: Record<string, RoutableConstructor> = {
|
||||
'/module/webhooks': WebhooksRoutes,
|
||||
'/module/messaging': MessagingRoutes,
|
||||
'/module/api-tokens': ApiTokensRoutes,
|
||||
'/module/oauth': OAuthRoutes,
|
||||
'/module/sessions': SessionsRoutes,
|
||||
'/module/organizations': OrganizationRoutes,
|
||||
'/module/sso': SsoRoutes,
|
||||
@@ -50,7 +55,10 @@ const routes: Record<string, RoutableConstructor> = {
|
||||
'/module/ui-preferences': UiPreferencesRoutes,
|
||||
'/module/sprints': SprintsRoutes,
|
||||
'/module/recurrence': RecurrenceRoutes,
|
||||
'/module/billing': BillingRoutes,
|
||||
'/module/invoices': InvoicesRoutes,
|
||||
'/scim/v2': ScimRoutes,
|
||||
'/.well-known': OAuthWellKnownRoutes,
|
||||
};
|
||||
|
||||
export default routes;
|
||||
|
||||
@@ -5,18 +5,12 @@ import { OverdueKpi } from './kpi/OverdueKpi'
|
||||
import { ThroughputSection } from './productivity/ThroughputSection'
|
||||
import { PriorityMixOverTimeSection } from './productivity/PriorityMixOverTimeSection'
|
||||
import { WorkloadByAssigneeSection } from './workload/WorkloadByAssigneeSection'
|
||||
import { BlockedByDependenciesSection } from './workload/BlockedByDependenciesSection'
|
||||
import { OverdueByAgeSection } from './quality/OverdueByAgeSection'
|
||||
import { StaleTasksSection } from './quality/StaleTasksSection'
|
||||
import { StatusDistributionSection } from './usage/StatusDistributionSection'
|
||||
import { ActiveProjectsSection } from './usage/ActiveProjectsSection'
|
||||
import { IncomeExpenseMonthSection } from './financial/IncomeExpenseMonthSection'
|
||||
import { IncomeExpensePerProjectSection } from './financial/IncomeExpensePerProjectSection'
|
||||
import { IncomePerProjectMonthSection } from './financial/IncomePerProjectMonthSection'
|
||||
import { ExpensePerProjectMonthSection } from './financial/ExpensePerProjectMonthSection'
|
||||
import { IncomePerTagMonthSection } from './financial/IncomePerTagMonthSection'
|
||||
import { ExpensePerTagMonthSection } from './financial/ExpensePerTagMonthSection'
|
||||
import { TopProjectsByAmountSection } from './financial/TopProjectsByAmountSection'
|
||||
import { AmountCoverageKpi } from './financial/AmountCoverageKpi'
|
||||
import { TotalIncomeKpi } from './financial/TotalIncomeKpi'
|
||||
import { TotalExpenseKpi } from './financial/TotalExpenseKpi'
|
||||
@@ -59,6 +53,12 @@ import { sectionLocales } from './locales'
|
||||
// - entered_at) for rows in that status. Without a transition log, this
|
||||
// metric cannot be computed correctly.
|
||||
// ---------------------------------------------------------------------------
|
||||
// import { BlockedByDependenciesSection } from './workload/BlockedByDependenciesSection'
|
||||
// import { ActiveProjectsSection } from './usage/ActiveProjectsSection'
|
||||
// import { OverdueByAgeSection } from './quality/OverdueByAgeSection'
|
||||
// import { TopProjectsByAmountSection } from './financial/TopProjectsByAmountSection'
|
||||
// import { IncomePerTagMonthSection } from './financial/IncomePerTagMonthSection'
|
||||
// import { ExpensePerTagMonthSection } from './financial/ExpensePerTagMonthSection'
|
||||
// import { AgingOpenTasksSection } from './workload/AgingOpenTasksSection'
|
||||
// import { TimeInKanbanStatusSection } from './workload/TimeInKanbanStatusSection'
|
||||
// import { CycleTimeKpi } from './kpi/CycleTimeKpi'
|
||||
@@ -82,25 +82,25 @@ const builders: SectionBuilder[] = [
|
||||
new PriorityMixOverTimeSection(),
|
||||
// Workload
|
||||
new WorkloadByAssigneeSection(),
|
||||
new BlockedByDependenciesSection(),
|
||||
// new BlockedByDependenciesSection(), // disabled
|
||||
// new TimeInKanbanStatusSection(), // disabled — see top-of-file comment
|
||||
// new AgingOpenTasksSection(), // disabled — see top-of-file comment
|
||||
// Quality
|
||||
new OverdueByAgeSection(),
|
||||
// new OverdueByAgeSection(), // disabled
|
||||
// new CycleTimeHistogramSection(), // disabled — see top-of-file comment
|
||||
new StaleTasksSection(),
|
||||
// new CycleTimePerProjectSection(), // disabled — see top-of-file comment
|
||||
// Usage
|
||||
new StatusDistributionSection(),
|
||||
new ActiveProjectsSection(),
|
||||
// new ActiveProjectsSection(), // disabled
|
||||
// Financial
|
||||
new IncomeExpenseMonthSection(),
|
||||
new IncomeExpensePerProjectSection(),
|
||||
new IncomePerProjectMonthSection(),
|
||||
new ExpensePerProjectMonthSection(),
|
||||
new IncomePerTagMonthSection(),
|
||||
new ExpensePerTagMonthSection(),
|
||||
new TopProjectsByAmountSection(),
|
||||
// new IncomePerTagMonthSection(), // disabled
|
||||
// new ExpensePerTagMonthSection(), // disabled
|
||||
// new TopProjectsByAmountSection(), // disabled
|
||||
]
|
||||
|
||||
export class SectionRegistry {
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { Request, Response } from 'express';
|
||||
import { ArkErrors } from 'arktype';
|
||||
import { getApiTokensManager } from './ApiTokensManager';
|
||||
import { ApiTokenArkTypeCreate, ApiTokenArkTypeDelete } from './types';
|
||||
import { Database } from '../../modules/db';
|
||||
|
||||
export class ApiTokensController {
|
||||
private get manager() { return getApiTokensManager(); }
|
||||
@@ -44,10 +43,7 @@ export class ApiTokensController {
|
||||
};
|
||||
|
||||
fetchPermissions = async (_req: Request, res: Response) => {
|
||||
const db = Database.getInstance();
|
||||
const result = await db.query<{ id: number; name: string; description: string; permissionGroup: number }>(
|
||||
`SELECT id, name, description, permission_group as "permissionGroup" FROM tv_auth.permissions WHERE permission_group <> 1 ORDER BY permission_group, id`
|
||||
);
|
||||
return res.tvJson(result?.rows ?? []);
|
||||
const result = await this.manager.fetchSelectablePermissions();
|
||||
return res.tvJson(result);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { randomBytes, createHash } from 'crypto';
|
||||
import { ApiTokensRepository } from './ApiTokensRepository';
|
||||
import { TOKEN_PREFIX, type ApiTokenArgCreate } from './types';
|
||||
import type { ApiTokensSchemaTypeForSelect } from 'taskview-db-schemas';
|
||||
import type { ApiTokensSchemaTypeForSelect, PermissionsSchemaTypeForSelect } from 'taskview-db-schemas';
|
||||
|
||||
export type ApiTokenForClient = Omit<ApiTokensSchemaTypeForSelect, 'tokenHash'>;
|
||||
|
||||
@@ -42,6 +42,10 @@ export class ApiTokensManager {
|
||||
return tokens.map((t) => this.toClient(t));
|
||||
}
|
||||
|
||||
async fetchSelectablePermissions(): Promise<PermissionsSchemaTypeForSelect[]> {
|
||||
return this.repository.fetchSelectablePermissions();
|
||||
}
|
||||
|
||||
async validateToken(fullToken: string): Promise<ApiTokensSchemaTypeForSelect | null> {
|
||||
const tokenHash = createHash('sha256').update(fullToken).digest('hex');
|
||||
const record = await this.repository.findByTokenHash(tokenHash);
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { and, eq } from 'drizzle-orm';
|
||||
import { ApiTokensSchema, type ApiTokensSchemaTypeForSelect } from 'taskview-db-schemas';
|
||||
import { and, asc, eq, isNull, ne } from 'drizzle-orm';
|
||||
import {
|
||||
ApiTokensSchema,
|
||||
PermissionsSchema,
|
||||
type ApiTokensSchemaTypeForSelect,
|
||||
type PermissionsSchemaTypeForSelect,
|
||||
} from 'taskview-db-schemas';
|
||||
import { Database } from '../../modules/db';
|
||||
import { callWithCatch } from '../../utils/helpers';
|
||||
|
||||
@@ -20,15 +25,21 @@ export class ApiTokensRepository {
|
||||
async delete(id: number, userId: number): Promise<boolean> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.delete(ApiTokensSchema).where(
|
||||
and(eq(ApiTokensSchema.id, id), eq(ApiTokensSchema.userId, userId))
|
||||
and(eq(ApiTokensSchema.id, id), eq(ApiTokensSchema.userId, userId), isNull(ApiTokensSchema.grantId))
|
||||
)
|
||||
);
|
||||
return !!result?.rowCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only manually issued tokens. OAuth access tokens live in the same table but
|
||||
* belong to a grant - they are listed and revoked as connected apps instead.
|
||||
*/
|
||||
async fetchByUserId(userId: number): Promise<ApiTokensSchemaTypeForSelect[]> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select().from(ApiTokensSchema).where(eq(ApiTokensSchema.userId, userId))
|
||||
this.db.dbDrizzle.select().from(ApiTokensSchema).where(
|
||||
and(eq(ApiTokensSchema.userId, userId), isNull(ApiTokensSchema.grantId))
|
||||
)
|
||||
);
|
||||
return result ?? [];
|
||||
}
|
||||
@@ -40,6 +51,21 @@ export class ApiTokensRepository {
|
||||
return result?.[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Permissions offered when scoping a token. Group 1 is excluded: those keys
|
||||
* exist in the table but are enforced nowhere in the code, so offering them
|
||||
* would promise a restriction that never happens.
|
||||
*/
|
||||
async fetchSelectablePermissions(): Promise<PermissionsSchemaTypeForSelect[]> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select()
|
||||
.from(PermissionsSchema)
|
||||
.where(ne(PermissionsSchema.permissionGroup, 1))
|
||||
.orderBy(asc(PermissionsSchema.permissionGroup), asc(PermissionsSchema.id))
|
||||
);
|
||||
return result ?? [];
|
||||
}
|
||||
|
||||
async updateLastUsedAt(id: number): Promise<void> {
|
||||
await callWithCatch(() =>
|
||||
this.db.dbDrizzle.update(ApiTokensSchema)
|
||||
|
||||
@@ -367,6 +367,16 @@ export default class AuthController {
|
||||
// Invalidate code immediately to prevent replay attacks
|
||||
await req.appUser.authManager.repository.updateLoginCode(null, userData.email);
|
||||
|
||||
if (userData.block) {
|
||||
if (!userData.confirm_email_code) {
|
||||
return res.status(403).send({ message: 'account_blocked' });
|
||||
}
|
||||
const confirmed = await req.appUser.authManager.repository.markEmailConfirmed(userData.email);
|
||||
if (!confirmed) {
|
||||
return res.status(500).end();
|
||||
}
|
||||
}
|
||||
|
||||
const sessionId = await req.appUser.authManager.sessionStorage.createSession(
|
||||
userData.id,
|
||||
req.ip,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { eq, sql } from 'drizzle-orm';
|
||||
import { CollaborationUsersSchema, OrganizationMembersSchema, SsoIdentitiesSchema, UsersSchema } from 'taskview-db-schemas';
|
||||
import { Database } from '../../modules/db';
|
||||
import { $logger } from '../../modules/logget';
|
||||
import type { RegisterUserInDb, UpdateUserCredentialsArgs, UpdateUserCredentialsResult, UserDbRecord } from '../../types/auth.types';
|
||||
import type { RegisterUserInDb, UpdateUserCredentialsArgs, UpdateUserEmailArgs, UpdateUserCredentialsResult, UserDbRecord } from '../../types/auth.types';
|
||||
|
||||
export default class AuthModel {
|
||||
private readonly db: Database;
|
||||
@@ -119,6 +119,21 @@ export default class AuthModel {
|
||||
}
|
||||
}
|
||||
|
||||
async markEmailConfirmed(email: string): Promise<boolean> {
|
||||
if (!email) return false;
|
||||
|
||||
try {
|
||||
const result = await this.db.dbDrizzle
|
||||
.update(UsersSchema)
|
||||
.set({ confirmEmailCode: null, block: 0 })
|
||||
.where(eq(UsersSchema.email, email));
|
||||
return (result.rowCount ?? 0) > 0;
|
||||
} catch (error) {
|
||||
$logger.error(error, `Error marking email confirmed for ${email}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async confirmEmail(login: string, code: string, block: number): Promise<boolean> {
|
||||
const query = `UPDATE tv_auth.users
|
||||
SET confirm_email_code = NULL, block = $1
|
||||
@@ -189,6 +204,37 @@ export default class AuthModel {
|
||||
}
|
||||
}
|
||||
|
||||
async updateUserEmail(args: UpdateUserEmailArgs): Promise<UpdateUserCredentialsResult> {
|
||||
try {
|
||||
await this.db.dbDrizzle.transaction(async (tx) => {
|
||||
await tx
|
||||
.update(UsersSchema)
|
||||
.set({ email: args.email })
|
||||
.where(eq(UsersSchema.id, args.userId));
|
||||
await tx
|
||||
.update(OrganizationMembersSchema)
|
||||
.set({ email: args.email })
|
||||
.where(eq(OrganizationMembersSchema.email, args.oldEmail));
|
||||
await tx
|
||||
.update(CollaborationUsersSchema)
|
||||
.set({ email: args.email })
|
||||
.where(eq(CollaborationUsersSchema.email, args.oldEmail));
|
||||
await tx
|
||||
.update(SsoIdentitiesSchema)
|
||||
.set({ email: args.email })
|
||||
.where(eq(SsoIdentitiesSchema.userId, args.userId));
|
||||
});
|
||||
return 'ok';
|
||||
} catch (error) {
|
||||
const pgCode = (error as { code?: string })?.code ?? (error as { cause?: { code?: string } })?.cause?.code;
|
||||
if (pgCode === '23505') {
|
||||
return 'conflict';
|
||||
}
|
||||
$logger.error(error, `Can not update email for user ${args.userId}`);
|
||||
return 'error';
|
||||
}
|
||||
}
|
||||
|
||||
async updateUserPassword(password: string, userId: number): Promise<boolean> {
|
||||
try {
|
||||
const query = 'UPDATE tv_auth.users SET password = $1 WHERE id = $2';
|
||||
|
||||
@@ -512,4 +512,65 @@ describe('Login API', () => {
|
||||
|
||||
expect(te).toBe(0);
|
||||
});
|
||||
|
||||
it('loginByCode confirms and admits a blocked-unconfirmed account', async () => {
|
||||
deleteTestUserEmail = `${Date.now()}test@mail.dest`;
|
||||
const email = deleteTestUserEmail;
|
||||
|
||||
await axios.post(`${url}/module/auth/registration`, {
|
||||
email,
|
||||
password: 'user1!#Q',
|
||||
passwordRepeat: 'user1!#Q',
|
||||
});
|
||||
|
||||
const userModel = new AuthModel();
|
||||
const before = await userModel.getUserByLogin(email, true);
|
||||
expect(before).toBeTruthy();
|
||||
expect((before as any).block).toBe(1);
|
||||
expect((before as any).confirm_email_code).toBeTruthy();
|
||||
|
||||
const code = '654321';
|
||||
await userModel.updateLoginCode(`${code}:${Date.now()}`, email);
|
||||
|
||||
const response = await axios.post(`${url}/module/auth/login-by-code`, { email, code });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.data.access).toBeTruthy();
|
||||
expect(response.data.refresh).toBeTruthy();
|
||||
|
||||
const after = await userModel.getUserByLogin(email, true);
|
||||
expect((after as any).block).toBe(0);
|
||||
expect((after as any).confirm_email_code).toBeNull();
|
||||
});
|
||||
|
||||
it('loginByCode rejects a banned account (blocked, no confirm code)', async () => {
|
||||
deleteTestUserEmail = `${Date.now()}test@mail.dest`;
|
||||
const email = deleteTestUserEmail;
|
||||
|
||||
await axios.post(`${url}/module/auth/registration`, {
|
||||
email,
|
||||
password: 'user1!#Q',
|
||||
passwordRepeat: 'user1!#Q',
|
||||
});
|
||||
|
||||
const db = Database.getInstance();
|
||||
await db.query('update tv_auth.users set block = 1, confirm_email_code = null where email = $1', [email]);
|
||||
|
||||
const userModel = new AuthModel();
|
||||
const code = '112233';
|
||||
await userModel.updateLoginCode(`${code}:${Date.now()}`, email);
|
||||
|
||||
let status = 0;
|
||||
let message = '';
|
||||
await axios.post(`${url}/module/auth/login-by-code`, { email, code }).catch((err) => {
|
||||
status = err.response.status;
|
||||
message = err.response.data.message;
|
||||
});
|
||||
|
||||
expect(status).toBe(403);
|
||||
expect(message).toBe('account_blocked');
|
||||
|
||||
const after = await userModel.getUserByLogin(email, true);
|
||||
expect((after as any).block).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { Request, Response } from 'express'
|
||||
import { ArkErrors } from 'arktype'
|
||||
import { BillingManager } from './BillingManager'
|
||||
import {
|
||||
BillingArkTypeArchive,
|
||||
BillingArkTypeId,
|
||||
BillingArkTypeList,
|
||||
CounterpartyArkTypeCreate,
|
||||
CounterpartyArkTypeUpdate,
|
||||
SellerArkTypeCreate,
|
||||
SellerArkTypeUpdate,
|
||||
type DeleteResult,
|
||||
} from './types'
|
||||
|
||||
const DELETE_STATUS: Record<DeleteResult, number> = { deleted: 200, in_use: 409, not_found: 404 }
|
||||
|
||||
export class BillingController {
|
||||
private readonly manager = new BillingManager()
|
||||
|
||||
currencies = async (_req: Request, res: Response) => {
|
||||
return res.tvJson(await this.manager.fetchCurrencies())
|
||||
}
|
||||
|
||||
fetchSellers = async (req: Request, res: Response) => {
|
||||
const data = BillingArkTypeList(req.query)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
return res.tvJson(await this.manager.fetchSellers(data))
|
||||
}
|
||||
|
||||
createSeller = async (req: Request, res: Response) => {
|
||||
const data = SellerArkTypeCreate(req.body)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
const result = await this.manager.createSeller(data)
|
||||
if (!result) return res.status(500).end()
|
||||
return res.tvJson(result)
|
||||
}
|
||||
|
||||
updateSeller = async (req: Request, res: Response) => {
|
||||
const id = BillingArkTypeId(req.params)
|
||||
const data = SellerArkTypeUpdate(req.body)
|
||||
if (id instanceof ArkErrors) return res.status(400).send(id.summary)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
const result = await this.manager.updateSeller({ sellerId: id.id, data })
|
||||
if (!result) return res.status(404).end()
|
||||
return res.tvJson(result)
|
||||
}
|
||||
|
||||
archiveSeller = async (req: Request, res: Response) => {
|
||||
const id = BillingArkTypeId(req.params)
|
||||
const data = BillingArkTypeArchive(req.body)
|
||||
if (id instanceof ArkErrors) return res.status(400).send(id.summary)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
const result = await this.manager.setSellerArchived({ id: id.id, archived: data.archived })
|
||||
if (!result) return res.status(404).end()
|
||||
return res.tvJson(result)
|
||||
}
|
||||
|
||||
deleteSeller = async (req: Request, res: Response) => {
|
||||
const id = BillingArkTypeId(req.params)
|
||||
if (id instanceof ArkErrors) return res.status(400).send(id.summary)
|
||||
const result = await this.manager.deleteSeller(id.id)
|
||||
if (result !== 'deleted') return res.status(DELETE_STATUS[result]).end()
|
||||
return res.tvJson(true)
|
||||
}
|
||||
|
||||
fetchCounterparties = async (req: Request, res: Response) => {
|
||||
const data = BillingArkTypeList(req.query)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
return res.tvJson(await this.manager.fetchCounterparties(data))
|
||||
}
|
||||
|
||||
createCounterparty = async (req: Request, res: Response) => {
|
||||
const data = CounterpartyArkTypeCreate(req.body)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
const result = await this.manager.createCounterparty(data)
|
||||
if (!result) return res.status(500).end()
|
||||
return res.tvJson(result)
|
||||
}
|
||||
|
||||
updateCounterparty = async (req: Request, res: Response) => {
|
||||
const id = BillingArkTypeId(req.params)
|
||||
const data = CounterpartyArkTypeUpdate(req.body)
|
||||
if (id instanceof ArkErrors) return res.status(400).send(id.summary)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
const result = await this.manager.updateCounterparty({ counterpartyId: id.id, data })
|
||||
if (!result) return res.status(404).end()
|
||||
return res.tvJson(result)
|
||||
}
|
||||
|
||||
archiveCounterparty = async (req: Request, res: Response) => {
|
||||
const id = BillingArkTypeId(req.params)
|
||||
const data = BillingArkTypeArchive(req.body)
|
||||
if (id instanceof ArkErrors) return res.status(400).send(id.summary)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
const result = await this.manager.setCounterpartyArchived({ id: id.id, archived: data.archived })
|
||||
if (!result) return res.status(404).end()
|
||||
return res.tvJson(result)
|
||||
}
|
||||
|
||||
deleteCounterparty = async (req: Request, res: Response) => {
|
||||
const id = BillingArkTypeId(req.params)
|
||||
if (id instanceof ArkErrors) return res.status(400).send(id.summary)
|
||||
const result = await this.manager.deleteCounterparty(id.id)
|
||||
if (result !== 'deleted') return res.status(DELETE_STATUS[result]).end()
|
||||
return res.tvJson(true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { BillingRepository } from './BillingRepository'
|
||||
import type {
|
||||
BillingArgList,
|
||||
CounterpartyArgCreate,
|
||||
CounterpartyForClient,
|
||||
CounterpartyUpdateArgs,
|
||||
DeleteResult,
|
||||
SellerArgCreate,
|
||||
SellerForClient,
|
||||
SellerUpdateArgs,
|
||||
SetArchivedArgs,
|
||||
} from './types'
|
||||
|
||||
export class BillingManager {
|
||||
public readonly repository: BillingRepository
|
||||
|
||||
constructor() {
|
||||
this.repository = new BillingRepository()
|
||||
}
|
||||
|
||||
fetchCurrencies() {
|
||||
return this.repository.fetchCurrencies()
|
||||
}
|
||||
|
||||
fetchSellers(args: BillingArgList): Promise<SellerForClient[]> {
|
||||
return this.repository.fetchSellers(args)
|
||||
}
|
||||
|
||||
fetchSellerById(sellerId: number): Promise<SellerForClient | null> {
|
||||
return this.repository.fetchSellerById(sellerId)
|
||||
}
|
||||
|
||||
createSeller(data: SellerArgCreate): Promise<SellerForClient | null> {
|
||||
return this.repository.createSeller(data)
|
||||
}
|
||||
|
||||
updateSeller(args: SellerUpdateArgs): Promise<SellerForClient | null> {
|
||||
return this.repository.updateSeller(args)
|
||||
}
|
||||
|
||||
setSellerArchived(args: SetArchivedArgs): Promise<SellerForClient | null> {
|
||||
return this.repository.setSellerArchived(args)
|
||||
}
|
||||
|
||||
async deleteSeller(sellerId: number): Promise<DeleteResult> {
|
||||
if ((await this.repository.countInvoicesBySeller(sellerId)) > 0) return 'in_use'
|
||||
return (await this.repository.deleteSeller(sellerId)) ? 'deleted' : 'not_found'
|
||||
}
|
||||
|
||||
fetchCounterparties(args: BillingArgList): Promise<CounterpartyForClient[]> {
|
||||
return this.repository.fetchCounterparties(args)
|
||||
}
|
||||
|
||||
fetchCounterpartyById(counterpartyId: number): Promise<CounterpartyForClient | null> {
|
||||
return this.repository.fetchCounterpartyById(counterpartyId)
|
||||
}
|
||||
|
||||
createCounterparty(data: CounterpartyArgCreate): Promise<CounterpartyForClient | null> {
|
||||
return this.repository.createCounterparty(data)
|
||||
}
|
||||
|
||||
updateCounterparty(args: CounterpartyUpdateArgs): Promise<CounterpartyForClient | null> {
|
||||
return this.repository.updateCounterparty(args)
|
||||
}
|
||||
|
||||
setCounterpartyArchived(args: SetArchivedArgs): Promise<CounterpartyForClient | null> {
|
||||
return this.repository.setCounterpartyArchived(args)
|
||||
}
|
||||
|
||||
async deleteCounterparty(counterpartyId: number): Promise<DeleteResult> {
|
||||
if ((await this.repository.countInvoicesByCounterparty(counterpartyId)) > 0) return 'in_use'
|
||||
return (await this.repository.deleteCounterparty(counterpartyId)) ? 'deleted' : 'not_found'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { and, asc, count, eq } from 'drizzle-orm'
|
||||
import {
|
||||
CounterpartiesSchema,
|
||||
CurrenciesSchema,
|
||||
InvoicesSchema,
|
||||
SellersSchema,
|
||||
type CounterpartiesSchemaTypeForSelect,
|
||||
type CurrenciesSchemaTypeForSelect,
|
||||
type SellersSchemaTypeForSelect,
|
||||
} from 'taskview-db-schemas'
|
||||
import { Database } from '../../modules/db'
|
||||
import { callWithCatch } from '../../utils/helpers'
|
||||
import type {
|
||||
BillingArgList,
|
||||
CounterpartyArgCreate,
|
||||
CounterpartyArgUpdate,
|
||||
CounterpartyUpdateArgs,
|
||||
SellerArgCreate,
|
||||
SellerArgUpdate,
|
||||
SellerUpdateArgs,
|
||||
SetArchivedArgs,
|
||||
} from './types'
|
||||
|
||||
export class BillingRepository {
|
||||
private readonly db: Database
|
||||
|
||||
constructor() {
|
||||
this.db = Database.getInstance()
|
||||
}
|
||||
|
||||
async fetchCurrencies(): Promise<CurrenciesSchemaTypeForSelect[]> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select()
|
||||
.from(CurrenciesSchema)
|
||||
.where(eq(CurrenciesSchema.isActive, true))
|
||||
.orderBy(asc(CurrenciesSchema.sortOrder)),
|
||||
)
|
||||
return result ?? []
|
||||
}
|
||||
|
||||
async fetchSellers({ organizationId, includeArchived }: BillingArgList): Promise<SellersSchemaTypeForSelect[]> {
|
||||
const conditions = [eq(SellersSchema.organizationId, organizationId)]
|
||||
if (!includeArchived) conditions.push(eq(SellersSchema.archived, false))
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select().from(SellersSchema).where(and(...conditions)).orderBy(asc(SellersSchema.name)),
|
||||
)
|
||||
return result ?? []
|
||||
}
|
||||
|
||||
async fetchSellerById(sellerId: number): Promise<SellersSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select().from(SellersSchema).where(eq(SellersSchema.id, sellerId)),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
private sellerColumns(data: SellerArgUpdate) {
|
||||
return {
|
||||
name: data.name,
|
||||
legalName: data.legalName,
|
||||
address: data.address,
|
||||
email: data.email,
|
||||
phone: data.phone,
|
||||
logoUrl: data.logoUrl,
|
||||
currencyCode: data.currencyCode,
|
||||
bank: data.bank,
|
||||
requisites: data.requisites,
|
||||
defaultTerms: data.defaultTerms,
|
||||
taxNote: data.taxNote,
|
||||
}
|
||||
}
|
||||
|
||||
private counterpartyColumns(data: CounterpartyArgUpdate) {
|
||||
return {
|
||||
kind: data.kind,
|
||||
name: data.name,
|
||||
legalName: data.legalName,
|
||||
address: data.address,
|
||||
email: data.email,
|
||||
phone: data.phone,
|
||||
contactPerson: data.contactPerson,
|
||||
requisites: data.requisites,
|
||||
}
|
||||
}
|
||||
|
||||
async createSeller(data: SellerArgCreate): Promise<SellersSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.insert(SellersSchema)
|
||||
.values({ organizationId: data.organizationId, ...this.sellerColumns(data) })
|
||||
.returning(),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
async updateSeller({ sellerId, data }: SellerUpdateArgs): Promise<SellersSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.update(SellersSchema)
|
||||
.set({ ...this.sellerColumns(data), updatedAt: new Date() })
|
||||
.where(eq(SellersSchema.id, sellerId))
|
||||
.returning(),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
async setSellerArchived({ id, archived }: SetArchivedArgs): Promise<SellersSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.update(SellersSchema)
|
||||
.set({ archived, updatedAt: new Date() })
|
||||
.where(eq(SellersSchema.id, id))
|
||||
.returning(),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
async deleteSeller(sellerId: number): Promise<boolean> {
|
||||
const result = await callWithCatch(() => this.db.dbDrizzle.delete(SellersSchema).where(eq(SellersSchema.id, sellerId)))
|
||||
return !!result?.rowCount
|
||||
}
|
||||
|
||||
async countInvoicesBySeller(sellerId: number): Promise<number> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select({ total: count() }).from(InvoicesSchema).where(eq(InvoicesSchema.sellerId, sellerId)),
|
||||
)
|
||||
return result?.[0]?.total ?? 0
|
||||
}
|
||||
|
||||
async fetchCounterparties({ organizationId, includeArchived }: BillingArgList): Promise<CounterpartiesSchemaTypeForSelect[]> {
|
||||
const conditions = [eq(CounterpartiesSchema.organizationId, organizationId)]
|
||||
if (!includeArchived) conditions.push(eq(CounterpartiesSchema.archived, false))
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select()
|
||||
.from(CounterpartiesSchema)
|
||||
.where(and(...conditions))
|
||||
.orderBy(asc(CounterpartiesSchema.name)),
|
||||
)
|
||||
return result ?? []
|
||||
}
|
||||
|
||||
async fetchCounterpartyById(counterpartyId: number): Promise<CounterpartiesSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select().from(CounterpartiesSchema).where(eq(CounterpartiesSchema.id, counterpartyId)),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
async createCounterparty(data: CounterpartyArgCreate): Promise<CounterpartiesSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.insert(CounterpartiesSchema)
|
||||
.values({ organizationId: data.organizationId, ...this.counterpartyColumns(data) })
|
||||
.returning(),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
async updateCounterparty({ counterpartyId, data }: CounterpartyUpdateArgs): Promise<CounterpartiesSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.update(CounterpartiesSchema)
|
||||
.set({ ...this.counterpartyColumns(data), updatedAt: new Date() })
|
||||
.where(eq(CounterpartiesSchema.id, counterpartyId))
|
||||
.returning(),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
async setCounterpartyArchived({ id, archived }: SetArchivedArgs): Promise<CounterpartiesSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.update(CounterpartiesSchema)
|
||||
.set({ archived, updatedAt: new Date() })
|
||||
.where(eq(CounterpartiesSchema.id, id))
|
||||
.returning(),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
async deleteCounterparty(counterpartyId: number): Promise<boolean> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.delete(CounterpartiesSchema).where(eq(CounterpartiesSchema.id, counterpartyId)),
|
||||
)
|
||||
return !!result?.rowCount
|
||||
}
|
||||
|
||||
async countInvoicesByCounterparty(counterpartyId: number): Promise<number> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select({ total: count() })
|
||||
.from(InvoicesSchema)
|
||||
.where(eq(InvoicesSchema.counterpartyId, counterpartyId)),
|
||||
)
|
||||
return result?.[0]?.total ?? 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Router } from 'express'
|
||||
import type { Routable } from '../../types/routable.type'
|
||||
import { IsLoggedIn } from '../auth/middlewares/is-logged-in'
|
||||
import { IsOrgAdmin } from '../organizations/middlewares/IsOrgAdmin'
|
||||
import { RequireTokenPermission } from '../../middlewares/require-token-permission'
|
||||
import { GoalPermissions } from '../../types/auth.types'
|
||||
import { BillingController } from './BillingController'
|
||||
import { isOrgAdminForCounterparty, isOrgAdminForSeller } from './middlewares/is-org-admin-for-billing'
|
||||
|
||||
export default class BillingRoutes implements Routable {
|
||||
private readonly router: ReturnType<typeof Router>
|
||||
private readonly controller: BillingController
|
||||
|
||||
constructor() {
|
||||
this.router = Router()
|
||||
this.controller = new BillingController()
|
||||
this.initRoutes()
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router
|
||||
}
|
||||
|
||||
private initRoutes() {
|
||||
const canManage = RequireTokenPermission(GoalPermissions.BILLING_CAN_MANAGE)
|
||||
|
||||
this.router.get('/currencies', [IsLoggedIn], this.controller.currencies)
|
||||
|
||||
this.router.get('/sellers', [IsLoggedIn, IsOrgAdmin, canManage], this.controller.fetchSellers)
|
||||
this.router.post('/sellers', [IsLoggedIn, IsOrgAdmin, canManage], this.controller.createSeller)
|
||||
this.router.patch('/sellers/:id', [IsLoggedIn, isOrgAdminForSeller, canManage], this.controller.updateSeller)
|
||||
this.router.patch('/sellers/:id/archive', [IsLoggedIn, isOrgAdminForSeller, canManage], this.controller.archiveSeller)
|
||||
this.router.delete('/sellers/:id', [IsLoggedIn, isOrgAdminForSeller, canManage], this.controller.deleteSeller)
|
||||
|
||||
this.router.get('/counterparties', [IsLoggedIn, IsOrgAdmin, canManage], this.controller.fetchCounterparties)
|
||||
this.router.post('/counterparties', [IsLoggedIn, IsOrgAdmin, canManage], this.controller.createCounterparty)
|
||||
this.router.patch('/counterparties/:id', [IsLoggedIn, isOrgAdminForCounterparty, canManage], this.controller.updateCounterparty)
|
||||
this.router.patch('/counterparties/:id/archive', [IsLoggedIn, isOrgAdminForCounterparty, canManage], this.controller.archiveCounterparty)
|
||||
this.router.delete('/counterparties/:id', [IsLoggedIn, isOrgAdminForCounterparty, canManage], this.controller.deleteCounterparty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { BillingRepository } from '../BillingRepository'
|
||||
import { isOrgAdminFor } from './is-org-admin-for'
|
||||
|
||||
const repository = new BillingRepository()
|
||||
|
||||
export const isOrgAdminForSeller = isOrgAdminFor(async (id) => (await repository.fetchSellerById(id))?.organizationId ?? null)
|
||||
|
||||
export const isOrgAdminForCounterparty = isOrgAdminFor(
|
||||
async (id) => (await repository.fetchCounterpartyById(id))?.organizationId ?? null,
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { NextFunction, Request, Response } from 'express'
|
||||
import { ORG_ADMIN_ROLES, type OrgRole } from '../../organizations/types'
|
||||
import { parsePositiveInt } from '../../../utils/helpers'
|
||||
|
||||
export type OrganizationIdResolver = (id: number) => Promise<number | null>
|
||||
|
||||
export const isOrgAdminFor = (resolveOrganizationId: OrganizationIdResolver) => {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
const id = parsePositiveInt(req.params.id)
|
||||
if (id === null) return res.status(400).end()
|
||||
|
||||
const organizationId = await resolveOrganizationId(id)
|
||||
if (organizationId === null) return res.status(404).end()
|
||||
|
||||
const member = await req.appUser.organizationManager.getCurrentUserMember(organizationId)
|
||||
if (!member || !ORG_ADMIN_ROLES.includes(member.role as OrgRole)) return res.status(403).end()
|
||||
|
||||
return next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { type } from 'arktype'
|
||||
import type {
|
||||
BillingBankDetails,
|
||||
BillingRequisite,
|
||||
CounterpartiesSchemaTypeForSelect,
|
||||
SellersSchemaTypeForSelect,
|
||||
} from 'taskview-db-schemas'
|
||||
|
||||
const NumberFromString = type('string|number').pipe((v) => Number(v))
|
||||
const BooleanFromString = type('string|boolean|undefined').pipe((v) => {
|
||||
if (v === undefined) return undefined
|
||||
if (typeof v === 'boolean') return v
|
||||
return v === 'true' || v === '1'
|
||||
})
|
||||
|
||||
export const RequisiteArkType = type({
|
||||
key: 'string<=64',
|
||||
label: 'string<=100',
|
||||
value: 'string<=300',
|
||||
})
|
||||
|
||||
export const BankDetailsArkType = type({
|
||||
bankName: 'string<=200',
|
||||
accountNumber: 'string<=64',
|
||||
iban: 'string<=64',
|
||||
swift: 'string<=32',
|
||||
correspondentAccount: 'string<=64',
|
||||
})
|
||||
|
||||
export const SellerArkTypeCreate = type({
|
||||
organizationId: 'number',
|
||||
name: '1<=string<=200',
|
||||
legalName: 'string<=300',
|
||||
address: 'string<=1000',
|
||||
email: 'string<=320',
|
||||
phone: 'string<=50',
|
||||
logoUrl: 'string<=1000',
|
||||
currencyCode: /^[A-Z]{3}$/,
|
||||
bank: BankDetailsArkType,
|
||||
requisites: RequisiteArkType.array(),
|
||||
defaultTerms: 'string<=2000',
|
||||
taxNote: 'string<=500',
|
||||
})
|
||||
export type SellerArgCreate = typeof SellerArkTypeCreate.infer
|
||||
|
||||
export const SellerArkTypeUpdate = SellerArkTypeCreate.omit('organizationId')
|
||||
export type SellerArgUpdate = typeof SellerArkTypeUpdate.infer
|
||||
|
||||
export const CounterpartyArkTypeCreate = type({
|
||||
organizationId: 'number',
|
||||
kind: "'organization' | 'person'",
|
||||
name: '1<=string<=200',
|
||||
legalName: 'string<=300',
|
||||
address: 'string<=1000',
|
||||
email: 'string<=320',
|
||||
phone: 'string<=50',
|
||||
contactPerson: 'string<=200',
|
||||
requisites: RequisiteArkType.array(),
|
||||
})
|
||||
export type CounterpartyArgCreate = typeof CounterpartyArkTypeCreate.infer
|
||||
|
||||
export const CounterpartyArkTypeUpdate = CounterpartyArkTypeCreate.omit('organizationId')
|
||||
export type CounterpartyArgUpdate = typeof CounterpartyArkTypeUpdate.infer
|
||||
|
||||
export const BillingArkTypeList = type({
|
||||
organizationId: NumberFromString,
|
||||
'includeArchived?': BooleanFromString,
|
||||
})
|
||||
export type BillingArgList = typeof BillingArkTypeList.infer
|
||||
|
||||
export const BillingArkTypeId = type({
|
||||
id: NumberFromString,
|
||||
})
|
||||
|
||||
export const BillingArkTypeArchive = type({
|
||||
archived: 'boolean',
|
||||
})
|
||||
|
||||
export type SellerUpdateArgs = {
|
||||
sellerId: number
|
||||
data: SellerArgUpdate
|
||||
}
|
||||
|
||||
export type CounterpartyUpdateArgs = {
|
||||
counterpartyId: number
|
||||
data: CounterpartyArgUpdate
|
||||
}
|
||||
|
||||
export type SetArchivedArgs = {
|
||||
id: number
|
||||
archived: boolean
|
||||
}
|
||||
|
||||
export type SellerForClient = Omit<SellersSchemaTypeForSelect, 'bank' | 'requisites'> & {
|
||||
bank: BillingBankDetails
|
||||
requisites: BillingRequisite[]
|
||||
}
|
||||
|
||||
export type CounterpartyForClient = Omit<CounterpartiesSchemaTypeForSelect, 'requisites'> & {
|
||||
requisites: BillingRequisite[]
|
||||
}
|
||||
|
||||
export type DeleteResult = 'deleted' | 'in_use' | 'not_found'
|
||||
+2
-1
@@ -5,7 +5,8 @@ import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
export const CanFetchRolesPermissionsCollaborationRoles = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const goalId = req.body.goalId ? req.body.goalId : req.params.goalId;
|
||||
// the only route using this guard names the goal in the path
|
||||
const goalId = req.params.goalId;
|
||||
|
||||
if (!goalId) {
|
||||
return res.status(400).end();
|
||||
|
||||
@@ -5,7 +5,7 @@ import { IsOrgMemberIfProvided } from '../../middlewares/is-org-member';
|
||||
import { CollaborationController } from './CollaborationController';
|
||||
import { CanAddUserCollaboration } from './middlewares/CanAddUserCollaboration';
|
||||
import { CanDeleteUserCollaboration } from './middlewares/CanDeleteUserCollaboration';
|
||||
// import { CanFetchUsersCollaboration } from './middlewares/CanFetchUsersCollaboration';
|
||||
import { CanFetchUsersCollaboration } from './middlewares/CanFetchUsersCollaboration';
|
||||
import { CanToggleRolesCollaboration } from './middlewares/CanToggleRolesCollaboration';
|
||||
|
||||
export default class CollaborationRoutes implements Routable {
|
||||
@@ -56,6 +56,10 @@ export default class CollaborationRoutes implements Routable {
|
||||
/**
|
||||
* Fetch users for goal for collaboration
|
||||
*/
|
||||
this.router.get('/:goalId', [IsLoggedIn], this.collaborationController.fetchUsersForGoalNew);
|
||||
this.router.get(
|
||||
'/:goalId',
|
||||
[IsLoggedIn, CanFetchUsersCollaboration],
|
||||
this.collaborationController.fetchUsersForGoalNew
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,8 @@ export const CanFetchUsersCollaboration = async (req: Request, res: Response, ne
|
||||
|
||||
if (
|
||||
permissions.hasPermissions(GoalPermissions.TASKS_CAN_ASSIGN_USERS) ||
|
||||
permissions.hasPermissions(GoalPermissions.GOAL_CAN_MANAGE_USERS)
|
||||
permissions.hasPermissions(GoalPermissions.GOAL_CAN_MANAGE_USERS) ||
|
||||
permissions.hasPermissions(GoalPermissions.TASKS_CAN_WATCH_ASSIGNED_USERS)
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
@@ -33,6 +33,15 @@ export class GraphController {
|
||||
return res.tvJson(edges);
|
||||
};
|
||||
|
||||
fetchTaskEdges = async (req: Request, res: Response) => {
|
||||
const taskId = Number(req.params.taskId);
|
||||
if (!Number.isFinite(taskId)) {
|
||||
return res.status(400).send('Task ID is required');
|
||||
}
|
||||
const edges = await req.appUser.graphManager.fetchEdgesForTask(taskId);
|
||||
return res.tvJson(edges);
|
||||
};
|
||||
|
||||
deleteEdge = async (req: Request, res: Response) => {
|
||||
if (!req.params.id) {
|
||||
return res.status(400).send('Edge ID is required');
|
||||
|
||||
@@ -19,6 +19,10 @@ export class GraphManager {
|
||||
return await this.repository.fetchAllEdges(goalId);
|
||||
}
|
||||
|
||||
async fetchEdgesForTask(taskId: number) {
|
||||
return await this.repository.fetchEdgesForTask(taskId);
|
||||
}
|
||||
|
||||
async deleteEdge(id: number) {
|
||||
return await this.repository.deleteEdge(id);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { eq, or } from 'drizzle-orm';
|
||||
import { GraphRelationsSchema } from 'taskview-db-schemas';
|
||||
import { Database } from '../../modules/db';
|
||||
import { callWithCatch } from '../../utils/helpers';
|
||||
@@ -32,6 +32,16 @@ export class GraphRepository {
|
||||
return result ?? [];
|
||||
}
|
||||
|
||||
public async fetchEdgesForTask(taskId: number): Promise<GraphReturnRelationsType[]> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select()
|
||||
.from(GraphRelationsSchema)
|
||||
.where(or(eq(GraphRelationsSchema.fromTaskId, taskId), eq(GraphRelationsSchema.toTaskId, taskId)))
|
||||
);
|
||||
return result ?? [];
|
||||
}
|
||||
|
||||
public async deleteEdge(id: number): Promise<boolean> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.delete(GraphRelationsSchema).where(eq(GraphRelationsSchema.id, id))
|
||||
|
||||
@@ -21,6 +21,7 @@ export default class GraphRoutes implements Routable {
|
||||
|
||||
initRoutes() {
|
||||
this.router.post('', [IsLoggedIn, CanManageGraph], this.graphController.addEdge);
|
||||
this.router.get('/task/:taskId', [IsLoggedIn, CanViewGraph], this.graphController.fetchTaskEdges);
|
||||
this.router.get('/:goalId', [IsLoggedIn, CanViewGraph], this.graphController.fetchAllEdges);
|
||||
this.router.delete('/:id', [IsLoggedIn, CanManageGraph], this.graphController.deleteEdge);
|
||||
}
|
||||
|
||||
@@ -3,28 +3,32 @@ import { GraphRepository } from '../GraphRepository';
|
||||
import { TasksRepository } from '../../tasks/TasksRepository';
|
||||
|
||||
/**
|
||||
* Resolves goalId from graph request.
|
||||
* - GET /:goalId → params.goalId
|
||||
* - POST (addEdge) → resolve via fromTaskId (body.source)
|
||||
* - DELETE /:id → resolve via edge id
|
||||
* Resolves the single goal a graph request belongs to.
|
||||
*
|
||||
* The source is chosen by what the route actually carries, not by probing every
|
||||
* field in turn: a route parameter always wins, and only a request with no
|
||||
* parameters at all (addEdge) is resolved from the body. Reading the body first
|
||||
* would let a caller point the guard at a task they own while the handler acts
|
||||
* on someone else's edge.
|
||||
*
|
||||
* A graph lives inside one project, so an edge whose endpoints sit in different
|
||||
* goals is not a permission question — it is an impossible object. It resolves
|
||||
* to null and the guards reject it before any permission is considered, the same
|
||||
* invariant the tasks.check_task_graph_relation_goal trigger enforces in the DB.
|
||||
*/
|
||||
export async function resolveGoalId(req: Request): Promise<number | null> {
|
||||
// Direct goalId in params (fetchAllEdges)
|
||||
// fetchAllEdges: GET /:goalId
|
||||
if (req.params.goalId) {
|
||||
const id = Number(req.params.goalId);
|
||||
return isNaN(id) ? null : id;
|
||||
const goalId = Number(req.params.goalId);
|
||||
return isNaN(goalId) ? null : goalId;
|
||||
}
|
||||
|
||||
// addEdge: resolve goalId from task
|
||||
if (req.body?.source) {
|
||||
const taskId = Number(req.body.source);
|
||||
if (isNaN(taskId)) return null;
|
||||
const tasksRepo = new TasksRepository();
|
||||
const task = await tasksRepo.fetchTaskByIdNew(taskId);
|
||||
return task?.goalId ?? null;
|
||||
// fetchTaskEdges: GET /task/:taskId
|
||||
if (req.params.taskId) {
|
||||
return goalIdForTask(req.params.taskId);
|
||||
}
|
||||
|
||||
// deleteEdge: resolve goalId from edge
|
||||
// deleteEdge: DELETE /:id
|
||||
if (req.params.id) {
|
||||
const edgeId = Number(req.params.id);
|
||||
if (isNaN(edgeId)) return null;
|
||||
@@ -33,5 +37,25 @@ export async function resolveGoalId(req: Request): Promise<number | null> {
|
||||
return edge?.goalId ?? null;
|
||||
}
|
||||
|
||||
// addEdge: POST with { source, target } — both endpoints must be in one goal
|
||||
if (req.body?.source) {
|
||||
const sourceGoalId = await goalIdForTask(req.body.source);
|
||||
if (sourceGoalId === null) return null;
|
||||
|
||||
const targetGoalId = await goalIdForTask(req.body.target);
|
||||
if (targetGoalId !== sourceGoalId) return null;
|
||||
|
||||
return sourceGoalId;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function goalIdForTask(rawTaskId: unknown): Promise<number | null> {
|
||||
const taskId = Number(rawTaskId);
|
||||
if (!taskId || isNaN(taskId)) return null;
|
||||
|
||||
const tasksRepo = new TasksRepository();
|
||||
const task = await tasksRepo.fetchTaskByIdNew(taskId);
|
||||
return task?.goalId ?? null;
|
||||
}
|
||||
|
||||
@@ -2,22 +2,26 @@ import type { Request } from 'express';
|
||||
import { IntegrationsRepository } from '../IntegrationsRepository';
|
||||
|
||||
/**
|
||||
* Resolves projectId from request.
|
||||
* Checks body (projectId, integrationId, id) and query (projectId, integrationId).
|
||||
* Resolves the project to authorize the request against.
|
||||
*
|
||||
* When the request names an integration, the project is derived from that
|
||||
* integration and a projectId supplied by the caller is ignored: every handler
|
||||
* that takes an integration id acts on the integration, so authorizing a
|
||||
* caller-supplied project would guard a different object than the one touched.
|
||||
*
|
||||
* Only create and fetch carry no integration id — there the project itself is
|
||||
* the object being acted on, so it is read from the request.
|
||||
*/
|
||||
export async function resolveProjectId(req: Request): Promise<number | null> {
|
||||
// Direct projectId in body or query
|
||||
const directId = req.body?.projectId ?? req.query?.projectId;
|
||||
if (directId) {
|
||||
const id = Number(directId);
|
||||
return isNaN(id) ? null : id;
|
||||
const integrationId = Number(req.body?.integrationId || req.query?.integrationId || req.body?.id);
|
||||
if (integrationId && !isNaN(integrationId)) {
|
||||
const repo = new IntegrationsRepository();
|
||||
const integration = await repo.fetchById(integrationId);
|
||||
return integration?.projectId ?? null;
|
||||
}
|
||||
|
||||
// integrationId from body or query, or id from body
|
||||
const integrationId = Number(req.body?.integrationId || req.query?.integrationId || req.body?.id);
|
||||
if (!integrationId || isNaN(integrationId)) return null;
|
||||
const projectId = Number(req.body?.projectId || req.query?.projectId);
|
||||
if (!projectId || isNaN(projectId)) return null;
|
||||
|
||||
const repo = new IntegrationsRepository();
|
||||
const integration = await repo.fetchById(integrationId);
|
||||
return integration?.projectId ?? null;
|
||||
return projectId;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
import pdfmakeModule from 'pdfmake'
|
||||
import vfs from 'pdfmake/build/vfs_fonts.js'
|
||||
import { invoiceLineAmount } from '../../utils/invoiceTotals'
|
||||
import type { InvoiceForClient, InvoicePdfLang, PdfmakeServer } from './types'
|
||||
|
||||
const LABELS: Record<InvoicePdfLang, Record<string, string>> = {
|
||||
en: {
|
||||
title: 'INVOICE',
|
||||
void: 'VOID',
|
||||
issueDate: 'Issue date',
|
||||
dueDate: 'Due date',
|
||||
reference: 'Reference',
|
||||
period: 'Period',
|
||||
replaces: 'Replaces',
|
||||
billTo: 'Bill to',
|
||||
description: 'Description',
|
||||
qty: 'Qty',
|
||||
unit: 'Unit',
|
||||
price: 'Price',
|
||||
amount: 'Amount',
|
||||
subtotal: 'Subtotal',
|
||||
discount: 'Discount',
|
||||
tax: 'Tax',
|
||||
total: 'Total',
|
||||
paymentDetails: 'Payment details',
|
||||
bankName: 'Bank',
|
||||
accountNumber: 'Account',
|
||||
iban: 'IBAN',
|
||||
swift: 'SWIFT / BIC',
|
||||
correspondentAccount: 'Correspondent account',
|
||||
service: 'service',
|
||||
hours: 'h',
|
||||
pcs: 'pcs',
|
||||
},
|
||||
ru: {
|
||||
title: 'СЧЁТ',
|
||||
void: 'АННУЛИРОВАН',
|
||||
issueDate: 'Дата выставления',
|
||||
dueDate: 'Срок оплаты',
|
||||
reference: 'Основание',
|
||||
period: 'Период',
|
||||
replaces: 'Взамен',
|
||||
billTo: 'Плательщик',
|
||||
description: 'Описание',
|
||||
qty: 'Кол-во',
|
||||
unit: 'Ед.',
|
||||
price: 'Цена',
|
||||
amount: 'Сумма',
|
||||
subtotal: 'Промежуточная сумма',
|
||||
discount: 'Скидка',
|
||||
tax: 'Налог',
|
||||
total: 'Итого',
|
||||
paymentDetails: 'Реквизиты для оплаты',
|
||||
bankName: 'Банк',
|
||||
accountNumber: 'Расчётный счёт',
|
||||
iban: 'IBAN',
|
||||
swift: 'SWIFT / БИК',
|
||||
correspondentAccount: 'Корр. счёт',
|
||||
service: 'усл.',
|
||||
hours: 'ч',
|
||||
pcs: 'шт.',
|
||||
},
|
||||
}
|
||||
|
||||
const FONT_FILES = ['Roboto-Regular.ttf', 'Roboto-Medium.ttf', 'Roboto-Italic.ttf', 'Roboto-MediumItalic.ttf']
|
||||
const MUTED = '#6b7280'
|
||||
const RULE = '#d4d4d8'
|
||||
|
||||
export class InvoicePdfRenderer {
|
||||
private static fontsReady = false
|
||||
private readonly pdfmake = pdfmakeModule as unknown as PdfmakeServer
|
||||
|
||||
constructor() {
|
||||
if (!InvoicePdfRenderer.fontsReady) {
|
||||
for (const name of FONT_FILES) this.pdfmake.virtualfs.writeFileSync(name, Buffer.from(vfs[name], 'base64'))
|
||||
this.pdfmake.setFonts({
|
||||
Roboto: {
|
||||
normal: 'Roboto-Regular.ttf',
|
||||
bold: 'Roboto-Medium.ttf',
|
||||
italics: 'Roboto-Italic.ttf',
|
||||
bolditalics: 'Roboto-MediumItalic.ttf',
|
||||
},
|
||||
})
|
||||
InvoicePdfRenderer.fontsReady = true
|
||||
}
|
||||
}
|
||||
|
||||
render(invoice: InvoiceForClient, lang: InvoicePdfLang): Promise<Buffer> {
|
||||
return this.pdfmake.createPdf(this.buildDocument(invoice, lang)).getBuffer()
|
||||
}
|
||||
|
||||
private buildDocument(invoice: InvoiceForClient, lang: InvoicePdfLang) {
|
||||
const t = LABELS[lang]
|
||||
const money = (amount: number) => this.formatMoney(amount, invoice.currencyCode, lang)
|
||||
const date = (value: string | null) => this.formatDate(value, lang)
|
||||
|
||||
const metaRows: [string, string][] = [[t.issueDate, date(invoice.issueDate)]]
|
||||
if (invoice.dueDate) metaRows.push([t.dueDate, date(invoice.dueDate)])
|
||||
if (invoice.reference) metaRows.push([t.reference, invoice.reference])
|
||||
if (invoice.periodFrom || invoice.periodTo) metaRows.push([t.period, `${date(invoice.periodFrom)} – ${date(invoice.periodTo)}`])
|
||||
|
||||
const lineRows = invoice.lines.map((line) => [
|
||||
{ text: line.description },
|
||||
{ text: String(line.quantity), alignment: 'right' },
|
||||
{ text: t[line.unit] ?? line.unit, color: MUTED },
|
||||
{ text: money(line.unitPrice), alignment: 'right' },
|
||||
{ text: money(invoiceLineAmount(line.quantity, line.unitPrice)), alignment: 'right' },
|
||||
])
|
||||
|
||||
const totalsRows: unknown[] = [[{ text: t.subtotal, color: MUTED }, { text: money(invoice.totals.subtotal), alignment: 'right' }]]
|
||||
if (invoice.totals.discount > 0) totalsRows.push([{ text: t.discount, color: MUTED }, { text: `−${money(invoice.totals.discount)}`, alignment: 'right' }])
|
||||
if (!invoice.taxExempt) totalsRows.push([{ text: `${t.tax} ${invoice.taxRate}%`, color: MUTED }, { text: money(invoice.totals.tax), alignment: 'right' }])
|
||||
totalsRows.push([{ text: t.total, bold: true, fontSize: 12 }, { text: money(invoice.totals.total), bold: true, fontSize: 12, alignment: 'right' }])
|
||||
|
||||
const bank = invoice.seller.bank
|
||||
const bankRows = (
|
||||
[
|
||||
[t.bankName, bank.bankName],
|
||||
[t.accountNumber, bank.accountNumber],
|
||||
[t.iban, bank.iban],
|
||||
[t.swift, bank.swift],
|
||||
[t.correspondentAccount, bank.correspondentAccount],
|
||||
] as [string, string][]
|
||||
).filter(([, value]) => value.trim().length > 0)
|
||||
|
||||
const content: unknown[] = [
|
||||
{
|
||||
columns: [
|
||||
{
|
||||
width: '*',
|
||||
stack: [
|
||||
{ text: invoice.seller.legalName || invoice.seller.name, fontSize: 14, bold: true },
|
||||
...this.partyLines(invoice.seller),
|
||||
],
|
||||
},
|
||||
{
|
||||
width: 'auto',
|
||||
stack: [
|
||||
{ text: t.title, fontSize: 20, bold: true, alignment: 'right' },
|
||||
{ text: invoice.number, alignment: 'right', margin: [0, 2, 0, 8] },
|
||||
{
|
||||
table: { body: metaRows.map(([label, value]) => [{ text: label, color: MUTED }, { text: value, alignment: 'right' }]) },
|
||||
layout: 'noBorders',
|
||||
fontSize: 9,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
columnGap: 24,
|
||||
},
|
||||
{ canvas: [{ type: 'line', x1: 0, y1: 0, x2: 515, y2: 0, lineWidth: 0.5, lineColor: RULE }], margin: [0, 12, 0, 12] },
|
||||
{ text: t.billTo.toUpperCase(), fontSize: 8, bold: true, color: MUTED },
|
||||
{ text: invoice.counterparty.legalName || invoice.counterparty.name, bold: true, margin: [0, 2, 0, 0] },
|
||||
...(invoice.counterparty.contactPerson ? [{ text: invoice.counterparty.contactPerson }] : []),
|
||||
...this.partyLines(invoice.counterparty),
|
||||
{
|
||||
table: {
|
||||
headerRows: 1,
|
||||
widths: ['*', 40, 44, 80, 90],
|
||||
body: [
|
||||
[
|
||||
{ text: t.description.toUpperCase(), style: 'th' },
|
||||
{ text: t.qty.toUpperCase(), style: 'th', alignment: 'right' },
|
||||
{ text: t.unit.toUpperCase(), style: 'th' },
|
||||
{ text: t.price.toUpperCase(), style: 'th', alignment: 'right' },
|
||||
{ text: t.amount.toUpperCase(), style: 'th', alignment: 'right' },
|
||||
],
|
||||
...lineRows,
|
||||
],
|
||||
},
|
||||
layout: {
|
||||
hLineWidth: (index: number, node: { table: { body: unknown[] } }) => (index === 0 || index === node.table.body.length ? 0 : 0.5),
|
||||
vLineWidth: () => 0,
|
||||
hLineColor: () => RULE,
|
||||
paddingTop: () => 6,
|
||||
paddingBottom: () => 6,
|
||||
},
|
||||
margin: [0, 18, 0, 8],
|
||||
},
|
||||
{
|
||||
columns: [
|
||||
{ width: '*', text: '' },
|
||||
{ width: 220, table: { widths: ['*', 'auto'], body: totalsRows }, layout: 'noBorders' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
if (bankRows.length > 0) {
|
||||
content.push(
|
||||
{ text: t.paymentDetails.toUpperCase(), fontSize: 8, bold: true, color: MUTED, margin: [0, 20, 0, 4] },
|
||||
{ table: { body: bankRows.map(([label, value]) => [{ text: label, color: MUTED }, { text: value }]) }, layout: 'noBorders' },
|
||||
)
|
||||
}
|
||||
if (invoice.taxExempt && invoice.taxNote) content.push({ text: invoice.taxNote, margin: [0, 16, 0, 0], color: '#374151' })
|
||||
if (invoice.terms) content.push({ text: invoice.terms, margin: [0, 8, 0, 0], color: '#374151' })
|
||||
if (invoice.notes) content.push({ text: invoice.notes, margin: [0, 8, 0, 0], color: '#374151' })
|
||||
|
||||
return {
|
||||
pageSize: 'A4',
|
||||
pageMargins: [40, 40, 40, 40],
|
||||
info: { title: invoice.number },
|
||||
...(invoice.status === 'void' ? { watermark: { text: t.void, color: '#ef4444', opacity: 0.12, bold: true } } : {}),
|
||||
defaultStyle: { font: 'Roboto', fontSize: 10, color: '#18181b' },
|
||||
styles: { th: { fontSize: 8, bold: true, color: MUTED } },
|
||||
content,
|
||||
}
|
||||
}
|
||||
|
||||
private partyLines(party: InvoiceForClient['seller'] | InvoiceForClient['counterparty']) {
|
||||
const lines: unknown[] = []
|
||||
if (party.address) lines.push({ text: party.address, color: MUTED, fontSize: 9 })
|
||||
for (const item of party.requisites) {
|
||||
if (item.label.trim() && item.value.trim()) lines.push({ text: `${item.label}: ${item.value}`, color: MUTED, fontSize: 9 })
|
||||
}
|
||||
const contacts = [party.email, party.phone].filter(Boolean).join(' · ')
|
||||
if (contacts) lines.push({ text: contacts, color: MUTED, fontSize: 9 })
|
||||
return lines
|
||||
}
|
||||
|
||||
private formatMoney(amount: number, currencyCode: string, lang: InvoicePdfLang): string {
|
||||
try {
|
||||
return new Intl.NumberFormat(lang === 'ru' ? 'ru-RU' : 'en-US', { style: 'currency', currency: currencyCode }).format(amount)
|
||||
} catch {
|
||||
return `${amount.toFixed(2)} ${currencyCode}`
|
||||
}
|
||||
}
|
||||
|
||||
private formatDate(value: string | null, lang: InvoicePdfLang): string {
|
||||
if (!value) return ''
|
||||
const [year, month, day] = value.split('-')
|
||||
return lang === 'ru' ? `${day}.${month}.${year}` : `${day}.${month}.${year}`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { Request, Response } from 'express'
|
||||
import { ArkErrors } from 'arktype'
|
||||
import { InvoicesManager } from './InvoicesManager'
|
||||
import {
|
||||
InvoiceArkTypeCreate,
|
||||
InvoiceArkTypeId,
|
||||
InvoiceArkTypeList,
|
||||
InvoiceArkTypePdf,
|
||||
InvoiceArkTypeStatus,
|
||||
InvoiceArkTypeUpdate,
|
||||
type InvoiceDeleteResult,
|
||||
type InvoiceTransitionResult,
|
||||
type InvoiceWriteError,
|
||||
} from './types'
|
||||
|
||||
const WRITE_ERROR_STATUS: Record<InvoiceWriteError, number> = {
|
||||
seller_not_found: 422,
|
||||
counterparty_not_found: 422,
|
||||
goal_not_found: 422,
|
||||
duplicate_number: 409,
|
||||
not_found: 404,
|
||||
not_draft: 409,
|
||||
}
|
||||
|
||||
const TRANSITION_ERROR_STATUS = { not_found: 404, invalid_transition: 409, missing_requisites: 422 } as const
|
||||
|
||||
const DELETE_STATUS: Record<InvoiceDeleteResult, number> = { deleted: 200, not_draft: 409, not_found: 404 }
|
||||
|
||||
export class InvoicesController {
|
||||
private readonly manager = new InvoicesManager()
|
||||
|
||||
fetch = async (req: Request, res: Response) => {
|
||||
const data = InvoiceArkTypeList(req.query)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
return res.tvJson(await this.manager.fetchList(data))
|
||||
}
|
||||
|
||||
getById = async (req: Request, res: Response) => {
|
||||
const id = InvoiceArkTypeId(req.params)
|
||||
if (id instanceof ArkErrors) return res.status(400).send(id.summary)
|
||||
const result = await this.manager.fetchById(id.id)
|
||||
if (!result) return res.status(404).end()
|
||||
return res.tvJson(result)
|
||||
}
|
||||
|
||||
create = async (req: Request, res: Response) => {
|
||||
const data = InvoiceArkTypeCreate(req.body)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
const result = await this.manager.create({ data, createdBy: req.appUser.getUserData()?.id ?? null })
|
||||
if ('error' in result) return res.status(WRITE_ERROR_STATUS[result.error]).send(result.error)
|
||||
return res.tvJson(result.invoice)
|
||||
}
|
||||
|
||||
update = async (req: Request, res: Response) => {
|
||||
const id = InvoiceArkTypeId(req.params)
|
||||
const data = InvoiceArkTypeUpdate(req.body)
|
||||
if (id instanceof ArkErrors) return res.status(400).send(id.summary)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
const result = await this.manager.update({ invoiceId: id.id, data })
|
||||
if ('error' in result) return res.status(WRITE_ERROR_STATUS[result.error]).send(result.error)
|
||||
return res.tvJson(result.invoice)
|
||||
}
|
||||
|
||||
setStatus = async (req: Request, res: Response) => {
|
||||
const id = InvoiceArkTypeId(req.params)
|
||||
const data = InvoiceArkTypeStatus(req.body)
|
||||
if (id instanceof ArkErrors) return res.status(400).send(id.summary)
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
return this.sendTransition(res, await this.manager.transition({ invoiceId: id.id, status: data.status }))
|
||||
}
|
||||
|
||||
reissue = async (req: Request, res: Response) => {
|
||||
const id = InvoiceArkTypeId(req.params)
|
||||
if (id instanceof ArkErrors) return res.status(400).send(id.summary)
|
||||
const result = await this.manager.reissue({ invoiceId: id.id, createdBy: req.appUser.getUserData()?.id ?? null })
|
||||
return this.sendTransition(res, result)
|
||||
}
|
||||
|
||||
pdf = async (req: Request, res: Response) => {
|
||||
const data = InvoiceArkTypePdf({ ...req.params, ...req.query })
|
||||
if (data instanceof ArkErrors) return res.status(400).send(data.summary)
|
||||
const invoice = await this.manager.fetchById(data.id)
|
||||
if (!invoice) return res.status(404).end()
|
||||
const buffer = await this.manager.renderPdf({ invoiceId: data.id, lang: data.lang ?? 'en' })
|
||||
if (!buffer) return res.status(404).end()
|
||||
res.setHeader('Content-Type', 'application/pdf')
|
||||
res.setHeader('Content-Disposition', `inline; filename="${encodeURIComponent(invoice.number)}.pdf"`)
|
||||
return res.send(buffer)
|
||||
}
|
||||
|
||||
private sendTransition(res: Response, result: InvoiceTransitionResult) {
|
||||
if ('error' in result) return res.status(TRANSITION_ERROR_STATUS[result.error]).json(result)
|
||||
return res.tvJson(result.invoice)
|
||||
}
|
||||
|
||||
delete = async (req: Request, res: Response) => {
|
||||
const id = InvoiceArkTypeId(req.params)
|
||||
if (id instanceof ArkErrors) return res.status(400).send(id.summary)
|
||||
const result = await this.manager.delete(id.id)
|
||||
if (result !== 'deleted') return res.status(DELETE_STATUS[result]).end()
|
||||
return res.tvJson(true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import type {
|
||||
CounterpartiesSchemaTypeForSelect,
|
||||
InvoiceCounterpartySnapshot,
|
||||
InvoiceSellerSnapshot,
|
||||
InvoiceStatus,
|
||||
SellersSchemaTypeForSelect,
|
||||
} from 'taskview-db-schemas'
|
||||
import { BillingRepository } from '../billing/BillingRepository'
|
||||
import { computeInvoiceTotals } from '../../utils/invoiceTotals'
|
||||
import { InvoicePdfRenderer } from './InvoicePdfRenderer'
|
||||
import { InvoicesRepository } from './InvoicesRepository'
|
||||
import {
|
||||
INVOICE_TEMPLATE_VERSION,
|
||||
INVOICE_TRANSITIONS,
|
||||
type InvoiceArgList,
|
||||
type InvoiceArgUpdate,
|
||||
type InvoiceCreateArgs,
|
||||
type InvoiceDeleteResult,
|
||||
type InvoiceForClient,
|
||||
type InvoiceMissingRequisite,
|
||||
type InvoiceReissueArgs,
|
||||
type InvoiceRenderPdfArgs,
|
||||
type InvoiceSetStatusArgs,
|
||||
type InvoiceSnapshots,
|
||||
type InvoiceStatusPatch,
|
||||
type InvoiceTransitionResult,
|
||||
type InvoiceUpdateArgs,
|
||||
type InvoiceWithLines,
|
||||
type InvoiceWriteError,
|
||||
type InvoiceWriteResult,
|
||||
} from './types'
|
||||
|
||||
export class InvoicesManager {
|
||||
public readonly repository: InvoicesRepository
|
||||
private readonly billing: BillingRepository
|
||||
private readonly pdf: InvoicePdfRenderer
|
||||
|
||||
constructor() {
|
||||
this.repository = new InvoicesRepository()
|
||||
this.billing = new BillingRepository()
|
||||
this.pdf = new InvoicePdfRenderer()
|
||||
}
|
||||
|
||||
async fetchList(args: InvoiceArgList): Promise<InvoiceForClient[]> {
|
||||
return (await this.repository.fetchList(args)).map((invoice) => this.toClient(invoice))
|
||||
}
|
||||
|
||||
async fetchById(invoiceId: number): Promise<InvoiceForClient | null> {
|
||||
const invoice = await this.repository.fetchById(invoiceId)
|
||||
return invoice ? this.toClient(invoice) : null
|
||||
}
|
||||
|
||||
async create({ data, createdBy }: InvoiceCreateArgs): Promise<InvoiceWriteResult> {
|
||||
const snapshots = await this.resolveSnapshots(data.organizationId, data)
|
||||
if (typeof snapshots === 'string') return { error: snapshots }
|
||||
const created = await this.repository.create({ data, createdBy, ...snapshots })
|
||||
return this.toWriteResult(created)
|
||||
}
|
||||
|
||||
async update({ invoiceId, data }: InvoiceUpdateArgs): Promise<InvoiceWriteResult> {
|
||||
const existing = await this.repository.fetchById(invoiceId)
|
||||
if (!existing) return { error: 'not_found' }
|
||||
if (existing.status !== 'draft') return { error: 'not_draft' }
|
||||
const snapshots = await this.resolveSnapshots(existing.organizationId, data)
|
||||
if (typeof snapshots === 'string') return { error: snapshots }
|
||||
const updated = await this.repository.update({ invoiceId, data, ...snapshots })
|
||||
return this.toWriteResult(updated)
|
||||
}
|
||||
|
||||
async transition({ invoiceId, status }: InvoiceSetStatusArgs): Promise<InvoiceTransitionResult> {
|
||||
const existing = await this.repository.fetchById(invoiceId)
|
||||
if (!existing) return { error: 'not_found' }
|
||||
if (!INVOICE_TRANSITIONS[existing.status].includes(status)) {
|
||||
return { error: 'invalid_transition', from: existing.status, to: status }
|
||||
}
|
||||
|
||||
const patch: InvoiceStatusPatch = { status }
|
||||
if (status === 'issued' && existing.status === 'draft') {
|
||||
const missing = this.missingRequisites(existing)
|
||||
if (missing.length > 0) return { error: 'missing_requisites', missing }
|
||||
const totals = computeInvoiceTotals(existing)
|
||||
patch.issuedAt = new Date()
|
||||
patch.templateVersion = INVOICE_TEMPLATE_VERSION
|
||||
patch.subtotal = String(totals.subtotal)
|
||||
patch.discountAmount = String(totals.discount)
|
||||
patch.taxAmount = String(totals.tax)
|
||||
patch.total = String(totals.total)
|
||||
}
|
||||
if (status === 'issued' && existing.status === 'paid') patch.paidAt = null
|
||||
if (status === 'paid') patch.paidAt = new Date()
|
||||
if (status === 'void') patch.voidedAt = new Date()
|
||||
|
||||
const updated = await this.repository.applyStatus({ invoiceId, patch })
|
||||
return updated ? { invoice: this.toClient(updated) } : { error: 'not_found' }
|
||||
}
|
||||
|
||||
async reissue({ invoiceId, createdBy }: InvoiceReissueArgs): Promise<InvoiceTransitionResult> {
|
||||
const original = await this.repository.fetchById(invoiceId)
|
||||
if (!original) return { error: 'not_found' }
|
||||
if (original.status === 'issued') {
|
||||
const voided = await this.transition({ invoiceId, status: 'void' })
|
||||
if ('error' in voided) return voided
|
||||
} else if (original.status !== 'void') {
|
||||
return { error: 'invalid_transition', from: original.status, to: 'void' }
|
||||
}
|
||||
|
||||
const number = await this.repository.nextNumber({ organizationId: original.organizationId, base: original.number })
|
||||
const created = await this.repository.create({
|
||||
createdBy,
|
||||
sellerSnapshot: original.sellerSnapshot,
|
||||
counterpartySnapshot: original.counterpartySnapshot,
|
||||
goalName: original.goalName,
|
||||
data: {
|
||||
organizationId: original.organizationId,
|
||||
goalId: original.goalId,
|
||||
sellerId: original.sellerId,
|
||||
counterpartyId: original.counterpartyId,
|
||||
number,
|
||||
reference: original.reference,
|
||||
currencyCode: original.currencyCode,
|
||||
issueDate: new Date().toISOString().slice(0, 10),
|
||||
paymentTerms: original.paymentTerms,
|
||||
dueDate: original.dueDate,
|
||||
periodFrom: original.periodFrom,
|
||||
periodTo: original.periodTo,
|
||||
discountType: original.discountType,
|
||||
discountValue: Number(original.discountValue),
|
||||
taxRate: Number(original.taxRate),
|
||||
taxExempt: original.taxExempt,
|
||||
taxNote: original.taxNote,
|
||||
notes: original.notes,
|
||||
terms: original.terms,
|
||||
lines: original.lines.map((line) => ({
|
||||
taskId: line.taskId,
|
||||
description: line.description,
|
||||
unit: line.unit,
|
||||
quantity: Number(line.quantity),
|
||||
unitPrice: Number(line.unitPrice),
|
||||
})),
|
||||
},
|
||||
})
|
||||
if (!created || created === 'duplicate_number') return { error: 'not_found' }
|
||||
await this.repository.setReplaces({ invoiceId: created.id, replacesInvoiceId: original.id })
|
||||
return { invoice: this.toClient({ ...created, replacesInvoiceId: original.id }) }
|
||||
}
|
||||
|
||||
async delete(invoiceId: number): Promise<InvoiceDeleteResult> {
|
||||
const existing = await this.repository.fetchById(invoiceId)
|
||||
if (!existing) return 'not_found'
|
||||
if (existing.status !== 'draft') return 'not_draft'
|
||||
return (await this.repository.delete(invoiceId)) ? 'deleted' : 'not_found'
|
||||
}
|
||||
|
||||
async renderPdf({ invoiceId, lang }: InvoiceRenderPdfArgs): Promise<Buffer | null> {
|
||||
const invoice = await this.fetchById(invoiceId)
|
||||
if (!invoice) return null
|
||||
return this.pdf.render(invoice, lang)
|
||||
}
|
||||
|
||||
private missingRequisites(invoice: InvoiceWithLines): InvoiceMissingRequisite[] {
|
||||
const seller = invoice.sellerSnapshot
|
||||
const counterparty = invoice.counterpartySnapshot
|
||||
const missing: InvoiceMissingRequisite[] = []
|
||||
if (!seller.name.trim() && !seller.legalName.trim()) missing.push('seller.name')
|
||||
if (!seller.address.trim()) missing.push('seller.address')
|
||||
if (!seller.bank.accountNumber.trim() && !seller.bank.iban.trim()) missing.push('seller.bank')
|
||||
if (!counterparty.name.trim() && !counterparty.legalName.trim()) missing.push('counterparty.name')
|
||||
if (!counterparty.address.trim()) missing.push('counterparty.address')
|
||||
if (invoice.lines.length === 0) missing.push('lines')
|
||||
return missing
|
||||
}
|
||||
|
||||
private async resolveSnapshots(organizationId: number, data: InvoiceArgUpdate): Promise<InvoiceSnapshots | InvoiceWriteError> {
|
||||
const seller = await this.billing.fetchSellerById(data.sellerId)
|
||||
if (!seller || seller.organizationId !== organizationId) return 'seller_not_found'
|
||||
const counterparty = await this.billing.fetchCounterpartyById(data.counterpartyId)
|
||||
if (!counterparty || counterparty.organizationId !== organizationId) return 'counterparty_not_found'
|
||||
let goalName = ''
|
||||
if (data.goalId !== null) {
|
||||
const goal = await this.repository.fetchGoal(data.goalId)
|
||||
if (!goal || goal.organizationId !== organizationId) return 'goal_not_found'
|
||||
goalName = goal.name ?? ''
|
||||
}
|
||||
return {
|
||||
sellerSnapshot: this.snapshotSeller(seller),
|
||||
counterpartySnapshot: this.snapshotCounterparty(counterparty),
|
||||
goalName,
|
||||
}
|
||||
}
|
||||
|
||||
private snapshotSeller(seller: SellersSchemaTypeForSelect): InvoiceSellerSnapshot {
|
||||
return {
|
||||
name: seller.name,
|
||||
legalName: seller.legalName,
|
||||
address: seller.address,
|
||||
email: seller.email,
|
||||
phone: seller.phone,
|
||||
logoUrl: seller.logoUrl,
|
||||
bank: seller.bank,
|
||||
requisites: seller.requisites,
|
||||
}
|
||||
}
|
||||
|
||||
private snapshotCounterparty(counterparty: CounterpartiesSchemaTypeForSelect): InvoiceCounterpartySnapshot {
|
||||
return {
|
||||
kind: counterparty.kind,
|
||||
name: counterparty.name,
|
||||
legalName: counterparty.legalName,
|
||||
address: counterparty.address,
|
||||
email: counterparty.email,
|
||||
phone: counterparty.phone,
|
||||
contactPerson: counterparty.contactPerson,
|
||||
requisites: counterparty.requisites,
|
||||
}
|
||||
}
|
||||
|
||||
private toWriteResult(result: InvoiceWithLines | 'duplicate_number' | null): InvoiceWriteResult {
|
||||
if (result === 'duplicate_number') return { error: 'duplicate_number' }
|
||||
if (!result) return { error: 'not_found' }
|
||||
return { invoice: this.toClient(result) }
|
||||
}
|
||||
|
||||
private toClient(invoice: InvoiceWithLines): InvoiceForClient {
|
||||
const { sellerSnapshot, counterpartySnapshot, lines, subtotal, discountAmount, taxAmount, total, ...rest } = invoice
|
||||
const totalsFrozen = total !== null
|
||||
const totals = totalsFrozen
|
||||
? {
|
||||
subtotal: Number(subtotal),
|
||||
discount: Number(discountAmount),
|
||||
taxable: Number(subtotal) - Number(discountAmount),
|
||||
tax: Number(taxAmount),
|
||||
total: Number(total),
|
||||
}
|
||||
: computeInvoiceTotals(invoice)
|
||||
return {
|
||||
...rest,
|
||||
discountValue: Number(invoice.discountValue),
|
||||
taxRate: Number(invoice.taxRate),
|
||||
seller: sellerSnapshot,
|
||||
counterparty: counterpartySnapshot,
|
||||
totals,
|
||||
totalsFrozen,
|
||||
lines: lines.map((line) => ({
|
||||
id: line.id,
|
||||
taskId: line.taskId,
|
||||
description: line.description,
|
||||
unit: line.unit,
|
||||
quantity: Number(line.quantity),
|
||||
unitPrice: Number(line.unitPrice),
|
||||
})),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type { InvoiceStatus }
|
||||
@@ -0,0 +1,228 @@
|
||||
import { and, asc, desc, eq, inArray } from 'drizzle-orm'
|
||||
import {
|
||||
CounterpartiesSchema,
|
||||
GoalsSchema,
|
||||
InvoiceLinesSchema,
|
||||
InvoicesSchema,
|
||||
type InvoiceLinesSchemaTypeForSelect,
|
||||
type InvoicesSchemaTypeForSelect,
|
||||
} from 'taskview-db-schemas'
|
||||
import { Database } from '../../modules/db'
|
||||
import { callWithCatch } from '../../utils/helpers'
|
||||
import type {
|
||||
InvoiceArgList,
|
||||
InvoiceArgUpdate,
|
||||
InvoiceCreateRepoArgs,
|
||||
InvoiceLineArg,
|
||||
InvoiceNextNumberArgs,
|
||||
InvoiceSetReplacesArgs,
|
||||
InvoiceStatusRepoArgs,
|
||||
InvoiceUpdateRepoArgs,
|
||||
InvoiceWithLines,
|
||||
} from './types'
|
||||
|
||||
const PG_UNIQUE_VIOLATION = '23505'
|
||||
|
||||
export class InvoicesRepository {
|
||||
private readonly db: Database
|
||||
|
||||
constructor() {
|
||||
this.db = Database.getInstance()
|
||||
}
|
||||
|
||||
async fetchList({ organizationId, includeArchived }: InvoiceArgList): Promise<InvoiceWithLines[]> {
|
||||
const conditions = [eq(InvoicesSchema.organizationId, organizationId)]
|
||||
if (!includeArchived) conditions.push(eq(CounterpartiesSchema.archived, false))
|
||||
const rows = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select({ invoice: InvoicesSchema })
|
||||
.from(InvoicesSchema)
|
||||
.innerJoin(CounterpartiesSchema, eq(CounterpartiesSchema.id, InvoicesSchema.counterpartyId))
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(InvoicesSchema.issueDate), desc(InvoicesSchema.id)),
|
||||
)
|
||||
const invoices = (rows ?? []).map((row) => row.invoice)
|
||||
return this.attachLines(invoices)
|
||||
}
|
||||
|
||||
async fetchById(invoiceId: number): Promise<InvoiceWithLines | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select().from(InvoicesSchema).where(eq(InvoicesSchema.id, invoiceId)),
|
||||
)
|
||||
const invoice = result?.[0]
|
||||
if (!invoice) return null
|
||||
return (await this.attachLines([invoice]))[0]
|
||||
}
|
||||
|
||||
async fetchOrganizationId(invoiceId: number): Promise<number | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select({ organizationId: InvoicesSchema.organizationId })
|
||||
.from(InvoicesSchema)
|
||||
.where(eq(InvoicesSchema.id, invoiceId)),
|
||||
)
|
||||
return result?.[0]?.organizationId ?? null
|
||||
}
|
||||
|
||||
async fetchGoal(goalId: number): Promise<{ organizationId: number | null; name: string | null } | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select({ organizationId: GoalsSchema.organizationId, name: GoalsSchema.name })
|
||||
.from(GoalsSchema)
|
||||
.where(eq(GoalsSchema.id, goalId)),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
private invoiceColumns(data: InvoiceArgUpdate) {
|
||||
return {
|
||||
goalId: data.goalId,
|
||||
sellerId: data.sellerId,
|
||||
counterpartyId: data.counterpartyId,
|
||||
number: data.number,
|
||||
reference: data.reference,
|
||||
currencyCode: data.currencyCode,
|
||||
issueDate: data.issueDate,
|
||||
paymentTerms: data.paymentTerms,
|
||||
dueDate: data.dueDate,
|
||||
periodFrom: data.periodFrom,
|
||||
periodTo: data.periodTo,
|
||||
discountType: data.discountType,
|
||||
discountValue: String(data.discountValue),
|
||||
taxRate: String(data.taxRate),
|
||||
taxExempt: data.taxExempt,
|
||||
taxNote: data.taxNote,
|
||||
notes: data.notes,
|
||||
terms: data.terms,
|
||||
}
|
||||
}
|
||||
|
||||
async create({ data, createdBy, sellerSnapshot, counterpartySnapshot, goalName }: InvoiceCreateRepoArgs): Promise<InvoiceWithLines | 'duplicate_number' | null> {
|
||||
try {
|
||||
return await this.db.dbDrizzle.transaction(async (tx) => {
|
||||
const inserted = await tx
|
||||
.insert(InvoicesSchema)
|
||||
.values({
|
||||
organizationId: data.organizationId,
|
||||
...this.invoiceColumns(data),
|
||||
goalName,
|
||||
sellerSnapshot,
|
||||
counterpartySnapshot,
|
||||
createdBy,
|
||||
})
|
||||
.returning()
|
||||
const created = inserted[0]
|
||||
const insertedLines = await tx.insert(InvoiceLinesSchema).values(this.toLineRows(created.id, data.lines)).returning()
|
||||
return { ...created, lines: insertedLines }
|
||||
})
|
||||
} catch (error) {
|
||||
if (this.isUniqueViolation(error)) return 'duplicate_number'
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async update({ invoiceId, data, sellerSnapshot, counterpartySnapshot, goalName }: InvoiceUpdateRepoArgs): Promise<InvoiceWithLines | 'duplicate_number' | null> {
|
||||
try {
|
||||
return await this.db.dbDrizzle.transaction(async (tx) => {
|
||||
const updated = await tx
|
||||
.update(InvoicesSchema)
|
||||
.set({
|
||||
...this.invoiceColumns(data),
|
||||
goalName,
|
||||
sellerSnapshot,
|
||||
counterpartySnapshot,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(InvoicesSchema.id, invoiceId))
|
||||
.returning()
|
||||
const current = updated[0]
|
||||
if (!current) return null
|
||||
await tx.delete(InvoiceLinesSchema).where(eq(InvoiceLinesSchema.invoiceId, invoiceId))
|
||||
const insertedLines = await tx.insert(InvoiceLinesSchema).values(this.toLineRows(invoiceId, data.lines)).returning()
|
||||
return { ...current, lines: insertedLines }
|
||||
})
|
||||
} catch (error) {
|
||||
if (this.isUniqueViolation(error)) return 'duplicate_number'
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async applyStatus({ invoiceId, patch }: InvoiceStatusRepoArgs): Promise<InvoiceWithLines | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.update(InvoicesSchema)
|
||||
.set({ ...patch, updatedAt: new Date() })
|
||||
.where(eq(InvoicesSchema.id, invoiceId))
|
||||
.returning(),
|
||||
)
|
||||
const invoice = result?.[0]
|
||||
if (!invoice) return null
|
||||
return (await this.attachLines([invoice]))[0]
|
||||
}
|
||||
|
||||
async setReplaces({ invoiceId, replacesInvoiceId }: InvoiceSetReplacesArgs): Promise<void> {
|
||||
await callWithCatch(() =>
|
||||
this.db.dbDrizzle.update(InvoicesSchema).set({ replacesInvoiceId }).where(eq(InvoicesSchema.id, invoiceId)),
|
||||
)
|
||||
}
|
||||
|
||||
async nextNumber({ organizationId, base }: InvoiceNextNumberArgs): Promise<string> {
|
||||
const match = base.match(/^(.*?)(\d+)$/)
|
||||
if (!match) return `${base}-1`
|
||||
const [, prefix, digits] = match
|
||||
const rows = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select({ number: InvoicesSchema.number })
|
||||
.from(InvoicesSchema)
|
||||
.where(eq(InvoicesSchema.organizationId, organizationId)),
|
||||
)
|
||||
let max = Number(digits)
|
||||
for (const row of rows ?? []) {
|
||||
if (!row.number.startsWith(prefix)) continue
|
||||
const tail = row.number.slice(prefix.length)
|
||||
if (/^\d+$/.test(tail)) max = Math.max(max, Number(tail))
|
||||
}
|
||||
return `${prefix}${String(max + 1).padStart(digits.length, '0')}`
|
||||
}
|
||||
|
||||
async delete(invoiceId: number): Promise<boolean> {
|
||||
const result = await callWithCatch(() => this.db.dbDrizzle.delete(InvoicesSchema).where(eq(InvoicesSchema.id, invoiceId)))
|
||||
return !!result?.rowCount
|
||||
}
|
||||
|
||||
private toLineRows(invoiceId: number, lines: InvoiceLineArg[]) {
|
||||
return lines.map((line, index) => ({
|
||||
invoiceId,
|
||||
position: index,
|
||||
taskId: line.taskId,
|
||||
description: line.description,
|
||||
unit: line.unit,
|
||||
quantity: String(line.quantity),
|
||||
unitPrice: String(line.unitPrice),
|
||||
}))
|
||||
}
|
||||
|
||||
private async attachLines(invoices: InvoicesSchemaTypeForSelect[]): Promise<InvoiceWithLines[]> {
|
||||
if (invoices.length === 0) return []
|
||||
const lines = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select()
|
||||
.from(InvoiceLinesSchema)
|
||||
.where(inArray(InvoiceLinesSchema.invoiceId, invoices.map((invoice) => invoice.id)))
|
||||
.orderBy(asc(InvoiceLinesSchema.invoiceId), asc(InvoiceLinesSchema.position)),
|
||||
)
|
||||
const byInvoice = new Map<number, InvoiceLinesSchemaTypeForSelect[]>()
|
||||
for (const line of lines ?? []) {
|
||||
const list = byInvoice.get(line.invoiceId) ?? []
|
||||
list.push(line)
|
||||
byInvoice.set(line.invoiceId, list)
|
||||
}
|
||||
return invoices.map((invoice) => ({ ...invoice, lines: byInvoice.get(invoice.id) ?? [] }))
|
||||
}
|
||||
|
||||
private isUniqueViolation(error: unknown): boolean {
|
||||
if (typeof error !== 'object' || error === null) return false
|
||||
const { code, cause } = error as { code?: string; cause?: { code?: string } }
|
||||
return code === PG_UNIQUE_VIOLATION || cause?.code === PG_UNIQUE_VIOLATION
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Router } from 'express'
|
||||
import type { Routable } from '../../types/routable.type'
|
||||
import { IsLoggedIn } from '../auth/middlewares/is-logged-in'
|
||||
import { IsOrgAdmin } from '../organizations/middlewares/IsOrgAdmin'
|
||||
import { RequireTokenPermission } from '../../middlewares/require-token-permission'
|
||||
import { GoalPermissions } from '../../types/auth.types'
|
||||
import { InvoicesController } from './InvoicesController'
|
||||
import { isOrgAdminForInvoice } from './middlewares/is-org-admin-for-invoice'
|
||||
|
||||
export default class InvoicesRoutes implements Routable {
|
||||
private readonly router: ReturnType<typeof Router>
|
||||
private readonly controller: InvoicesController
|
||||
|
||||
constructor() {
|
||||
this.router = Router()
|
||||
this.controller = new InvoicesController()
|
||||
this.initRoutes()
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router
|
||||
}
|
||||
|
||||
private initRoutes() {
|
||||
const canManage = RequireTokenPermission(GoalPermissions.BILLING_CAN_MANAGE)
|
||||
|
||||
this.router.get('', [IsLoggedIn, IsOrgAdmin, canManage], this.controller.fetch)
|
||||
this.router.post('', [IsLoggedIn, IsOrgAdmin, canManage], this.controller.create)
|
||||
this.router.get('/:id', [IsLoggedIn, isOrgAdminForInvoice, canManage], this.controller.getById)
|
||||
this.router.patch('/:id', [IsLoggedIn, isOrgAdminForInvoice, canManage], this.controller.update)
|
||||
this.router.patch('/:id/status', [IsLoggedIn, isOrgAdminForInvoice, canManage], this.controller.setStatus)
|
||||
this.router.post('/:id/reissue', [IsLoggedIn, isOrgAdminForInvoice, canManage], this.controller.reissue)
|
||||
this.router.get('/:id/pdf', [IsLoggedIn, isOrgAdminForInvoice, canManage], this.controller.pdf)
|
||||
this.router.delete('/:id', [IsLoggedIn, isOrgAdminForInvoice, canManage], this.controller.delete)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import axios from 'axios'
|
||||
import type http from 'http'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import App from '../../../App'
|
||||
|
||||
const port = 1811
|
||||
const api = axios.create({ baseURL: `http://localhost:${port}`, validateStatus: () => true })
|
||||
|
||||
const LOGIN = 'test@mail.dest'
|
||||
const PASSWORD = 'user1!#Q'
|
||||
|
||||
let server: http.Server
|
||||
let jwt = ''
|
||||
let organizationId = 0
|
||||
let goalId = 0
|
||||
let sellerId = 0
|
||||
let counterpartyId = 0
|
||||
let invoiceId = 0
|
||||
|
||||
const auth = () => ({ headers: { Authorization: `Bearer ${jwt}` } })
|
||||
|
||||
const sellerPayload = () => ({
|
||||
organizationId,
|
||||
name: 'IT Seller',
|
||||
legalName: 'IT Seller LLC',
|
||||
address: 'Somewhere 1',
|
||||
email: 'billing@seller.test',
|
||||
phone: '',
|
||||
logoUrl: '',
|
||||
currencyCode: 'EUR',
|
||||
bank: { bankName: 'Bank', accountNumber: '123', iban: 'DE00', swift: 'XXX', correspondentAccount: '' },
|
||||
requisites: [{ key: 'vat', label: 'VAT ID', value: 'DE1' }],
|
||||
defaultTerms: 'Net 14',
|
||||
taxNote: '',
|
||||
})
|
||||
|
||||
const counterpartyPayload = () => ({
|
||||
organizationId,
|
||||
kind: 'organization',
|
||||
name: 'IT Client',
|
||||
legalName: 'IT Client GmbH',
|
||||
address: '',
|
||||
email: 'ap@client.test',
|
||||
phone: '',
|
||||
contactPerson: 'Anna',
|
||||
requisites: [],
|
||||
})
|
||||
|
||||
const invoicePayload = (number: string) => ({
|
||||
organizationId,
|
||||
goalId,
|
||||
sellerId,
|
||||
counterpartyId,
|
||||
number,
|
||||
reference: 'PO-1',
|
||||
currencyCode: 'EUR',
|
||||
issueDate: '2026-09-01',
|
||||
paymentTerms: 'net14',
|
||||
dueDate: '2026-09-15',
|
||||
periodFrom: null,
|
||||
periodTo: null,
|
||||
discountType: 'percent',
|
||||
discountValue: 10,
|
||||
taxRate: 19,
|
||||
taxExempt: false,
|
||||
taxNote: '',
|
||||
notes: '',
|
||||
terms: 'Net 14',
|
||||
lines: [
|
||||
{ taskId: null, description: 'Design', unit: 'service', quantity: 1, unitPrice: 1000 },
|
||||
{ taskId: null, description: 'Dev', unit: 'hours', quantity: 10.5, unitPrice: 80 },
|
||||
],
|
||||
})
|
||||
|
||||
describe('billing and invoices', () => {
|
||||
vi.mock('emailjs', () => ({
|
||||
SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
|
||||
}))
|
||||
|
||||
beforeAll(async () => {
|
||||
server = new App(port).listen()
|
||||
const login = await api.post('/module/auth/login', { login: LOGIN, password: PASSWORD })
|
||||
expect(login.status).toBe(200)
|
||||
jwt = login.data.access
|
||||
|
||||
const org = await api.post('/module/organizations', { name: `billing-it-${Date.now()}` }, auth())
|
||||
expect(org.status).toBe(200)
|
||||
organizationId = org.data.response.id
|
||||
|
||||
const goal = await api.post('/module/goals', { name: 'billing-it-goal', organizationId }, auth())
|
||||
expect(goal.status).toBe(200)
|
||||
goalId = goal.data.response.id ?? goal.data.response.goal?.id
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
if (organizationId) await api.delete(`/module/organizations/${organizationId}`, auth())
|
||||
server?.close()
|
||||
})
|
||||
|
||||
it('lists the seeded currencies', async () => {
|
||||
const response = await api.get('/module/billing/currencies', auth())
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.data.response.length).toBeGreaterThanOrEqual(20)
|
||||
expect(response.data.response.find((c: { code: string }) => c.code === 'JPY').decimalDigits).toBe(0)
|
||||
})
|
||||
|
||||
it('creates a seller and a counterparty for the organization', async () => {
|
||||
const seller = await api.post('/module/billing/sellers', sellerPayload(), auth())
|
||||
expect(seller.status).toBe(200)
|
||||
sellerId = seller.data.response.id
|
||||
expect(seller.data.response.bank.iban).toBe('DE00')
|
||||
|
||||
const counterparty = await api.post('/module/billing/counterparties', counterpartyPayload(), auth())
|
||||
expect(counterparty.status).toBe(200)
|
||||
counterpartyId = counterparty.data.response.id
|
||||
|
||||
const list = await api.get('/module/billing/counterparties', { params: { organizationId }, ...auth() })
|
||||
expect(list.data.response.map((c: { id: number }) => c.id)).toContain(counterpartyId)
|
||||
})
|
||||
|
||||
it('rejects an invalid payload', async () => {
|
||||
const response = await api.post('/module/billing/sellers', { ...sellerPayload(), currencyCode: 'euro' }, auth())
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('creates an invoice with snapshots, lines and the project name', async () => {
|
||||
const response = await api.post('/module/invoices', invoicePayload('INV-IT-1'), auth())
|
||||
expect(response.status).toBe(200)
|
||||
const invoice = response.data.response
|
||||
invoiceId = invoice.id
|
||||
expect(invoice.status).toBe('draft')
|
||||
expect(invoice.goalName).toBe('billing-it-goal')
|
||||
expect(invoice.seller.legalName).toBe('IT Seller LLC')
|
||||
expect(invoice.counterparty.contactPerson).toBe('Anna')
|
||||
expect(invoice.lines).toHaveLength(2)
|
||||
expect(invoice.lines[1].quantity).toBe(10.5)
|
||||
expect(invoice.discountValue).toBe(10)
|
||||
expect(typeof invoice.taxRate).toBe('number')
|
||||
})
|
||||
|
||||
it('refuses a duplicate number inside the organization', async () => {
|
||||
const response = await api.post('/module/invoices', invoicePayload('INV-IT-1'), auth())
|
||||
expect(response.status).toBe(409)
|
||||
})
|
||||
|
||||
it('refuses a seller from another organization', async () => {
|
||||
const response = await api.post('/module/invoices', { ...invoicePayload('INV-IT-2'), sellerId: 999999 }, auth())
|
||||
expect(response.status).toBe(422)
|
||||
})
|
||||
|
||||
it('keeps the seller snapshot when the seller is edited', async () => {
|
||||
const update = await api.patch(`/module/billing/sellers/${sellerId}`, { ...sellerPayload(), organizationId: undefined, legalName: 'Renamed LLC' }, auth())
|
||||
expect(update.status).toBe(200)
|
||||
const invoice = await api.get(`/module/invoices/${invoiceId}`, auth())
|
||||
expect(invoice.data.response.seller.legalName).toBe('IT Seller LLC')
|
||||
})
|
||||
|
||||
it('replaces lines on update', async () => {
|
||||
const data = { ...invoicePayload('INV-IT-1'), organizationId: undefined, lines: [{ taskId: null, description: 'Only', unit: 'pcs', quantity: 2, unitPrice: 5 }] }
|
||||
const response = await api.patch(`/module/invoices/${invoiceId}`, data, auth())
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.data.response.lines).toHaveLength(1)
|
||||
expect(response.data.response.lines[0].description).toBe('Only')
|
||||
})
|
||||
|
||||
it('refuses to delete a seller that has invoices', async () => {
|
||||
const response = await api.delete(`/module/billing/sellers/${sellerId}`, auth())
|
||||
expect(response.status).toBe(409)
|
||||
})
|
||||
|
||||
it('hides invoices of an archived client unless asked for', async () => {
|
||||
const archive = await api.patch(`/module/billing/counterparties/${counterpartyId}/archive`, { archived: true }, auth())
|
||||
expect(archive.status).toBe(200)
|
||||
expect(archive.data.response.archived).toBe(true)
|
||||
|
||||
const hidden = await api.get('/module/invoices', { params: { organizationId }, ...auth() })
|
||||
expect(hidden.data.response.map((i: { id: number }) => i.id)).not.toContain(invoiceId)
|
||||
|
||||
const shown = await api.get('/module/invoices', { params: { organizationId, includeArchived: true }, ...auth() })
|
||||
expect(shown.data.response.map((i: { id: number }) => i.id)).toContain(invoiceId)
|
||||
|
||||
await api.patch(`/module/billing/counterparties/${counterpartyId}/archive`, { archived: false }, auth())
|
||||
})
|
||||
|
||||
it('refuses to pay a draft and reports what is missing before issuing', async () => {
|
||||
const paid = await api.patch(`/module/invoices/${invoiceId}/status`, { status: 'paid' }, auth())
|
||||
expect(paid.status).toBe(409)
|
||||
expect(paid.data.error).toBe('invalid_transition')
|
||||
|
||||
const issued = await api.patch(`/module/invoices/${invoiceId}/status`, { status: 'issued' }, auth())
|
||||
expect(issued.status).toBe(422)
|
||||
expect(issued.data.missing).toContain('counterparty.address')
|
||||
})
|
||||
|
||||
it('issues the invoice, freezes the totals and locks editing', async () => {
|
||||
const fixed = await api.patch(`/module/billing/counterparties/${counterpartyId}`, { ...counterpartyPayload(), organizationId: undefined, address: 'Client street 1' }, auth())
|
||||
expect(fixed.status).toBe(200)
|
||||
const resnap = await api.patch(`/module/invoices/${invoiceId}`, { ...invoicePayload('INV-IT-1'), organizationId: undefined }, auth())
|
||||
expect(resnap.status).toBe(200)
|
||||
|
||||
const issued = await api.patch(`/module/invoices/${invoiceId}/status`, { status: 'issued' }, auth())
|
||||
expect(issued.status).toBe(200)
|
||||
expect(issued.data.response.status).toBe('issued')
|
||||
expect(issued.data.response.issuedAt).toBeTruthy()
|
||||
expect(issued.data.response.totalsFrozen).toBe(true)
|
||||
expect(issued.data.response.totals.total).toBe(1970.64)
|
||||
|
||||
const edit = await api.patch(`/module/invoices/${invoiceId}`, { ...invoicePayload('INV-IT-1'), organizationId: undefined }, auth())
|
||||
expect(edit.status).toBe(409)
|
||||
const del = await api.delete(`/module/invoices/${invoiceId}`, auth())
|
||||
expect(del.status).toBe(409)
|
||||
const back = await api.patch(`/module/invoices/${invoiceId}/status`, { status: 'draft' }, auth())
|
||||
expect(back.status).toBe(409)
|
||||
})
|
||||
|
||||
it('marks paid, unmarks and refuses to void a paid invoice', async () => {
|
||||
const paid = await api.patch(`/module/invoices/${invoiceId}/status`, { status: 'paid' }, auth())
|
||||
expect(paid.data.response.paidAt).toBeTruthy()
|
||||
const voided = await api.patch(`/module/invoices/${invoiceId}/status`, { status: 'void' }, auth())
|
||||
expect(voided.status).toBe(409)
|
||||
const unpaid = await api.patch(`/module/invoices/${invoiceId}/status`, { status: 'issued' }, auth())
|
||||
expect(unpaid.data.response.paidAt).toBeNull()
|
||||
})
|
||||
|
||||
it('renders the invoice as a PDF', async () => {
|
||||
const response = await api.get(`/module/invoices/${invoiceId}/pdf`, { ...auth(), params: { lang: 'ru' }, responseType: 'arraybuffer' })
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers['content-type']).toContain('application/pdf')
|
||||
expect(Buffer.from(response.data).subarray(0, 4).toString()).toBe('%PDF')
|
||||
})
|
||||
|
||||
it('reissues: voids the original and creates a draft copy with the next number', async () => {
|
||||
const response = await api.post(`/module/invoices/${invoiceId}/reissue`, {}, auth())
|
||||
expect(response.status).toBe(200)
|
||||
const copy = response.data.response
|
||||
expect(copy.status).toBe('draft')
|
||||
expect(copy.number).toBe('INV-IT-2')
|
||||
expect(copy.replacesInvoiceId).toBe(invoiceId)
|
||||
expect(copy.lines).toHaveLength(2)
|
||||
|
||||
const original = await api.get(`/module/invoices/${invoiceId}`, auth())
|
||||
expect(original.data.response.status).toBe('void')
|
||||
expect(original.data.response.voidedAt).toBeTruthy()
|
||||
|
||||
const revive = await api.patch(`/module/invoices/${invoiceId}/status`, { status: 'issued' }, auth())
|
||||
expect(revive.status).toBe(409)
|
||||
const deleted = await api.delete(`/module/invoices/${copy.id}`, auth())
|
||||
expect(deleted.status).toBe(200)
|
||||
})
|
||||
|
||||
it('keeps a seller with a voided invoice undeletable', async () => {
|
||||
const response = await api.delete(`/module/billing/sellers/${sellerId}`, auth())
|
||||
expect(response.status).toBe(409)
|
||||
})
|
||||
|
||||
it('rejects an anonymous request', async () => {
|
||||
const response = await api.get('/module/invoices', { params: { organizationId } })
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,6 @@
|
||||
import { isOrgAdminFor } from '../../billing/middlewares/is-org-admin-for'
|
||||
import { InvoicesRepository } from '../InvoicesRepository'
|
||||
|
||||
const repository = new InvoicesRepository()
|
||||
|
||||
export const isOrgAdminForInvoice = isOrgAdminFor((id) => repository.fetchOrganizationId(id))
|
||||
@@ -0,0 +1,203 @@
|
||||
import { type } from 'arktype'
|
||||
import type {
|
||||
InvoiceCounterpartySnapshot,
|
||||
InvoiceLinesSchemaTypeForSelect,
|
||||
InvoiceSellerSnapshot,
|
||||
InvoiceStatus,
|
||||
InvoicesSchemaTypeForSelect,
|
||||
} from 'taskview-db-schemas'
|
||||
import type { InvoiceTotalsResult } from '../../utils/invoiceTotals'
|
||||
|
||||
const NumberFromString = type('string|number').pipe((v) => Number(v))
|
||||
const BooleanFromString = type('string|boolean|undefined').pipe((v) => {
|
||||
if (v === undefined) return undefined
|
||||
if (typeof v === 'boolean') return v
|
||||
return v === 'true' || v === '1'
|
||||
})
|
||||
const DateString = type(/^\d{4}-\d{2}-\d{2}$/)
|
||||
const DateStringOrNull = DateString.or('null')
|
||||
|
||||
export const InvoiceLineArkType = type({
|
||||
taskId: 'number|null',
|
||||
description: '1<=string<=1000',
|
||||
unit: "'service' | 'hours' | 'pcs'",
|
||||
quantity: 'number>=0',
|
||||
unitPrice: 'number>=0',
|
||||
})
|
||||
export type InvoiceLineArg = typeof InvoiceLineArkType.infer
|
||||
|
||||
export const InvoiceArkTypeCreate = type({
|
||||
organizationId: 'number',
|
||||
goalId: 'number|null',
|
||||
sellerId: 'number',
|
||||
counterpartyId: 'number',
|
||||
number: '1<=string<=50',
|
||||
reference: 'string<=200',
|
||||
currencyCode: /^[A-Z]{3}$/,
|
||||
issueDate: DateString,
|
||||
paymentTerms: "'on_receipt' | 'net7' | 'net14' | 'net30' | 'custom'",
|
||||
dueDate: DateStringOrNull,
|
||||
periodFrom: DateStringOrNull,
|
||||
periodTo: DateStringOrNull,
|
||||
discountType: "'percent' | 'amount'",
|
||||
discountValue: 'number>=0',
|
||||
taxRate: '0<=number<=100',
|
||||
taxExempt: 'boolean',
|
||||
taxNote: 'string<=500',
|
||||
notes: 'string<=2000',
|
||||
terms: 'string<=2000',
|
||||
lines: InvoiceLineArkType.array().atLeastLength(1),
|
||||
})
|
||||
export type InvoiceArgCreate = typeof InvoiceArkTypeCreate.infer
|
||||
|
||||
export const InvoiceArkTypeUpdate = InvoiceArkTypeCreate.omit('organizationId')
|
||||
export type InvoiceArgUpdate = typeof InvoiceArkTypeUpdate.infer
|
||||
|
||||
export const InvoiceArkTypeList = type({
|
||||
organizationId: NumberFromString,
|
||||
'includeArchived?': BooleanFromString,
|
||||
})
|
||||
export type InvoiceArgList = typeof InvoiceArkTypeList.infer
|
||||
|
||||
export const InvoiceArkTypeId = type({
|
||||
id: NumberFromString,
|
||||
})
|
||||
|
||||
export const InvoiceArkTypeStatus = type({
|
||||
status: "'draft' | 'issued' | 'paid' | 'void'",
|
||||
})
|
||||
export type InvoiceArgStatus = typeof InvoiceArkTypeStatus.infer
|
||||
|
||||
export const InvoiceArkTypePdf = type({
|
||||
id: NumberFromString,
|
||||
'lang?': "'en' | 'ru'",
|
||||
})
|
||||
export type InvoiceArgPdf = typeof InvoiceArkTypePdf.infer
|
||||
|
||||
export const INVOICE_TRANSITIONS: Record<InvoiceStatus, InvoiceStatus[]> = {
|
||||
draft: ['issued'],
|
||||
issued: ['paid', 'void'],
|
||||
paid: ['issued'],
|
||||
void: [],
|
||||
}
|
||||
|
||||
export const INVOICE_TEMPLATE_VERSION = 1
|
||||
|
||||
export type InvoiceMissingRequisite =
|
||||
| 'seller.name'
|
||||
| 'seller.address'
|
||||
| 'seller.bank'
|
||||
| 'counterparty.name'
|
||||
| 'counterparty.address'
|
||||
| 'lines'
|
||||
|
||||
export type InvoiceStatusPatch = {
|
||||
status: InvoiceStatus
|
||||
issuedAt?: Date | null
|
||||
paidAt?: Date | null
|
||||
voidedAt?: Date | null
|
||||
templateVersion?: number
|
||||
subtotal?: string | null
|
||||
discountAmount?: string | null
|
||||
taxAmount?: string | null
|
||||
total?: string | null
|
||||
}
|
||||
|
||||
export type InvoiceStatusRepoArgs = {
|
||||
invoiceId: number
|
||||
patch: InvoiceStatusPatch
|
||||
}
|
||||
|
||||
export type InvoiceSetReplacesArgs = {
|
||||
invoiceId: number
|
||||
replacesInvoiceId: number
|
||||
}
|
||||
|
||||
export type InvoiceReissueArgs = {
|
||||
invoiceId: number
|
||||
createdBy: number | null
|
||||
}
|
||||
|
||||
export type InvoiceTransitionError =
|
||||
| { error: 'not_found' }
|
||||
| { error: 'invalid_transition'; from: InvoiceStatus; to: InvoiceStatus }
|
||||
| { error: 'missing_requisites'; missing: InvoiceMissingRequisite[] }
|
||||
|
||||
export type InvoiceTransitionResult = { invoice: InvoiceForClient } | InvoiceTransitionError
|
||||
|
||||
export type InvoicePdfLang = 'en' | 'ru'
|
||||
|
||||
export type InvoiceRenderPdfArgs = {
|
||||
invoiceId: number
|
||||
lang: InvoicePdfLang
|
||||
}
|
||||
|
||||
export type PdfmakeServer = {
|
||||
virtualfs: { writeFileSync(filename: string, content: Buffer): void }
|
||||
setFonts(fonts: Record<string, { normal: string; bold: string; italics: string; bolditalics: string }>): void
|
||||
createPdf(docDefinition: unknown): { getBuffer(): Promise<Buffer> }
|
||||
}
|
||||
|
||||
export type InvoiceSnapshots = {
|
||||
sellerSnapshot: InvoiceSellerSnapshot
|
||||
counterpartySnapshot: InvoiceCounterpartySnapshot
|
||||
goalName: string
|
||||
}
|
||||
|
||||
export type InvoiceCreateRepoArgs = InvoiceSnapshots & {
|
||||
data: InvoiceArgCreate
|
||||
createdBy: number | null
|
||||
}
|
||||
|
||||
export type InvoiceUpdateRepoArgs = InvoiceSnapshots & {
|
||||
invoiceId: number
|
||||
data: InvoiceArgUpdate
|
||||
}
|
||||
|
||||
export type InvoiceCreateArgs = {
|
||||
data: InvoiceArgCreate
|
||||
createdBy: number | null
|
||||
}
|
||||
|
||||
export type InvoiceUpdateArgs = {
|
||||
invoiceId: number
|
||||
data: InvoiceArgUpdate
|
||||
}
|
||||
|
||||
export type InvoiceSetStatusArgs = {
|
||||
invoiceId: number
|
||||
status: InvoiceArgStatus['status']
|
||||
}
|
||||
|
||||
export type InvoiceWithLines = InvoicesSchemaTypeForSelect & {
|
||||
lines: InvoiceLinesSchemaTypeForSelect[]
|
||||
}
|
||||
|
||||
export type InvoiceLineForClient = Omit<InvoiceLinesSchemaTypeForSelect, 'invoiceId' | 'position' | 'quantity' | 'unitPrice'> & {
|
||||
quantity: number
|
||||
unitPrice: number
|
||||
}
|
||||
|
||||
export type InvoiceForClient = Omit<
|
||||
InvoicesSchemaTypeForSelect,
|
||||
'discountValue' | 'taxRate' | 'sellerSnapshot' | 'counterpartySnapshot' | 'subtotal' | 'discountAmount' | 'taxAmount' | 'total'
|
||||
> & {
|
||||
discountValue: number
|
||||
taxRate: number
|
||||
seller: InvoiceSellerSnapshot
|
||||
counterparty: InvoiceCounterpartySnapshot
|
||||
lines: InvoiceLineForClient[]
|
||||
totals: InvoiceTotalsResult
|
||||
totalsFrozen: boolean
|
||||
}
|
||||
|
||||
export type InvoiceWriteError = 'seller_not_found' | 'counterparty_not_found' | 'goal_not_found' | 'duplicate_number' | 'not_found' | 'not_draft'
|
||||
|
||||
export type InvoiceWriteResult = { invoice: InvoiceForClient } | { error: InvoiceWriteError }
|
||||
|
||||
export type InvoiceDeleteResult = 'deleted' | 'not_draft' | 'not_found'
|
||||
|
||||
export type InvoiceNextNumberArgs = {
|
||||
organizationId: number
|
||||
base: string
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Router } from 'express';
|
||||
import type { Routable } from '../../types/routable.type';
|
||||
import { GoalPermissions } from '../../types/auth.types';
|
||||
import { IsLoggedIn } from '../auth/middlewares/is-logged-in';
|
||||
import { KanbanController } from './KanbanController';
|
||||
import { CanManageKanban } from './middlewares/CanManageKanban';
|
||||
import { CanViewKanban } from './middlewares/CanViewKanban';
|
||||
import { CanFetchTasks } from './middlewares/CanFetchTasks';
|
||||
import { goalIdFromBody, goalIdFromParam, goalIdFromStatusBody } from './middlewares/goal-id-resolvers';
|
||||
import { requireKanbanPermission } from './middlewares/require-kanban-permission';
|
||||
|
||||
export default class KanbanRoutes implements Routable {
|
||||
private readonly router: ReturnType<typeof Router>;
|
||||
private readonly kanbanController: KanbanController;
|
||||
@@ -20,17 +21,89 @@ export default class KanbanRoutes implements Routable {
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.post('/fetch-statuses', [IsLoggedIn, CanViewKanban], this.kanbanController.fetchAllColumns);
|
||||
this.router.post('/add-status', [IsLoggedIn, CanManageKanban], this.kanbanController.addStatus);
|
||||
this.router.post('/delete-status', [IsLoggedIn, CanManageKanban], this.kanbanController.deleteStatus);
|
||||
this.router.post('/update-status', [IsLoggedIn, CanManageKanban], this.kanbanController.updateStatus);
|
||||
this.router.post(
|
||||
'/fetch-statuses',
|
||||
[
|
||||
IsLoggedIn,
|
||||
requireKanbanPermission({
|
||||
anyOf: [GoalPermissions.KANBAN_CAN_VIEW],
|
||||
resolveGoalId: goalIdFromBody,
|
||||
}),
|
||||
],
|
||||
this.kanbanController.fetchAllColumns
|
||||
);
|
||||
|
||||
// this.router.get('columns/:goalId', [IsLoggedIn], this.kanbanController.fetchAllColumns);
|
||||
this.router.get('/tasks/:goalId/:columnId/:cursor', [IsLoggedIn, CanViewKanban, CanFetchTasks], this.kanbanController.fetchTasksForColumn);
|
||||
this.router.post(
|
||||
'/add-status',
|
||||
[
|
||||
IsLoggedIn, requireKanbanPermission({
|
||||
anyOf: [GoalPermissions.KANBAN_CAN_MANAGE],
|
||||
resolveGoalId: goalIdFromBody
|
||||
})
|
||||
],
|
||||
this.kanbanController.addStatus
|
||||
);
|
||||
|
||||
this.router.post(
|
||||
'/delete-status',
|
||||
[
|
||||
IsLoggedIn, requireKanbanPermission({
|
||||
anyOf: [GoalPermissions.KANBAN_CAN_MANAGE],
|
||||
resolveGoalId: goalIdFromStatusBody
|
||||
})
|
||||
],
|
||||
this.kanbanController.deleteStatus
|
||||
);
|
||||
|
||||
this.router.post(
|
||||
'/update-status',
|
||||
[
|
||||
IsLoggedIn, requireKanbanPermission({
|
||||
anyOf: [GoalPermissions.KANBAN_CAN_MANAGE],
|
||||
resolveGoalId: goalIdFromStatusBody
|
||||
})
|
||||
],
|
||||
this.kanbanController.updateStatus
|
||||
);
|
||||
|
||||
this.router.get(
|
||||
'/tasks/:goalId/:columnId/:cursor',
|
||||
[
|
||||
IsLoggedIn,
|
||||
requireKanbanPermission({
|
||||
anyOf: [GoalPermissions.KANBAN_CAN_VIEW],
|
||||
resolveGoalId: goalIdFromParam,
|
||||
}),
|
||||
requireKanbanPermission({
|
||||
anyOf: [GoalPermissions.COMPONENT_CAN_WATCH_CONTENT],
|
||||
resolveGoalId: goalIdFromParam,
|
||||
}),
|
||||
],
|
||||
this.kanbanController.fetchTasksForColumn
|
||||
);
|
||||
|
||||
//we do not use this route in the client (no logic for this route on the client side)!!!
|
||||
this.router.get('/tasks-order/:goalId/:columnId/:cursor', [IsLoggedIn, CanManageKanban], this.kanbanController.getTasksOrderForColumnAndCursor);
|
||||
this.router.get(
|
||||
'/tasks-order/:goalId/:columnId/:cursor',
|
||||
[
|
||||
IsLoggedIn, requireKanbanPermission({
|
||||
anyOf: [GoalPermissions.KANBAN_CAN_VIEW],
|
||||
resolveGoalId: goalIdFromParam
|
||||
})
|
||||
],
|
||||
this.kanbanController.getTasksOrderForColumnAndCursor
|
||||
);
|
||||
|
||||
this.router.patch('/update-tasks-order-and-column', [IsLoggedIn, CanManageKanban], this.kanbanController.updateTasksOrderAndColumn);
|
||||
this.router.patch(
|
||||
'/update-tasks-order-and-column',
|
||||
[
|
||||
IsLoggedIn,
|
||||
requireKanbanPermission({
|
||||
anyOf: [GoalPermissions.KANBAN_CAN_MANAGE],
|
||||
resolveGoalId: goalIdFromBody
|
||||
})
|
||||
],
|
||||
this.kanbanController.updateTasksOrderAndColumn
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
import { KanbanArkTypeCanManageKanban } from '../types';
|
||||
import { ArkErrors } from 'arktype';
|
||||
|
||||
export const CanFetchTasks = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const props = req.body.goalId ? req.body : req.params;
|
||||
|
||||
const data = KanbanArkTypeCanManageKanban(props);
|
||||
|
||||
if (data instanceof ArkErrors) {
|
||||
return res.status(400).send(data.summary);
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(data.goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)
|
||||
.catch(logError);
|
||||
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanAddTask middleware');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (permissions.hasPermissions(GoalPermissions.COMPONENT_CAN_WATCH_CONTENT)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -1,54 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { ALL_TASKS_LIST_ID, DEFAULT_ID } from '../../../types/tasks.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
import { KanbanArkTypeCanManageKanban } from '../types';
|
||||
import { ArkErrors } from 'arktype';
|
||||
|
||||
export const CanManageKanban = async (req: Request, res: Response, next: NextFunction) => {
|
||||
let props = req.body.goalId ? req.body : req.params;
|
||||
|
||||
switch (req.url) {
|
||||
case '/update-status':
|
||||
const result = await req.appUser.kanbanManager.repository.fetchStatus(req.body.id);
|
||||
props = {
|
||||
goalId: result?.goal_id,
|
||||
};
|
||||
break;
|
||||
case '/delete-status':
|
||||
const result2 = await req.appUser.kanbanManager.repository.fetchStatus(req.body.id);
|
||||
props = {
|
||||
goalId: result2?.goal_id,
|
||||
};
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
const data = KanbanArkTypeCanManageKanban(props);
|
||||
|
||||
if (data instanceof ArkErrors) {
|
||||
return res.status(400).send(data.summary);
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(data.goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)
|
||||
.catch(logError);
|
||||
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanAddTask middleware');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (
|
||||
permissions.hasPermissions(GoalPermissions.COMPONENT_CAN_ADD_TASKS) ||
|
||||
permissions.hasPermissions(GoalPermissions.TASKS_CAN_ADD_SUBTASKS)
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
import { KanbanArkTypeCanManageKanban } from '../types';
|
||||
import { ArkErrors } from 'arktype';
|
||||
|
||||
export const CanViewKanban = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const props = req.body.goalId ? req.body : req.params;
|
||||
|
||||
const data = KanbanArkTypeCanManageKanban(props);
|
||||
|
||||
if (data instanceof ArkErrors) {
|
||||
return res.status(400).send(data.summary);
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(data.goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)
|
||||
.catch(logError);
|
||||
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanAddTask middleware');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (permissions.hasPermissions(GoalPermissions.KANBAN_CAN_VIEW)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Request } from 'express';
|
||||
|
||||
export function goalIdFromParam(req: Request): number | null {
|
||||
const goalId = Number(req.params.goalId);
|
||||
return goalId && !isNaN(goalId) ? goalId : null;
|
||||
}
|
||||
|
||||
export function goalIdFromBody(req: Request): number | null {
|
||||
const goalId = Number(req.body?.goalId);
|
||||
return goalId && !isNaN(goalId) ? goalId : null;
|
||||
}
|
||||
|
||||
export async function goalIdFromStatusBody(req: Request): Promise<number | null> {
|
||||
const statusId = Number(req.body?.id);
|
||||
if (!statusId || isNaN(statusId)) return null;
|
||||
|
||||
const status = await req.appUser.kanbanManager.repository.fetchStatus(statusId);
|
||||
return status?.goal_id ?? null;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { logError } from '../../../utils/api';
|
||||
import type { RequireKanbanPermissionArgs } from '../types';
|
||||
|
||||
export function requireKanbanPermission({ anyOf, resolveGoalId }: RequireKanbanPermissionArgs) {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
const goalId = await resolveGoalId(req);
|
||||
if (!goalId) return res.status(400).end();
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)
|
||||
.catch(logError);
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not resolve kanban permissions');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (anyOf.some((permission) => permissions.hasPermissions(permission))) return next();
|
||||
return res.status(403).end();
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { type } from 'arktype';
|
||||
import type { Request } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { StringToNumber } from '../../types/app.types';
|
||||
import type { GoalPermissionType } from '../../types/auth.types';
|
||||
|
||||
// ============ Arktype schemas ============
|
||||
|
||||
@@ -102,11 +104,13 @@ export const KanbanArkTypeUpdateTasksOrder = type({
|
||||
|
||||
export type KanbanArgUpdateTasksOrder = typeof KanbanArkTypeUpdateTasksOrder.infer;
|
||||
|
||||
export const KanbanArkTypeCanManageKanban = type({
|
||||
goalId: NumberFromString,
|
||||
});
|
||||
export type KanbanGoalIdResolver = (req: Request) => Promise<number | null> | number | null;
|
||||
|
||||
export type KanbanArgCanManageKanban = typeof KanbanArkTypeCanManageKanban.infer;
|
||||
export type RequireKanbanPermissionArgs = {
|
||||
/** the caller must hold at least ONE of these */
|
||||
anyOf: GoalPermissionType[];
|
||||
resolveGoalId: KanbanGoalIdResolver;
|
||||
};
|
||||
|
||||
// ============ Deprecated Zod schemas ============
|
||||
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
import type { Request, Response } from 'express'
|
||||
import { ArkErrors } from 'arktype'
|
||||
import { PublicApiUrl } from '../../modules/public-url'
|
||||
import { OAuthManager } from './OAuthManager'
|
||||
import {
|
||||
type SendTokenErrorArgs,
|
||||
type SendTokenSuccessArgs,
|
||||
OAuthAuthorizeArkType,
|
||||
OAuthConsentArkType,
|
||||
OAuthRegisterArkType,
|
||||
OAuthRevokeArkType,
|
||||
OAuthTokenArkType,
|
||||
} from './types'
|
||||
import {
|
||||
buildRedirectUrl,
|
||||
isAcceptableRedirectUri,
|
||||
isDcrEnabled,
|
||||
} from './oauth.utils'
|
||||
|
||||
export class OAuthController {
|
||||
private get manager() { return OAuthManager.getInstance() }
|
||||
|
||||
authorize = async (req: Request, res: Response) => {
|
||||
const params = OAuthAuthorizeArkType(req.query)
|
||||
if (params instanceof ArkErrors) {
|
||||
return res.status(400).send(params.summary)
|
||||
}
|
||||
|
||||
const client = await this.manager.validateRedirectUri({
|
||||
clientId: params.client_id,
|
||||
redirectUri: params.redirect_uri,
|
||||
})
|
||||
if (!client.ok) {
|
||||
return res.status(400).send(client.description)
|
||||
}
|
||||
|
||||
const consentUrl = buildRedirectUrl({
|
||||
redirectUri: `${process.env.APP_URL}/oauth/consent`,
|
||||
params: {
|
||||
client_id: params.client_id,
|
||||
client_name: client.value.name,
|
||||
redirect_uri: params.redirect_uri,
|
||||
code_challenge: params.code_challenge,
|
||||
code_challenge_method: params.code_challenge_method,
|
||||
state: params.state,
|
||||
resource: params.resource,
|
||||
},
|
||||
})
|
||||
return res.redirect(consentUrl)
|
||||
}
|
||||
|
||||
consent = async (req: Request, res: Response) => {
|
||||
const data = OAuthConsentArkType(req.body)
|
||||
if (data instanceof ArkErrors) {
|
||||
return res.status(400).send(data.summary)
|
||||
}
|
||||
|
||||
const userId = req.appUser.getUserData()?.id
|
||||
if (!userId) return res.status(401).end()
|
||||
|
||||
const client = await this.manager.validateRedirectUri({
|
||||
clientId: data.client_id,
|
||||
redirectUri: data.redirect_uri,
|
||||
})
|
||||
if (!client.ok) {
|
||||
return res.status(400).send(client.description)
|
||||
}
|
||||
|
||||
// Empty means "do not narrow", matching how a tvk_ token with no
|
||||
// permissions selected behaves. The user's own RBAC is still the ceiling.
|
||||
const code = await this.manager.issueAuthCode({
|
||||
clientId: data.client_id,
|
||||
userId,
|
||||
redirectUri: data.redirect_uri,
|
||||
codeChallenge: data.code_challenge,
|
||||
codeChallengeMethod: data.code_challenge_method,
|
||||
allowedPermissions: data.allowedPermissions ?? [],
|
||||
allowedGoalIds: data.allowedGoalIds ?? [],
|
||||
resource: data.resource ?? null,
|
||||
})
|
||||
if (!code) return res.status(500).end()
|
||||
|
||||
return res.tvJson({
|
||||
redirectUrl: buildRedirectUrl({
|
||||
redirectUri: data.redirect_uri,
|
||||
params: { code, state: data.state },
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
denyConsent = async (req: Request, res: Response) => {
|
||||
const data = OAuthConsentArkType(req.body)
|
||||
if (data instanceof ArkErrors) {
|
||||
return res.status(400).send(data.summary)
|
||||
}
|
||||
|
||||
const client = await this.manager.validateRedirectUri({
|
||||
clientId: data.client_id,
|
||||
redirectUri: data.redirect_uri,
|
||||
})
|
||||
if (!client.ok) {
|
||||
return res.status(400).send(client.description)
|
||||
}
|
||||
|
||||
return res.tvJson({
|
||||
redirectUrl: buildRedirectUrl({
|
||||
redirectUri: data.redirect_uri,
|
||||
params: { error: 'access_denied', state: data.state },
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
token = async (req: Request, res: Response) => {
|
||||
const data = OAuthTokenArkType(req.body)
|
||||
if (data instanceof ArkErrors) {
|
||||
return this.sendTokenError({ res, status: 400, error: 'invalid_request', description: data.summary })
|
||||
}
|
||||
|
||||
const basic = this.readBasicAuth(req)
|
||||
const clientId = basic?.clientId ?? data.client_id
|
||||
const clientSecret = basic?.clientSecret ?? data.client_secret
|
||||
if (!clientId) {
|
||||
return this.sendTokenError({ res, status: 401, error: 'invalid_client', description: 'client_id is required' })
|
||||
}
|
||||
|
||||
const client = await this.manager.authenticateClient({ clientId, clientSecret })
|
||||
if (!client.ok) {
|
||||
return this.sendTokenError({ res, status: 401, error: client.error, description: client.description })
|
||||
}
|
||||
|
||||
const resource = data.resource ?? null
|
||||
|
||||
if (data.grant_type === 'authorization_code') {
|
||||
if (!data.code || !data.code_verifier || !data.redirect_uri) {
|
||||
return this.sendTokenError({
|
||||
res,
|
||||
status: 400,
|
||||
error: 'invalid_request',
|
||||
description: 'code, code_verifier and redirect_uri are required',
|
||||
})
|
||||
}
|
||||
const result = await this.manager.exchangeCode({
|
||||
code: data.code,
|
||||
codeVerifier: data.code_verifier,
|
||||
clientId,
|
||||
redirectUri: data.redirect_uri,
|
||||
resource,
|
||||
})
|
||||
if (!result.ok) {
|
||||
return this.sendTokenError({ res, status: 400, error: result.error, description: result.description })
|
||||
}
|
||||
return this.sendTokenSuccess({ res, body: result.value })
|
||||
}
|
||||
|
||||
if (!data.refresh_token) {
|
||||
return this.sendTokenError({ res, status: 400, error: 'invalid_request', description: 'refresh_token is required' })
|
||||
}
|
||||
const refreshed = await this.manager.refreshTokens({
|
||||
refreshToken: data.refresh_token,
|
||||
clientId,
|
||||
resource,
|
||||
})
|
||||
if (!refreshed.ok) {
|
||||
return this.sendTokenError({ res, status: 400, error: refreshed.error, description: refreshed.description })
|
||||
}
|
||||
return this.sendTokenSuccess({ res, body: refreshed.value })
|
||||
}
|
||||
|
||||
register = async (req: Request, res: Response) => {
|
||||
if (!isDcrEnabled()) {
|
||||
return res.status(403).json({
|
||||
error: 'access_denied',
|
||||
error_description: 'Dynamic client registration is disabled on this instance',
|
||||
})
|
||||
}
|
||||
|
||||
const data = OAuthRegisterArkType(req.body)
|
||||
if (data instanceof ArkErrors) {
|
||||
return res.status(400).json({ error: 'invalid_client_metadata', error_description: data.summary })
|
||||
}
|
||||
|
||||
const rejected = data.redirect_uris.find((uri) => !isAcceptableRedirectUri(uri))
|
||||
if (rejected) {
|
||||
return res.status(400).json({
|
||||
error: 'invalid_redirect_uri',
|
||||
error_description: `redirect_uri must be https, loopback http, or an app scheme, and carry no fragment: ${rejected}`,
|
||||
})
|
||||
}
|
||||
|
||||
const name = data.client_name?.trim() || 'Unnamed client'
|
||||
const isPublic = (data.token_endpoint_auth_method ?? 'none') === 'none'
|
||||
const result = await this.manager.registerClient({
|
||||
name,
|
||||
redirectUris: data.redirect_uris,
|
||||
isPublic,
|
||||
})
|
||||
if (!result.ok) {
|
||||
return res.status(500).json({ error: result.error, error_description: result.description })
|
||||
}
|
||||
|
||||
return res.status(201).json({
|
||||
client_id: result.value.clientId,
|
||||
// RFC 7591 §3.2.1: client_secret_expires_at is REQUIRED whenever a
|
||||
// secret is issued. 0 means it does not expire.
|
||||
...(result.value.clientSecret
|
||||
? { client_secret: result.value.clientSecret, client_secret_expires_at: 0 }
|
||||
: {}),
|
||||
client_id_issued_at: Math.floor(Date.now() / 1000),
|
||||
client_name: name,
|
||||
redirect_uris: data.redirect_uris,
|
||||
token_endpoint_auth_method: isPublic ? 'none' : 'client_secret_post',
|
||||
grant_types: ['authorization_code', 'refresh_token'],
|
||||
response_types: ['code'],
|
||||
})
|
||||
}
|
||||
|
||||
revoke = async (req: Request, res: Response) => {
|
||||
const data = OAuthRevokeArkType(req.body)
|
||||
if (data instanceof ArkErrors) {
|
||||
return res.status(400).send(data.summary)
|
||||
}
|
||||
// RFC 7009: revocation always answers 200, even for an unknown token.
|
||||
await this.manager.revokeToken(data.token)
|
||||
return res.status(200).end()
|
||||
}
|
||||
|
||||
fetchConnectedApps = async (req: Request, res: Response) => {
|
||||
const userId = req.appUser.getUserData()?.id
|
||||
if (!userId) return res.status(401).end()
|
||||
|
||||
const result = await this.manager.fetchConnectedApps(userId)
|
||||
return res.tvJson(result)
|
||||
}
|
||||
|
||||
revokeConnectedApp = async (req: Request, res: Response) => {
|
||||
const userId = req.appUser.getUserData()?.id
|
||||
if (!userId) return res.status(401).end()
|
||||
|
||||
const grantId = Number(req.body?.grantId)
|
||||
if (!Number.isInteger(grantId) || grantId <= 0) {
|
||||
return res.status(400).send('grantId must be a positive integer')
|
||||
}
|
||||
|
||||
const result = await this.manager.revokeGrant({ grantId, userId })
|
||||
return res.tvJson(result)
|
||||
}
|
||||
|
||||
authorizationServerMetadata = async (req: Request, res: Response) => {
|
||||
const issuer = PublicApiUrl.base(req)
|
||||
return res.json({
|
||||
issuer,
|
||||
authorization_endpoint: `${issuer}/module/oauth/authorize`,
|
||||
token_endpoint: `${issuer}/module/oauth/token`,
|
||||
revocation_endpoint: `${issuer}/module/oauth/revoke`,
|
||||
...(isDcrEnabled() ? { registration_endpoint: `${issuer}/module/oauth/register` } : {}),
|
||||
response_types_supported: ['code'],
|
||||
grant_types_supported: ['authorization_code', 'refresh_token'],
|
||||
code_challenge_methods_supported: ['S256'],
|
||||
token_endpoint_auth_methods_supported: ['none', 'client_secret_post', 'client_secret_basic'],
|
||||
})
|
||||
}
|
||||
|
||||
protectedResourceMetadata = async (req: Request, res: Response) => {
|
||||
const issuer = PublicApiUrl.base(req)
|
||||
return res.json({
|
||||
resource: issuer,
|
||||
authorization_servers: [issuer],
|
||||
bearer_methods_supported: ['header'],
|
||||
})
|
||||
}
|
||||
|
||||
private readBasicAuth(req: Request): { clientId: string; clientSecret: string } | null {
|
||||
const header = req.headers.authorization
|
||||
if (!header?.toLowerCase().startsWith('basic ')) return null
|
||||
|
||||
const decoded = Buffer.from(header.slice(6).trim(), 'base64').toString('utf8')
|
||||
const separator = decoded.indexOf(':')
|
||||
if (separator < 0) return null
|
||||
|
||||
return {
|
||||
clientId: decodeURIComponent(decoded.slice(0, separator)),
|
||||
clientSecret: decodeURIComponent(decoded.slice(separator + 1)),
|
||||
}
|
||||
}
|
||||
|
||||
private sendTokenSuccess(args: SendTokenSuccessArgs) {
|
||||
args.res.setHeader('Cache-Control', 'no-store')
|
||||
args.res.setHeader('Pragma', 'no-cache')
|
||||
return args.res.json(args.body)
|
||||
}
|
||||
|
||||
private sendTokenError(args: SendTokenErrorArgs) {
|
||||
args.res.setHeader('Cache-Control', 'no-store')
|
||||
return args.res.status(args.status).json({
|
||||
error: args.error,
|
||||
error_description: args.description,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { randomBytes } from 'crypto'
|
||||
import type { OAuthClientsSchemaTypeForSelect, OAuthGrantsSchemaTypeForSelect } from 'taskview-db-schemas'
|
||||
import { OAuthRepository } from './OAuthRepository'
|
||||
import {
|
||||
OAUTH_ACCESS_TOKEN_PREFIX,
|
||||
OAUTH_ACCESS_TOKEN_TTL_SECONDS,
|
||||
OAUTH_CODE_TTL_SECONDS,
|
||||
OAUTH_REFRESH_TOKEN_TTL_SECONDS,
|
||||
type AuthenticateClientArgs,
|
||||
type ConnectedApp,
|
||||
type CreateAuthCodeArgs,
|
||||
type ExchangeCodeArgs,
|
||||
type IssueTokenPairArgs,
|
||||
type OAuthResult,
|
||||
type OAuthTokenResponse,
|
||||
type RefreshTokensArgs,
|
||||
type RegisterClientArgs,
|
||||
type RevokeOwnGrantArgs,
|
||||
type ValidateRedirectUriArgs,
|
||||
} from './types'
|
||||
import {
|
||||
matchesRegisteredRedirectUri,
|
||||
randomToken,
|
||||
resourceMatches,
|
||||
safeCompareHex,
|
||||
sha256Hex,
|
||||
verifyPkce,
|
||||
} from './oauth.utils'
|
||||
|
||||
export class OAuthManager {
|
||||
private static instance: OAuthManager | null = null
|
||||
|
||||
public readonly repository: OAuthRepository
|
||||
|
||||
constructor() {
|
||||
this.repository = new OAuthRepository()
|
||||
}
|
||||
|
||||
static getInstance(): OAuthManager {
|
||||
if (!OAuthManager.instance) OAuthManager.instance = new OAuthManager()
|
||||
return OAuthManager.instance
|
||||
}
|
||||
|
||||
async findClient(clientId: string): Promise<OAuthClientsSchemaTypeForSelect | null> {
|
||||
return this.repository.findClientByClientId(clientId)
|
||||
}
|
||||
|
||||
async validateRedirectUri(args: ValidateRedirectUriArgs): Promise<OAuthResult<OAuthClientsSchemaTypeForSelect>> {
|
||||
const client = await this.repository.findClientByClientId(args.clientId)
|
||||
if (!client) {
|
||||
return { ok: false, error: 'invalid_client', description: 'Unknown client_id' }
|
||||
}
|
||||
if (!matchesRegisteredRedirectUri({ candidate: args.redirectUri, registered: client.redirectUris })) {
|
||||
return { ok: false, error: 'invalid_request', description: 'redirect_uri does not match a registered URI' }
|
||||
}
|
||||
return { ok: true, value: client }
|
||||
}
|
||||
|
||||
async issueAuthCode(args: CreateAuthCodeArgs): Promise<string | null> {
|
||||
const code = randomToken()
|
||||
const created = await this.repository.createAuthCode({
|
||||
...args,
|
||||
codeHash: sha256Hex(code),
|
||||
expiresAt: new Date(Date.now() + OAUTH_CODE_TTL_SECONDS * 1000),
|
||||
})
|
||||
if (!created) return null
|
||||
|
||||
this.repository.deleteExpiredAuthCodes().catch(() => {})
|
||||
return code
|
||||
}
|
||||
|
||||
async exchangeCode(args: ExchangeCodeArgs): Promise<OAuthResult<OAuthTokenResponse>> {
|
||||
const record = await this.repository.findAuthCodeByHash(sha256Hex(args.code))
|
||||
if (!record) {
|
||||
return { ok: false, error: 'invalid_grant', description: 'Authorization code is not valid' }
|
||||
}
|
||||
|
||||
// A code presented twice means it leaked. Kill the grant it already produced.
|
||||
if (record.usedAt) {
|
||||
if (record.grantId) await this.repository.revokeGrant({ grantId: record.grantId })
|
||||
return { ok: false, error: 'invalid_grant', description: 'Authorization code has already been used' }
|
||||
}
|
||||
if (record.expiresAt < new Date()) {
|
||||
return { ok: false, error: 'invalid_grant', description: 'Authorization code has expired' }
|
||||
}
|
||||
if (record.clientId !== args.clientId) {
|
||||
return { ok: false, error: 'invalid_grant', description: 'Authorization code was issued to another client' }
|
||||
}
|
||||
if (record.redirectUri !== args.redirectUri) {
|
||||
return { ok: false, error: 'invalid_grant', description: 'redirect_uri does not match the authorization request' }
|
||||
}
|
||||
if (!verifyPkce({ codeVerifier: args.codeVerifier, codeChallenge: record.codeChallenge })) {
|
||||
return { ok: false, error: 'invalid_grant', description: 'code_verifier does not match code_challenge' }
|
||||
}
|
||||
if (!resourceMatches({ granted: record.resource, requested: args.resource })) {
|
||||
return { ok: false, error: 'invalid_target', description: 'resource does not match the authorization request' }
|
||||
}
|
||||
|
||||
const client = await this.repository.findClientByClientId(record.clientId)
|
||||
|
||||
const grant = await this.repository.createGrant({
|
||||
userId: record.userId,
|
||||
clientId: record.clientId,
|
||||
allowedPermissions: record.allowedPermissions,
|
||||
allowedGoalIds: record.allowedGoalIds,
|
||||
resource: record.resource,
|
||||
})
|
||||
if (!grant) {
|
||||
return { ok: false, error: 'server_error', description: 'Could not create the grant' }
|
||||
}
|
||||
|
||||
const consumed = await this.repository.consumeAuthCode({ id: record.id, grantId: grant.id })
|
||||
if (!consumed) {
|
||||
await this.repository.revokeGrant({ grantId: grant.id })
|
||||
return { ok: false, error: 'invalid_grant', description: 'Authorization code has already been used' }
|
||||
}
|
||||
|
||||
return this.issueTokenPair({ grant, clientName: client?.name ?? record.clientId })
|
||||
}
|
||||
|
||||
async refreshTokens(args: RefreshTokensArgs): Promise<OAuthResult<OAuthTokenResponse>> {
|
||||
const presentedHash = sha256Hex(args.refreshToken)
|
||||
const grant = await this.repository.findGrantByRefreshHash(presentedHash)
|
||||
if (!grant) {
|
||||
return { ok: false, error: 'invalid_grant', description: 'Refresh token is not valid' }
|
||||
}
|
||||
if (grant.revokedAt) {
|
||||
return { ok: false, error: 'invalid_grant', description: 'This authorization has been revoked' }
|
||||
}
|
||||
|
||||
// The previous token in the rotation chain showing up means it leaked.
|
||||
if (grant.refreshTokenPrevHash && safeCompareHex(grant.refreshTokenPrevHash, presentedHash)) {
|
||||
await this.repository.revokeGrant({ grantId: grant.id })
|
||||
return { ok: false, error: 'invalid_grant', description: 'Refresh token was reused; the authorization has been revoked' }
|
||||
}
|
||||
if (grant.refreshExpiresAt && grant.refreshExpiresAt < new Date()) {
|
||||
return { ok: false, error: 'invalid_grant', description: 'Refresh token has expired' }
|
||||
}
|
||||
if (grant.clientId !== args.clientId) {
|
||||
return { ok: false, error: 'invalid_grant', description: 'Refresh token was issued to another client' }
|
||||
}
|
||||
if (!resourceMatches({ granted: grant.resource, requested: args.resource })) {
|
||||
return { ok: false, error: 'invalid_target', description: 'resource does not match the granted audience' }
|
||||
}
|
||||
|
||||
const client = await this.repository.findClientByClientId(grant.clientId)
|
||||
return this.issueTokenPair({ grant, clientName: client?.name ?? grant.clientId, prevRefreshHash: presentedHash })
|
||||
}
|
||||
|
||||
async registerClient(args: RegisterClientArgs): Promise<OAuthResult<{ clientId: string; clientSecret: string | null }>> {
|
||||
const clientId = randomBytes(16).toString('hex')
|
||||
const clientSecret = args.isPublic ? null : randomToken()
|
||||
|
||||
const client = await this.repository.createClient({
|
||||
clientId,
|
||||
clientSecretHash: clientSecret ? sha256Hex(clientSecret) : null,
|
||||
name: args.name.slice(0, 200),
|
||||
redirectUris: args.redirectUris,
|
||||
createdVia: 'dcr',
|
||||
})
|
||||
if (!client) {
|
||||
return { ok: false, error: 'server_error', description: 'Could not register the client' }
|
||||
}
|
||||
return { ok: true, value: { clientId, clientSecret } }
|
||||
}
|
||||
|
||||
async authenticateClient(args: AuthenticateClientArgs): Promise<OAuthResult<OAuthClientsSchemaTypeForSelect>> {
|
||||
const client = await this.repository.findClientByClientId(args.clientId)
|
||||
if (!client) {
|
||||
return { ok: false, error: 'invalid_client', description: 'Unknown client_id' }
|
||||
}
|
||||
if (client.clientSecretHash) {
|
||||
if (!args.clientSecret || !safeCompareHex(client.clientSecretHash, sha256Hex(args.clientSecret))) {
|
||||
return { ok: false, error: 'invalid_client', description: 'Client authentication failed' }
|
||||
}
|
||||
}
|
||||
return { ok: true, value: client }
|
||||
}
|
||||
|
||||
async fetchConnectedApps(userId: number): Promise<ConnectedApp[]> {
|
||||
const grants = await this.repository.fetchGrantsByUserId(userId)
|
||||
if (!grants.length) return []
|
||||
|
||||
const clients = await this.repository.fetchClientsByClientIds(grants.map((grant) => grant.clientId))
|
||||
const nameByClientId = new Map(clients.map((client) => [client.clientId, client.name]))
|
||||
|
||||
return grants.map((grant) => ({
|
||||
grantId: grant.id,
|
||||
clientId: grant.clientId,
|
||||
clientName: nameByClientId.get(grant.clientId) ?? grant.clientId,
|
||||
allowedPermissions: grant.allowedPermissions,
|
||||
allowedGoalIds: grant.allowedGoalIds,
|
||||
createdAt: grant.createdAt,
|
||||
lastUsedAt: grant.lastUsedAt,
|
||||
}))
|
||||
}
|
||||
|
||||
async revokeGrant(args: RevokeOwnGrantArgs): Promise<boolean> {
|
||||
return this.repository.revokeGrant(args)
|
||||
}
|
||||
|
||||
/** RFC 7009: accepts either an access token or a refresh token. */
|
||||
async revokeToken(token: string): Promise<void> {
|
||||
const hash = sha256Hex(token)
|
||||
|
||||
const grantId = await this.repository.findGrantIdByAccessTokenHash(hash)
|
||||
if (grantId) {
|
||||
await this.repository.revokeGrant({ grantId })
|
||||
return
|
||||
}
|
||||
|
||||
const grant = await this.repository.findGrantByRefreshHash(hash)
|
||||
if (grant) await this.repository.revokeGrant({ grantId: grant.id })
|
||||
}
|
||||
|
||||
private async issueTokenPair(args: IssueTokenPairArgs): Promise<OAuthResult<OAuthTokenResponse>> {
|
||||
// Copied straight from the grant: these are the RBAC keys the user
|
||||
// ticked. An empty list means "do not narrow anything", the same thing
|
||||
// it means for a manually issued tvk_ token.
|
||||
const allowedPermissions = args.grant.allowedPermissions
|
||||
const accessToken = OAUTH_ACCESS_TOKEN_PREFIX + randomToken()
|
||||
const refreshToken = randomToken()
|
||||
const now = Date.now()
|
||||
|
||||
const rotated = await this.repository.rotateRefreshToken({
|
||||
grantId: args.grant.id,
|
||||
refreshTokenHash: sha256Hex(refreshToken),
|
||||
prevHash: args.prevRefreshHash ?? null,
|
||||
refreshExpiresAt: new Date(now + OAUTH_REFRESH_TOKEN_TTL_SECONDS * 1000),
|
||||
presentedHash: args.prevRefreshHash ?? null,
|
||||
})
|
||||
if (!rotated) {
|
||||
return { ok: false, error: 'invalid_grant', description: 'This authorization has been revoked' }
|
||||
}
|
||||
|
||||
const created = await this.repository.createAccessToken({
|
||||
userId: args.grant.userId,
|
||||
name: args.clientName.slice(0, 100),
|
||||
tokenHash: sha256Hex(accessToken),
|
||||
allowedPermissions,
|
||||
allowedGoalIds: args.grant.allowedGoalIds,
|
||||
grantId: args.grant.id,
|
||||
expiresAt: new Date(now + OAUTH_ACCESS_TOKEN_TTL_SECONDS * 1000),
|
||||
})
|
||||
if (!created) {
|
||||
return { ok: false, error: 'server_error', description: 'Could not issue the access token' }
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
access_token: accessToken,
|
||||
token_type: 'Bearer',
|
||||
expires_in: OAUTH_ACCESS_TOKEN_TTL_SECONDS,
|
||||
refresh_token: refreshToken,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import { and, eq, isNull, lt, or } from 'drizzle-orm'
|
||||
import {
|
||||
ApiTokensSchema,
|
||||
OAuthAuthCodesSchema,
|
||||
OAuthClientsSchema,
|
||||
OAuthGrantsSchema,
|
||||
type OAuthAuthCodesSchemaTypeForSelect,
|
||||
type OAuthClientsSchemaTypeForSelect,
|
||||
type OAuthGrantsSchemaTypeForInsert,
|
||||
type OAuthGrantsSchemaTypeForSelect,
|
||||
} from 'taskview-db-schemas'
|
||||
import { Database } from '../../modules/db'
|
||||
import { callWithCatch } from '../../utils/helpers'
|
||||
import type {
|
||||
ConsumeAuthCodeArgs,
|
||||
CreateAccessTokenArgs,
|
||||
CreateAuthCodeArgs,
|
||||
CreateOAuthClientArgs,
|
||||
RevokeGrantArgs,
|
||||
RotateRefreshTokenArgs,
|
||||
} from './types'
|
||||
|
||||
export class OAuthRepository {
|
||||
private readonly db: Database
|
||||
|
||||
constructor() {
|
||||
this.db = Database.getInstance()
|
||||
}
|
||||
|
||||
async createClient(data: CreateOAuthClientArgs): Promise<OAuthClientsSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.insert(OAuthClientsSchema).values(data).returning(),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
async findClientByClientId(clientId: string): Promise<OAuthClientsSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select().from(OAuthClientsSchema).where(eq(OAuthClientsSchema.clientId, clientId)),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
async createAuthCode(data: CreateAuthCodeArgs & { codeHash: string; expiresAt: Date }): Promise<boolean> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.insert(OAuthAuthCodesSchema).values({
|
||||
codeHash: data.codeHash,
|
||||
clientId: data.clientId,
|
||||
userId: data.userId,
|
||||
redirectUri: data.redirectUri,
|
||||
codeChallenge: data.codeChallenge,
|
||||
codeChallengeMethod: data.codeChallengeMethod,
|
||||
allowedPermissions: data.allowedPermissions,
|
||||
allowedGoalIds: data.allowedGoalIds,
|
||||
resource: data.resource,
|
||||
expiresAt: data.expiresAt,
|
||||
}).returning(),
|
||||
)
|
||||
return !!result?.length
|
||||
}
|
||||
|
||||
async findAuthCodeByHash(codeHash: string): Promise<OAuthAuthCodesSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select().from(OAuthAuthCodesSchema).where(eq(OAuthAuthCodesSchema.codeHash, codeHash)),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-use redemption. The UPDATE only matches while used_at is still NULL,
|
||||
* so two concurrent exchanges of the same code cannot both win.
|
||||
*/
|
||||
async consumeAuthCode(args: ConsumeAuthCodeArgs): Promise<boolean> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.update(OAuthAuthCodesSchema)
|
||||
.set({ usedAt: new Date(), grantId: args.grantId })
|
||||
.where(and(eq(OAuthAuthCodesSchema.id, args.id), isNull(OAuthAuthCodesSchema.usedAt))),
|
||||
)
|
||||
return !!result?.rowCount
|
||||
}
|
||||
|
||||
async deleteExpiredAuthCodes(): Promise<void> {
|
||||
await callWithCatch(() =>
|
||||
this.db.dbDrizzle.delete(OAuthAuthCodesSchema).where(lt(OAuthAuthCodesSchema.expiresAt, new Date())),
|
||||
)
|
||||
}
|
||||
|
||||
async createGrant(data: OAuthGrantsSchemaTypeForInsert): Promise<OAuthGrantsSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.insert(OAuthGrantsSchema).values(data).returning(),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
/** Matches the current refresh token or the previous one, so replay is detectable. */
|
||||
async findGrantByRefreshHash(refreshTokenHash: string): Promise<OAuthGrantsSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select().from(OAuthGrantsSchema).where(
|
||||
or(
|
||||
eq(OAuthGrantsSchema.refreshTokenHash, refreshTokenHash),
|
||||
eq(OAuthGrantsSchema.refreshTokenPrevHash, refreshTokenHash),
|
||||
),
|
||||
),
|
||||
)
|
||||
return result?.[0] ?? null
|
||||
}
|
||||
|
||||
async rotateRefreshToken(args: RotateRefreshTokenArgs): Promise<boolean> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.update(OAuthGrantsSchema)
|
||||
.set({
|
||||
refreshTokenHash: args.refreshTokenHash,
|
||||
refreshTokenPrevHash: args.prevHash,
|
||||
refreshExpiresAt: args.refreshExpiresAt,
|
||||
lastUsedAt: new Date(),
|
||||
})
|
||||
.where(and(
|
||||
eq(OAuthGrantsSchema.id, args.grantId),
|
||||
isNull(OAuthGrantsSchema.revokedAt),
|
||||
// The presented token must still be the current one. Without this,
|
||||
// two concurrent refreshes both succeed and the second overwrites
|
||||
// the first, silently orphaning the refresh token it just handed out.
|
||||
args.presentedHash
|
||||
? eq(OAuthGrantsSchema.refreshTokenHash, args.presentedHash)
|
||||
: isNull(OAuthGrantsSchema.refreshTokenHash),
|
||||
)),
|
||||
)
|
||||
return !!result?.rowCount
|
||||
}
|
||||
|
||||
async fetchGrantsByUserId(userId: number): Promise<OAuthGrantsSchemaTypeForSelect[]> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select().from(OAuthGrantsSchema).where(
|
||||
and(eq(OAuthGrantsSchema.userId, userId), isNull(OAuthGrantsSchema.revokedAt)),
|
||||
),
|
||||
)
|
||||
return result ?? []
|
||||
}
|
||||
|
||||
async fetchClientsByClientIds(clientIds: string[]): Promise<OAuthClientsSchemaTypeForSelect[]> {
|
||||
if (!clientIds.length) return []
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select().from(OAuthClientsSchema),
|
||||
)
|
||||
return (result ?? []).filter((client) => clientIds.includes(client.clientId))
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoking a grant also deletes its live access tokens — that is the whole
|
||||
* point of storing them as opaque rows instead of self-contained JWTs.
|
||||
*/
|
||||
async revokeGrant(args: RevokeGrantArgs): Promise<boolean> {
|
||||
const where = args.userId === undefined
|
||||
? eq(OAuthGrantsSchema.id, args.grantId)
|
||||
: and(eq(OAuthGrantsSchema.id, args.grantId), eq(OAuthGrantsSchema.userId, args.userId))
|
||||
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.update(OAuthGrantsSchema)
|
||||
.set({ revokedAt: new Date(), refreshTokenHash: null, refreshTokenPrevHash: null })
|
||||
.where(where),
|
||||
)
|
||||
if (!result?.rowCount) return false
|
||||
|
||||
await callWithCatch(() =>
|
||||
this.db.dbDrizzle.delete(ApiTokensSchema).where(eq(ApiTokensSchema.grantId, args.grantId)),
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
async createAccessToken(data: CreateAccessTokenArgs): Promise<boolean> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.insert(ApiTokensSchema).values(data).returning(),
|
||||
)
|
||||
return !!result?.length
|
||||
}
|
||||
|
||||
async findGrantIdByAccessTokenHash(tokenHash: string): Promise<number | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle.select({ grantId: ApiTokensSchema.grantId })
|
||||
.from(ApiTokensSchema)
|
||||
.where(eq(ApiTokensSchema.tokenHash, tokenHash)),
|
||||
)
|
||||
return result?.[0]?.grantId ?? null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Router } from 'express'
|
||||
import type { Routable } from '../../types/routable.type'
|
||||
import { IsLoggedIn } from '../auth/middlewares/is-logged-in'
|
||||
import { RejectApiTokenAuth } from '../api-tokens/middlewares/RejectApiTokenAuth'
|
||||
import { OAuthController } from './OAuthController'
|
||||
|
||||
export default class OAuthRoutes implements Routable {
|
||||
private readonly router: ReturnType<typeof Router>
|
||||
private readonly controller: OAuthController
|
||||
|
||||
constructor() {
|
||||
this.router = Router()
|
||||
this.controller = new OAuthController()
|
||||
this.initRoutes()
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.get('/authorize', this.controller.authorize)
|
||||
this.router.post('/token', this.controller.token)
|
||||
this.router.post('/revoke', this.controller.revoke)
|
||||
this.router.post('/register', this.controller.register)
|
||||
|
||||
// Consent is the one place a real human decides. It must be a browser
|
||||
// session, never an API token acting on the user's behalf.
|
||||
this.router.post('/consent', [IsLoggedIn, RejectApiTokenAuth], this.controller.consent)
|
||||
this.router.post('/consent/deny', [IsLoggedIn, RejectApiTokenAuth], this.controller.denyConsent)
|
||||
|
||||
this.router.get('/connected-apps', [IsLoggedIn, RejectApiTokenAuth], this.controller.fetchConnectedApps)
|
||||
this.router.delete('/connected-apps', [IsLoggedIn, RejectApiTokenAuth], this.controller.revokeConnectedApp)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Router } from 'express'
|
||||
import type { Routable } from '../../types/routable.type'
|
||||
import { OAuthController } from './OAuthController'
|
||||
|
||||
/**
|
||||
* RFC 8414 / RFC 9728 discovery. These must sit at the origin root, not under
|
||||
* /module, because that is where clients look before they have any credentials.
|
||||
*/
|
||||
export default class OAuthWellKnownRoutes implements Routable {
|
||||
private readonly router: ReturnType<typeof Router>
|
||||
private readonly controller: OAuthController
|
||||
|
||||
constructor() {
|
||||
this.router = Router()
|
||||
this.controller = new OAuthController()
|
||||
this.initRoutes()
|
||||
}
|
||||
|
||||
getRouter() {
|
||||
return this.router
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.get('/oauth-authorization-server', this.controller.authorizationServerMetadata)
|
||||
this.router.get('/oauth-protected-resource', this.controller.protectedResourceMetadata)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,52 @@
|
||||
import axios from 'axios';
|
||||
import type http from 'http';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import App from '../../../App';
|
||||
|
||||
const port = 1812;
|
||||
const url = `http://localhost:${port}`;
|
||||
|
||||
let server: http.Server;
|
||||
const api = axios.create({ baseURL: url, validateStatus: () => true });
|
||||
|
||||
/**
|
||||
* OAUTH_DYNAMIC_REGISTRATION=false is the lever a self-hosted operator pulls to
|
||||
* keep the client registry closed. It has to do two things: refuse registration,
|
||||
* and stop advertising the endpoint — a client that reads the metadata should
|
||||
* never attempt a registration this instance will reject.
|
||||
*/
|
||||
describe('OAuth with dynamic client registration disabled', () => {
|
||||
vi.mock('emailjs', () => ({
|
||||
SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
|
||||
}));
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.OAUTH_DYNAMIC_REGISTRATION = 'false';
|
||||
server = new App(port).listen();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
server?.close();
|
||||
delete process.env.OAUTH_DYNAMIC_REGISTRATION;
|
||||
});
|
||||
|
||||
it('refuses to register a client', async () => {
|
||||
const response = await api.post('/module/oauth/register', {
|
||||
client_name: 'Should be refused',
|
||||
redirect_uris: ['https://client.test/cb'],
|
||||
});
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(response.data.error).toBe('access_denied');
|
||||
});
|
||||
|
||||
it('stops advertising the registration endpoint in the metadata', async () => {
|
||||
const response = await api.get('/.well-known/oauth-authorization-server');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.data.registration_endpoint).toBeUndefined();
|
||||
// The rest of the flow stays available for manually seeded clients.
|
||||
expect(response.data.authorization_endpoint).toContain('/module/oauth/authorize');
|
||||
expect(response.data.token_endpoint).toContain('/module/oauth/token');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,328 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createHash, randomBytes } from 'crypto'
|
||||
|
||||
const repositoryMock = {
|
||||
findClientByClientId: vi.fn(),
|
||||
findAuthCodeByHash: vi.fn(),
|
||||
consumeAuthCode: vi.fn(),
|
||||
createGrant: vi.fn(),
|
||||
createAccessToken: vi.fn(),
|
||||
rotateRefreshToken: vi.fn(),
|
||||
revokeGrant: vi.fn(),
|
||||
findGrantByRefreshHash: vi.fn(),
|
||||
findGrantIdByAccessTokenHash: vi.fn(),
|
||||
createAuthCode: vi.fn(),
|
||||
deleteExpiredAuthCodes: vi.fn(),
|
||||
}
|
||||
|
||||
vi.mock('../OAuthRepository', () => ({
|
||||
OAuthRepository: vi.fn(() => repositoryMock),
|
||||
}))
|
||||
|
||||
const { OAuthManager } = await import('../OAuthManager')
|
||||
|
||||
const sha256 = (value: string) => createHash('sha256').update(value).digest('hex')
|
||||
const VERIFIER = randomBytes(40).toString('base64url')
|
||||
const CHALLENGE = createHash('sha256').update(VERIFIER).digest('base64url')
|
||||
|
||||
const validCode = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 1,
|
||||
codeHash: sha256('the-code'),
|
||||
clientId: 'client-a',
|
||||
userId: 7,
|
||||
redirectUri: 'https://app.example.com/cb',
|
||||
codeChallenge: CHALLENGE,
|
||||
codeChallengeMethod: 'S256',
|
||||
allowedPermissions: ['goal_can_watch_content'],
|
||||
allowedGoalIds: [],
|
||||
resource: null,
|
||||
expiresAt: new Date(Date.now() + 60_000),
|
||||
usedAt: null,
|
||||
grantId: null,
|
||||
createdAt: new Date(),
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const validGrant = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 42,
|
||||
userId: 7,
|
||||
clientId: 'client-a',
|
||||
allowedPermissions: ['goal_can_watch_content'],
|
||||
allowedGoalIds: [],
|
||||
resource: null,
|
||||
refreshTokenHash: sha256('current-refresh'),
|
||||
refreshTokenPrevHash: null,
|
||||
refreshExpiresAt: new Date(Date.now() + 86_400_000),
|
||||
lastUsedAt: null,
|
||||
revokedAt: null,
|
||||
createdAt: new Date(),
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const exchangeArgs = (overrides: Record<string, unknown> = {}) => ({
|
||||
code: 'the-code',
|
||||
codeVerifier: VERIFIER,
|
||||
clientId: 'client-a',
|
||||
redirectUri: 'https://app.example.com/cb',
|
||||
resource: null,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('OAuthManager.exchangeCode', () => {
|
||||
let manager: InstanceType<typeof OAuthManager>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
manager = new OAuthManager()
|
||||
repositoryMock.findClientByClientId.mockResolvedValue({ clientId: 'client-a', name: 'Client A' })
|
||||
repositoryMock.createGrant.mockResolvedValue(validGrant())
|
||||
repositoryMock.consumeAuthCode.mockResolvedValue(true)
|
||||
repositoryMock.rotateRefreshToken.mockResolvedValue(true)
|
||||
repositoryMock.createAccessToken.mockResolvedValue(true)
|
||||
repositoryMock.revokeGrant.mockResolvedValue(true)
|
||||
})
|
||||
|
||||
it('issues a tvo_ access token and a refresh token on a valid exchange', async () => {
|
||||
repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())
|
||||
|
||||
const result = await manager.exchangeCode(exchangeArgs())
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.value.access_token.startsWith('tvo_')).toBe(true)
|
||||
expect(result.value.refresh_token).toBeTruthy()
|
||||
expect(result.value.token_type).toBe('Bearer')
|
||||
})
|
||||
|
||||
it('stores only the hash of the access token, never the token itself', async () => {
|
||||
repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())
|
||||
|
||||
const result = await manager.exchangeCode(exchangeArgs())
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
const stored = repositoryMock.createAccessToken.mock.calls[0][0]
|
||||
expect(stored.tokenHash).toBe(sha256(result.value.access_token))
|
||||
expect(JSON.stringify(stored)).not.toContain(result.value.access_token)
|
||||
})
|
||||
|
||||
it('rejects a wrong code_verifier', async () => {
|
||||
repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())
|
||||
|
||||
const result = await manager.exchangeCode(exchangeArgs({ codeVerifier: randomBytes(40).toString('base64url') }))
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })
|
||||
expect(repositoryMock.createGrant).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a redirect_uri that differs from the authorization request', async () => {
|
||||
repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())
|
||||
|
||||
const result = await manager.exchangeCode(exchangeArgs({ redirectUri: 'https://app.example.com/other' }))
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })
|
||||
})
|
||||
|
||||
it('rejects a code presented by a different client', async () => {
|
||||
repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())
|
||||
|
||||
const result = await manager.exchangeCode(exchangeArgs({ clientId: 'client-b' }))
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })
|
||||
})
|
||||
|
||||
it('rejects an expired code', async () => {
|
||||
repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode({ expiresAt: new Date(Date.now() - 1000) }))
|
||||
|
||||
const result = await manager.exchangeCode(exchangeArgs())
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })
|
||||
})
|
||||
|
||||
it('revokes the original grant when a used code is replayed', async () => {
|
||||
repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode({ usedAt: new Date(), grantId: 42 }))
|
||||
|
||||
const result = await manager.exchangeCode(exchangeArgs())
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })
|
||||
expect(repositoryMock.revokeGrant).toHaveBeenCalledWith({ grantId: 42 })
|
||||
})
|
||||
|
||||
it('rolls back the grant when the code was consumed by a concurrent request', async () => {
|
||||
repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())
|
||||
repositoryMock.consumeAuthCode.mockResolvedValue(false)
|
||||
|
||||
const result = await manager.exchangeCode(exchangeArgs())
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })
|
||||
expect(repositoryMock.revokeGrant).toHaveBeenCalledWith({ grantId: 42 })
|
||||
})
|
||||
|
||||
it('rejects a resource that does not match the authorization request', async () => {
|
||||
repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode({ resource: 'https://mcp.example.com' }))
|
||||
|
||||
const result = await manager.exchangeCode(exchangeArgs({ resource: 'https://other.example.com' }))
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_target' })
|
||||
})
|
||||
|
||||
it('rejects an unknown code', async () => {
|
||||
repositoryMock.findAuthCodeByHash.mockResolvedValue(null)
|
||||
|
||||
const result = await manager.exchangeCode(exchangeArgs())
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('OAuthManager.refreshTokens', () => {
|
||||
let manager: InstanceType<typeof OAuthManager>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
manager = new OAuthManager()
|
||||
repositoryMock.findClientByClientId.mockResolvedValue({ clientId: 'client-a', name: 'Client A' })
|
||||
repositoryMock.rotateRefreshToken.mockResolvedValue(true)
|
||||
repositoryMock.createAccessToken.mockResolvedValue(true)
|
||||
repositoryMock.revokeGrant.mockResolvedValue(true)
|
||||
})
|
||||
|
||||
it('rotates the refresh token and keeps the presented one as the previous hash', async () => {
|
||||
repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant())
|
||||
|
||||
const result = await manager.refreshTokens({
|
||||
refreshToken: 'current-refresh',
|
||||
clientId: 'client-a',
|
||||
resource: null,
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.value.refresh_token).not.toBe('current-refresh')
|
||||
|
||||
const rotation = repositoryMock.rotateRefreshToken.mock.calls[0][0]
|
||||
expect(rotation.prevHash).toBe(sha256('current-refresh'))
|
||||
expect(rotation.refreshTokenHash).toBe(sha256(result.value.refresh_token))
|
||||
})
|
||||
|
||||
it('revokes the whole grant when a superseded refresh token is replayed', async () => {
|
||||
repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant({
|
||||
refreshTokenHash: sha256('rotated-refresh'),
|
||||
refreshTokenPrevHash: sha256('leaked-refresh'),
|
||||
}))
|
||||
|
||||
const result = await manager.refreshTokens({
|
||||
refreshToken: 'leaked-refresh',
|
||||
clientId: 'client-a',
|
||||
resource: null,
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })
|
||||
expect(repositoryMock.revokeGrant).toHaveBeenCalledWith({ grantId: 42 })
|
||||
})
|
||||
|
||||
it('refuses a revoked grant', async () => {
|
||||
repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant({ revokedAt: new Date() }))
|
||||
|
||||
const result = await manager.refreshTokens({
|
||||
refreshToken: 'current-refresh',
|
||||
clientId: 'client-a',
|
||||
resource: null,
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })
|
||||
})
|
||||
|
||||
it('refuses an expired refresh token', async () => {
|
||||
repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant({
|
||||
refreshExpiresAt: new Date(Date.now() - 1000),
|
||||
}))
|
||||
|
||||
const result = await manager.refreshTokens({
|
||||
refreshToken: 'current-refresh',
|
||||
clientId: 'client-a',
|
||||
resource: null,
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })
|
||||
})
|
||||
|
||||
it('refuses a refresh token presented by another client', async () => {
|
||||
repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant())
|
||||
|
||||
const result = await manager.refreshTokens({
|
||||
refreshToken: 'current-refresh',
|
||||
clientId: 'client-b',
|
||||
resource: null,
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })
|
||||
})
|
||||
|
||||
it('carries the consented permission keys onto the reissued token', async () => {
|
||||
repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant({
|
||||
allowedPermissions: ['timetracking_can_view', 'task_can_edit_status'],
|
||||
}))
|
||||
|
||||
await manager.refreshTokens({ refreshToken: 'current-refresh', clientId: 'client-a', resource: null })
|
||||
|
||||
const stored = repositoryMock.createAccessToken.mock.calls[0][0]
|
||||
expect(stored.allowedPermissions).toEqual(['timetracking_can_view', 'task_can_edit_status'])
|
||||
})
|
||||
|
||||
it('keeps an unrestricted grant unrestricted, which is what "all permissions" means', async () => {
|
||||
repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant({ allowedPermissions: [] }))
|
||||
|
||||
await manager.refreshTokens({ refreshToken: 'current-refresh', clientId: 'client-a', resource: null })
|
||||
|
||||
const stored = repositoryMock.createAccessToken.mock.calls[0][0]
|
||||
expect(stored.allowedPermissions).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('OAuthManager.authenticateClient', () => {
|
||||
let manager: InstanceType<typeof OAuthManager>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
manager = new OAuthManager()
|
||||
})
|
||||
|
||||
it('accepts a public client with no secret', async () => {
|
||||
repositoryMock.findClientByClientId.mockResolvedValue({ clientId: 'pub', clientSecretHash: null })
|
||||
|
||||
const result = await manager.authenticateClient({ clientId: 'pub' })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a confidential client presenting the wrong secret', async () => {
|
||||
repositoryMock.findClientByClientId.mockResolvedValue({
|
||||
clientId: 'conf',
|
||||
clientSecretHash: sha256('right'),
|
||||
})
|
||||
|
||||
const result = await manager.authenticateClient({ clientId: 'conf', clientSecret: 'wrong' })
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_client' })
|
||||
})
|
||||
|
||||
it('rejects a confidential client presenting no secret at all', async () => {
|
||||
repositoryMock.findClientByClientId.mockResolvedValue({
|
||||
clientId: 'conf',
|
||||
clientSecretHash: sha256('right'),
|
||||
})
|
||||
|
||||
const result = await manager.authenticateClient({ clientId: 'conf' })
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_client' })
|
||||
})
|
||||
|
||||
it('rejects an unknown client', async () => {
|
||||
repositoryMock.findClientByClientId.mockResolvedValue(null)
|
||||
|
||||
const result = await manager.authenticateClient({ clientId: 'nope' })
|
||||
|
||||
expect(result).toMatchObject({ ok: false, error: 'invalid_client' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,158 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { createHash, randomBytes } from 'crypto'
|
||||
import {
|
||||
buildRedirectUrl,
|
||||
isAcceptableRedirectUri,
|
||||
matchesRegisteredRedirectUri,
|
||||
resourceMatches,
|
||||
verifyPkce,
|
||||
} from '../oauth.utils'
|
||||
|
||||
const challengeFor = (verifier: string) =>
|
||||
createHash('sha256').update(verifier).digest('base64url')
|
||||
|
||||
describe('verifyPkce', () => {
|
||||
const verifier = randomBytes(40).toString('base64url')
|
||||
|
||||
it('accepts the verifier that produced the challenge', () => {
|
||||
expect(verifyPkce({ codeVerifier: verifier, codeChallenge: challengeFor(verifier) })).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a different verifier', () => {
|
||||
const other = randomBytes(40).toString('base64url')
|
||||
expect(verifyPkce({ codeVerifier: other, codeChallenge: challengeFor(verifier) })).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a verifier shorter than the RFC 7636 minimum', () => {
|
||||
const short = 'abc'
|
||||
expect(verifyPkce({ codeVerifier: short, codeChallenge: challengeFor(short) })).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a verifier longer than the RFC 7636 maximum', () => {
|
||||
const long = 'a'.repeat(129)
|
||||
expect(verifyPkce({ codeVerifier: long, codeChallenge: challengeFor(long) })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('matchesRegisteredRedirectUri', () => {
|
||||
it('accepts an exact match', () => {
|
||||
expect(matchesRegisteredRedirectUri({
|
||||
candidate: 'https://chat.example.com/callback',
|
||||
registered: ['https://chat.example.com/callback'],
|
||||
})).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a different path on the same host', () => {
|
||||
expect(matchesRegisteredRedirectUri({
|
||||
candidate: 'https://chat.example.com/evil',
|
||||
registered: ['https://chat.example.com/callback'],
|
||||
})).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects an attacker host that merely prefixes the registered one', () => {
|
||||
expect(matchesRegisteredRedirectUri({
|
||||
candidate: 'https://chat.example.com.evil.test/callback',
|
||||
registered: ['https://chat.example.com/callback'],
|
||||
})).toBe(false)
|
||||
})
|
||||
|
||||
it('allows any loopback port for the same path (RFC 8252)', () => {
|
||||
expect(matchesRegisteredRedirectUri({
|
||||
candidate: 'http://127.0.0.1:55123/callback',
|
||||
registered: ['http://127.0.0.1:8080/callback'],
|
||||
})).toBe(true)
|
||||
})
|
||||
|
||||
it('does not extend the loopback port carve-out to other hosts', () => {
|
||||
expect(matchesRegisteredRedirectUri({
|
||||
candidate: 'https://example.com:9999/callback',
|
||||
registered: ['https://example.com:443/callback'],
|
||||
})).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a loopback candidate whose path differs', () => {
|
||||
expect(matchesRegisteredRedirectUri({
|
||||
candidate: 'http://127.0.0.1:55123/other',
|
||||
registered: ['http://127.0.0.1:8080/callback'],
|
||||
})).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects an unparseable candidate', () => {
|
||||
expect(matchesRegisteredRedirectUri({
|
||||
candidate: 'not a url',
|
||||
registered: ['https://chat.example.com/callback'],
|
||||
})).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isAcceptableRedirectUri', () => {
|
||||
it('accepts https', () => {
|
||||
expect(isAcceptableRedirectUri('https://example.com/cb')).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts loopback http', () => {
|
||||
expect(isAcceptableRedirectUri('http://127.0.0.1:1234/cb')).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a URI carrying a fragment', () => {
|
||||
expect(isAcceptableRedirectUri('https://example.com/cb#token')).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts a private-use scheme, which is how native apps come back (RFC 8252)', () => {
|
||||
expect(isAcceptableRedirectUri('com.example.app://oauth/callback')).toBe(true)
|
||||
expect(isAcceptableRedirectUri('myapp://callback')).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects schemes where redirecting would execute something', () => {
|
||||
expect(isAcceptableRedirectUri('javascript:alert(1)')).toBe(false)
|
||||
expect(isAcceptableRedirectUri('data:text/html,<script>alert(1)</script>')).toBe(false)
|
||||
expect(isAcceptableRedirectUri('vbscript:msgbox(1)')).toBe(false)
|
||||
expect(isAcceptableRedirectUri('file:///etc/passwd')).toBe(false)
|
||||
expect(isAcceptableRedirectUri('blob:https://example.com/x')).toBe(false)
|
||||
expect(isAcceptableRedirectUri('about:blank')).toBe(false)
|
||||
})
|
||||
|
||||
it('still refuses plaintext http off loopback', () => {
|
||||
expect(isAcceptableRedirectUri('http://evil.example.com/cb')).toBe(false)
|
||||
})
|
||||
|
||||
it('still refuses a fragment on any scheme', () => {
|
||||
expect(isAcceptableRedirectUri('com.example.app://cb#token')).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a string that is not a URL at all', () => {
|
||||
expect(isAcceptableRedirectUri('not a url')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildRedirectUrl', () => {
|
||||
it('appends parameters and skips undefined ones', () => {
|
||||
const url = buildRedirectUrl({
|
||||
redirectUri: 'https://example.com/cb?existing=1',
|
||||
params: { code: 'abc', state: undefined },
|
||||
})
|
||||
expect(url).toBe('https://example.com/cb?existing=1&code=abc')
|
||||
})
|
||||
|
||||
it('encodes parameter values', () => {
|
||||
const url = buildRedirectUrl({
|
||||
redirectUri: 'https://example.com/cb',
|
||||
params: { state: 'a b&c' },
|
||||
})
|
||||
expect(url).toContain('state=a+b%26c')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resourceMatches', () => {
|
||||
it('ignores a trailing slash', () => {
|
||||
expect(resourceMatches({ granted: 'https://mcp.example.com/', requested: 'https://mcp.example.com' })).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a token replayed against another resource', () => {
|
||||
expect(resourceMatches({ granted: 'https://mcp.example.com', requested: 'https://other.example.com' })).toBe(false)
|
||||
})
|
||||
|
||||
it('is permissive when the grant carries no audience', () => {
|
||||
expect(resourceMatches({ granted: null, requested: 'https://mcp.example.com' })).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,116 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from 'crypto'
|
||||
import type {
|
||||
BuildRedirectUrlArgs,
|
||||
MatchRedirectUriArgs,
|
||||
ResourceMatchArgs,
|
||||
VerifyPkceArgs,
|
||||
} from './types'
|
||||
|
||||
export function isDcrEnabled(): boolean {
|
||||
const raw = process.env.OAUTH_DYNAMIC_REGISTRATION
|
||||
if (raw === undefined || raw.trim() === '') return true
|
||||
return raw.trim().toLowerCase() === 'true'
|
||||
}
|
||||
|
||||
export function sha256Hex(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex')
|
||||
}
|
||||
|
||||
export function randomToken(): string {
|
||||
return randomBytes(32).toString('hex')
|
||||
}
|
||||
|
||||
export function safeCompareHex(a: string, b: string): boolean {
|
||||
if (a.length !== b.length) return false
|
||||
return timingSafeEqual(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'))
|
||||
}
|
||||
|
||||
export function verifyPkce(args: VerifyPkceArgs): boolean {
|
||||
if (args.codeVerifier.length < 43 || args.codeVerifier.length > 128) return false
|
||||
const digest = createHash('sha256').update(args.codeVerifier).digest('base64url')
|
||||
return safeCompareHex(digest, args.codeChallenge)
|
||||
}
|
||||
|
||||
function isLoopbackUrl(url: URL): boolean {
|
||||
return url.hostname === '127.0.0.1'
|
||||
|| url.hostname === '::1'
|
||||
|| url.hostname === '[::1]'
|
||||
|| url.hostname === 'localhost'
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact match, with one carve-out: RFC 8252 lets a native client bind an
|
||||
* arbitrary loopback port, so the port is ignored for 127.0.0.1 / ::1 only.
|
||||
* Everything else must match the registered string exactly — this is the guard
|
||||
* against turning /authorize into an open redirect.
|
||||
*/
|
||||
export function matchesRegisteredRedirectUri(args: MatchRedirectUriArgs): boolean {
|
||||
if (args.registered.includes(args.candidate)) return true
|
||||
|
||||
let candidateUrl: URL
|
||||
try {
|
||||
candidateUrl = new URL(args.candidate)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (!isLoopbackUrl(candidateUrl)) return false
|
||||
|
||||
return args.registered.some((registered) => {
|
||||
try {
|
||||
const registeredUrl = new URL(registered)
|
||||
return (
|
||||
isLoopbackUrl(registeredUrl)
|
||||
&& registeredUrl.protocol === candidateUrl.protocol
|
||||
&& registeredUrl.hostname === candidateUrl.hostname
|
||||
&& registeredUrl.pathname === candidateUrl.pathname
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Schemes where "redirecting" means executing something rather than handing
|
||||
* control to an application. Everything else is allowed: RFC 8252 §7.1 has
|
||||
* native apps return through a private-use scheme (com.example.app://), and
|
||||
* refusing those locks every mobile client out of the flow. Interception of a
|
||||
* private-use scheme by another app on the device is what PKCE — mandatory here,
|
||||
* S256 only — exists to make useless.
|
||||
*/
|
||||
const DANGEROUS_REDIRECT_SCHEMES = ['javascript:', 'data:', 'vbscript:', 'file:', 'blob:', 'about:']
|
||||
|
||||
export function isAcceptableRedirectUri(raw: string): boolean {
|
||||
let parsed: URL
|
||||
try {
|
||||
parsed = new URL(raw)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (parsed.hash) return false
|
||||
if (DANGEROUS_REDIRECT_SCHEMES.includes(parsed.protocol)) return false
|
||||
if (parsed.protocol === 'https:') return true
|
||||
// http stays loopback-only. There is deliberately no NODE_ENV escape hatch:
|
||||
// an install running without NODE_ENV=production would otherwise let any
|
||||
// client register a plaintext redirect to a host it does not control.
|
||||
if (parsed.protocol === 'http:') return isLoopbackUrl(parsed)
|
||||
return true
|
||||
}
|
||||
|
||||
export function buildRedirectUrl(args: BuildRedirectUrlArgs): string {
|
||||
const url = new URL(args.redirectUri)
|
||||
for (const [key, value] of Object.entries(args.params)) {
|
||||
if (value !== undefined) url.searchParams.set(key, value)
|
||||
}
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* RFC 8707 audience binding: a token minted for one MCP resource must not be
|
||||
* replayable against another. Compared on origin + path, ignoring trailing slash.
|
||||
*/
|
||||
export function resourceMatches(args: ResourceMatchArgs): boolean {
|
||||
if (!args.granted || !args.requested) return true
|
||||
const normalize = (value: string) => value.replace(/\/+$/, '').toLowerCase()
|
||||
return normalize(args.granted) === normalize(args.requested)
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import type { Response } from 'express'
|
||||
import type { OAuthGrantsSchemaTypeForSelect } from 'taskview-db-schemas'
|
||||
import { type } from 'arktype'
|
||||
|
||||
export const OAUTH_ACCESS_TOKEN_PREFIX = 'tvo_'
|
||||
export const OAUTH_CODE_TTL_SECONDS = 60
|
||||
export const OAUTH_ACCESS_TOKEN_TTL_SECONDS = 60 * 60
|
||||
export const OAUTH_REFRESH_TOKEN_TTL_SECONDS = 60 * 60 * 24 * 30
|
||||
|
||||
export const OAuthAuthorizeArkType = type({
|
||||
response_type: "'code'",
|
||||
client_id: 'string > 0',
|
||||
redirect_uri: 'string > 0',
|
||||
code_challenge: 'string > 0',
|
||||
code_challenge_method: "'S256'",
|
||||
'state?': 'string',
|
||||
'resource?': 'string',
|
||||
})
|
||||
|
||||
export type OAuthAuthorizeArgs = typeof OAuthAuthorizeArkType.infer
|
||||
|
||||
export const OAuthConsentArkType = type({
|
||||
client_id: 'string > 0',
|
||||
redirect_uri: 'string > 0',
|
||||
code_challenge: 'string > 0',
|
||||
code_challenge_method: "'S256'",
|
||||
'allowedPermissions?': 'string[]',
|
||||
'allowedGoalIds?': 'number[]',
|
||||
'state?': 'string',
|
||||
'resource?': 'string',
|
||||
})
|
||||
|
||||
export type OAuthConsentArgs = typeof OAuthConsentArkType.infer
|
||||
|
||||
export const OAuthTokenArkType = type({
|
||||
grant_type: "'authorization_code'|'refresh_token'",
|
||||
'client_id?': 'string',
|
||||
'client_secret?': 'string',
|
||||
'code?': 'string',
|
||||
'code_verifier?': 'string',
|
||||
'redirect_uri?': 'string',
|
||||
'refresh_token?': 'string',
|
||||
'resource?': 'string',
|
||||
})
|
||||
|
||||
export type OAuthTokenArgs = typeof OAuthTokenArkType.infer
|
||||
|
||||
export const OAuthRegisterArkType = type({
|
||||
'client_name?': 'string',
|
||||
redirect_uris: 'string[] > 0',
|
||||
'token_endpoint_auth_method?': 'string',
|
||||
'grant_types?': 'string[]',
|
||||
'response_types?': 'string[]',
|
||||
})
|
||||
|
||||
export type OAuthRegisterArgs = typeof OAuthRegisterArkType.infer
|
||||
|
||||
export const OAuthRevokeArkType = type({
|
||||
token: 'string > 0',
|
||||
'token_type_hint?': 'string',
|
||||
})
|
||||
|
||||
export type OAuthRevokeArgs = typeof OAuthRevokeArkType.infer
|
||||
|
||||
export type CreateAuthCodeArgs = {
|
||||
clientId: string
|
||||
userId: number
|
||||
redirectUri: string
|
||||
codeChallenge: string
|
||||
codeChallengeMethod: string
|
||||
allowedPermissions: string[]
|
||||
allowedGoalIds: number[]
|
||||
resource: string | null
|
||||
}
|
||||
|
||||
export type ExchangeCodeArgs = {
|
||||
code: string
|
||||
codeVerifier: string
|
||||
clientId: string
|
||||
redirectUri: string
|
||||
resource: string | null
|
||||
}
|
||||
|
||||
export type RefreshTokensArgs = {
|
||||
refreshToken: string
|
||||
clientId: string
|
||||
resource: string | null
|
||||
}
|
||||
|
||||
export type RegisterClientArgs = {
|
||||
name: string
|
||||
redirectUris: string[]
|
||||
isPublic: boolean
|
||||
}
|
||||
|
||||
export type OAuthTokenResponse = {
|
||||
access_token: string
|
||||
token_type: 'Bearer'
|
||||
expires_in: number
|
||||
refresh_token: string
|
||||
}
|
||||
|
||||
export type OAuthFailure = { ok: false; error: string; description: string }
|
||||
export type OAuthSuccess<T> = { ok: true; value: T }
|
||||
export type OAuthResult<T> = OAuthSuccess<T> | OAuthFailure
|
||||
|
||||
export type ConnectedApp = {
|
||||
grantId: number
|
||||
clientId: string
|
||||
clientName: string
|
||||
allowedPermissions: string[]
|
||||
allowedGoalIds: number[]
|
||||
createdAt: Date
|
||||
lastUsedAt: Date | null
|
||||
}
|
||||
|
||||
export type CreateOAuthClientArgs = {
|
||||
clientId: string
|
||||
clientSecretHash: string | null
|
||||
name: string
|
||||
redirectUris: string[]
|
||||
createdVia: string
|
||||
}
|
||||
|
||||
export type ConsumeAuthCodeArgs = {
|
||||
id: number
|
||||
grantId: number
|
||||
}
|
||||
|
||||
export type RotateRefreshTokenArgs = {
|
||||
grantId: number
|
||||
refreshTokenHash: string
|
||||
prevHash: string | null
|
||||
refreshExpiresAt: Date
|
||||
/** Hash the caller presented; null on the first issue, when the grant has none yet. */
|
||||
presentedHash: string | null
|
||||
}
|
||||
|
||||
export type RevokeGrantArgs = {
|
||||
grantId: number
|
||||
/** Omitted for server-side revocation; set when the owner revokes from the UI. */
|
||||
userId?: number
|
||||
}
|
||||
|
||||
export type RevokeOwnGrantArgs = {
|
||||
grantId: number
|
||||
userId: number
|
||||
}
|
||||
|
||||
export type CreateAccessTokenArgs = {
|
||||
userId: number
|
||||
name: string
|
||||
tokenHash: string
|
||||
allowedPermissions: string[]
|
||||
allowedGoalIds: number[]
|
||||
grantId: number
|
||||
expiresAt: Date
|
||||
}
|
||||
|
||||
export type ValidateRedirectUriArgs = {
|
||||
clientId: string
|
||||
redirectUri: string
|
||||
}
|
||||
|
||||
export type AuthenticateClientArgs = {
|
||||
clientId: string
|
||||
clientSecret?: string
|
||||
}
|
||||
|
||||
export type IssueTokenPairArgs = {
|
||||
grant: OAuthGrantsSchemaTypeForSelect
|
||||
clientName: string
|
||||
prevRefreshHash?: string
|
||||
}
|
||||
|
||||
export type VerifyPkceArgs = {
|
||||
codeVerifier: string
|
||||
codeChallenge: string
|
||||
}
|
||||
|
||||
export type MatchRedirectUriArgs = {
|
||||
candidate: string
|
||||
registered: string[]
|
||||
}
|
||||
|
||||
export type BuildRedirectUrlArgs = {
|
||||
redirectUri: string
|
||||
params: Record<string, string | undefined>
|
||||
}
|
||||
|
||||
export type ResourceMatchArgs = {
|
||||
granted: string | null
|
||||
requested: string | null
|
||||
}
|
||||
|
||||
export type SendTokenSuccessArgs = {
|
||||
res: Response
|
||||
body: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type SendTokenErrorArgs = {
|
||||
res: Response
|
||||
status: number
|
||||
error: string
|
||||
description: string
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import { OrganizationController } from './OrganizationController'
|
||||
import { IsOrgAdmin } from './middlewares/IsOrgAdmin'
|
||||
import { IsOrgMember } from './middlewares/IsOrgMember'
|
||||
import { IsOrgOwner } from './middlewares/IsOrgOwner'
|
||||
import { RequireTokenPermission } from '../../middlewares/require-token-permission'
|
||||
import { GoalPermissions } from '../../types/auth.types'
|
||||
|
||||
export default class OrganizationRoutes implements Routable {
|
||||
private readonly router: ReturnType<typeof Router>
|
||||
@@ -21,16 +23,20 @@ export default class OrganizationRoutes implements Routable {
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.post('', [IsLoggedIn], this.controller.create)
|
||||
const canManage = RequireTokenPermission(GoalPermissions.ORG_CAN_MANAGE)
|
||||
const canManageMembers = RequireTokenPermission(GoalPermissions.ORG_CAN_MANAGE_MEMBERS)
|
||||
const canView = RequireTokenPermission(GoalPermissions.ORG_CAN_VIEW)
|
||||
|
||||
this.router.post('', [IsLoggedIn, canManage], this.controller.create)
|
||||
this.router.get('', [IsLoggedIn], this.controller.fetch)
|
||||
|
||||
this.router.post('/members', [IsLoggedIn, IsOrgAdmin], this.controller.addMember)
|
||||
this.router.patch('/members/role', [IsLoggedIn, IsOrgAdmin], this.controller.updateMemberRole)
|
||||
this.router.delete('/members', [IsLoggedIn, IsOrgAdmin], this.controller.removeMember)
|
||||
this.router.post('/members', [IsLoggedIn, IsOrgAdmin, canManageMembers], this.controller.addMember)
|
||||
this.router.patch('/members/role', [IsLoggedIn, IsOrgAdmin, canManageMembers], this.controller.updateMemberRole)
|
||||
this.router.delete('/members', [IsLoggedIn, IsOrgAdmin, canManageMembers], this.controller.removeMember)
|
||||
|
||||
this.router.get('/:orgId', [IsLoggedIn, IsOrgMember], this.controller.getById)
|
||||
this.router.patch('/:orgId', [IsLoggedIn, IsOrgAdmin], this.controller.update)
|
||||
this.router.delete('/:orgId', [IsLoggedIn, IsOrgOwner], this.controller.delete)
|
||||
this.router.get('/:orgId/members', [IsLoggedIn, IsOrgAdmin], this.controller.fetchMembers)
|
||||
this.router.get('/:orgId', [IsLoggedIn, IsOrgMember, canView], this.controller.getById)
|
||||
this.router.patch('/:orgId', [IsLoggedIn, IsOrgAdmin, canManage], this.controller.update)
|
||||
this.router.delete('/:orgId', [IsLoggedIn, IsOrgOwner, canManage], this.controller.delete)
|
||||
this.router.get('/:orgId/members', [IsLoggedIn, IsOrgAdmin, canView], this.controller.fetchMembers)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import axios from 'axios';
|
||||
import fs from 'fs/promises';
|
||||
import type http from 'http';
|
||||
import { join } from 'path';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import App from '../../../App';
|
||||
import { Database } from '../../../modules/db';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
|
||||
const port = 1811;
|
||||
const url = `http://localhost:${port}`;
|
||||
const MIGRATION_DIR = join(__dirname, '../../../migrations/taskview/sql/1.65.0');
|
||||
|
||||
const LOGIN = 'test@mail.dest';
|
||||
const PASSWORD = 'user1!#Q';
|
||||
|
||||
let server: http.Server;
|
||||
let jwt = '';
|
||||
const createdTokenIds: number[] = [];
|
||||
const createdOrgIds: number[] = [];
|
||||
let ownedGoalId = 0;
|
||||
|
||||
const api = axios.create({ baseURL: url, validateStatus: () => true });
|
||||
|
||||
const asUser = () => ({ headers: { Authorization: `Bearer ${jwt}` } });
|
||||
|
||||
async function issueToken(allowedPermissions: string[]) {
|
||||
const response = await api.post(
|
||||
'/module/api-tokens',
|
||||
{ name: 'scope-probe', allowedPermissions, allowedGoalIds: [] },
|
||||
asUser(),
|
||||
);
|
||||
expect(response.status).toBe(200);
|
||||
createdTokenIds.push(response.data.response.item.id);
|
||||
return { headers: { Authorization: `Bearer ${response.data.response.token}` } };
|
||||
}
|
||||
|
||||
async function createOrg(auth: { headers: Record<string, string> }, name: string) {
|
||||
const response = await api.post('/module/organizations', { name }, auth);
|
||||
const id = response.data?.response?.id;
|
||||
if (id) createdOrgIds.push(id);
|
||||
return response;
|
||||
}
|
||||
|
||||
describe('API token scope on organization-level surfaces', () => {
|
||||
vi.mock('emailjs', () => ({
|
||||
SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
|
||||
}));
|
||||
|
||||
beforeAll(async () => {
|
||||
const db = Database.getInstance();
|
||||
const client = await db.getClient();
|
||||
for (const file of (await fs.readdir(MIGRATION_DIR)).sort()) {
|
||||
await client.query(await fs.readFile(join(MIGRATION_DIR, file), 'utf-8'));
|
||||
}
|
||||
client.release();
|
||||
|
||||
server = new App(port).listen();
|
||||
|
||||
const login = await api.post('/module/auth/login', { login: LOGIN, password: PASSWORD });
|
||||
expect(login.status).toBe(200);
|
||||
jwt = login.data.access;
|
||||
|
||||
// A goal the caller actually owns: otherwise IsGoalOwnerByGoalId answers 403
|
||||
// on its own and the webhook tests below would pass without the token check.
|
||||
const goal = await api.post('/module/goals', { name: `scope-goal-${Date.now()}` }, asUser());
|
||||
expect(goal.status).toBe(200);
|
||||
ownedGoalId = goal.data.response.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (ownedGoalId) {
|
||||
await api.delete('/module/goals', { ...asUser(), data: { goalId: ownedGoalId } });
|
||||
}
|
||||
for (const id of createdOrgIds) {
|
||||
await api.delete(`/module/organizations/${id}`, asUser());
|
||||
}
|
||||
for (const id of createdTokenIds) {
|
||||
await api.delete('/module/api-tokens', { ...asUser(), data: { id } });
|
||||
}
|
||||
server?.close();
|
||||
});
|
||||
|
||||
it('seeds the organization permission group', async () => {
|
||||
const db = Database.getInstance();
|
||||
const result = await db.query<{ name: string }>(
|
||||
'SELECT name FROM tv_auth.permissions WHERE permission_group = 6 ORDER BY name',
|
||||
);
|
||||
expect(result?.rows.map((row) => row.name)).toEqual([
|
||||
'org_can_manage', 'org_can_manage_members', 'org_can_view', 'sso_can_manage', 'webhooks_can_manage',
|
||||
]);
|
||||
});
|
||||
|
||||
it('offers the new permissions for selection, with localized descriptions', async () => {
|
||||
const response = await api.get('/module/api-tokens/permissions', asUser());
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const rows = response.data.response as {
|
||||
name: string;
|
||||
permissionGroup: number;
|
||||
descriptionLocales: Record<string, string> | null;
|
||||
}[];
|
||||
|
||||
const orgView = rows.find((row) => row.name === 'org_can_view');
|
||||
expect(orgView?.permissionGroup).toBe(6);
|
||||
expect(orgView?.descriptionLocales?.ru).toBeTruthy();
|
||||
|
||||
// Group 1 is enforced nowhere, so it must not be offered as a restriction.
|
||||
expect(rows.some((row) => row.permissionGroup === 1)).toBe(false);
|
||||
});
|
||||
|
||||
it('blocks a narrowly scoped token from creating an organization', async () => {
|
||||
const token = await issueToken([GoalPermissions.TIMETRACKING_CAN_VIEW]);
|
||||
|
||||
const response = await createOrg(token, 'scope-probe-denied');
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
});
|
||||
|
||||
it('allows a token that was given org_can_manage', async () => {
|
||||
const token = await issueToken([GoalPermissions.ORG_CAN_MANAGE]);
|
||||
|
||||
const response = await createOrg(token, 'scope-probe-allowed');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it('keeps an unrestricted token working, so existing integrations do not break', async () => {
|
||||
const token = await issueToken([]);
|
||||
|
||||
const response = await createOrg(token, 'scope-probe-unrestricted');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it('does not restrict a browser session', async () => {
|
||||
const response = await createOrg(asUser(), 'scope-probe-session');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it('separates managing the organization from managing its members', async () => {
|
||||
const token = await issueToken([GoalPermissions.ORG_CAN_MANAGE]);
|
||||
const org = await createOrg(token, 'scope-probe-members');
|
||||
expect(org.status).toBe(200);
|
||||
|
||||
const response = await api.post(
|
||||
'/module/organizations/members',
|
||||
{ organizationId: org.data.response.id, email: LOGIN, role: 'admin' },
|
||||
token,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
});
|
||||
|
||||
it('lets a token holding org_can_manage_members add one', async () => {
|
||||
const owner = await issueToken([GoalPermissions.ORG_CAN_MANAGE]);
|
||||
const org = await createOrg(owner, 'scope-probe-members-ok');
|
||||
expect(org.status).toBe(200);
|
||||
|
||||
const member = await issueToken([GoalPermissions.ORG_CAN_MANAGE_MEMBERS]);
|
||||
const response = await api.post(
|
||||
'/module/organizations/members',
|
||||
{ organizationId: org.data.response.id, email: `member-${Date.now()}@test.dest`, role: 'member' },
|
||||
member,
|
||||
);
|
||||
|
||||
// A precise status, not merely "not 403" — that would also pass on a 500.
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it('blocks a narrowly scoped token from reaching webhooks of a goal it owns', async () => {
|
||||
const token = await issueToken([GoalPermissions.TIMETRACKING_CAN_VIEW]);
|
||||
|
||||
const response = await api.get(`/module/webhooks?goalId=${ownedGoalId}`, token);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
});
|
||||
|
||||
it('lets webhooks_can_manage through on that same goal, proving the 403 came from the token', async () => {
|
||||
const token = await issueToken([GoalPermissions.WEBHOOKS_CAN_MANAGE]);
|
||||
|
||||
const response = await api.get(`/module/webhooks?goalId=${ownedGoalId}`, token);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -5,15 +5,24 @@ import type { Request, Response } from 'express'
|
||||
import { $logger } from '../../modules/logget'
|
||||
import { PublicApiUrl } from '../../modules/public-url'
|
||||
import { logError } from '../../utils/api'
|
||||
import { generateString, isEmail } from '../../utils/helpers'
|
||||
import { generateLetters, generateString } from '../../utils/helpers'
|
||||
import AuthModel from '../auth/AuthModel'
|
||||
import { GoalsRepository } from '../goals/GoalsRepository'
|
||||
import { OrganizationRepository } from '../organizations/OrganizationRepository'
|
||||
import { createSsoProvider } from './providers/provider-factory'
|
||||
import { SsoRepository } from './SsoRepository'
|
||||
import { parseSamlMetadata } from './saml-metadata-parser'
|
||||
import { generateLoginCode, stripSecrets, validateMetadataUrl } from './sso.utils'
|
||||
import { SsoConfigArkTypeCreate, SsoConfigArkTypeUpdate } from './types'
|
||||
import { generateLoginCode, isSsoDomainVerified, stripSecrets, validateMetadataUrl } from './sso.utils'
|
||||
import {
|
||||
SsoConfigArkTypeCreate,
|
||||
SsoConfigArkTypeUpdate,
|
||||
SsoDomainNotVerifiedError,
|
||||
type ApplySsoIdpEmailArgs,
|
||||
type ResolveSsoUserArgs,
|
||||
type ResolveSsoUserResult,
|
||||
type SsoCallbackError,
|
||||
} from './types'
|
||||
import type { UserDbRecord } from '../../types/auth.types'
|
||||
|
||||
export class SsoController {
|
||||
private readonly ssoRepo = new SsoRepository()
|
||||
@@ -21,6 +30,103 @@ export class SsoController {
|
||||
private readonly orgRepo = new OrganizationRepository()
|
||||
private readonly goalsRepo = new GoalsRepository()
|
||||
|
||||
private async resolveLogin(preferredUsername?: string): Promise<string> {
|
||||
const base = preferredUsername?.trim().slice(0, 50)
|
||||
if (!base) return generateString(7)
|
||||
|
||||
if (!(await this.authModel.getUserByLogin(base))) return base
|
||||
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
const suffix = `.${generateLetters(3)}`
|
||||
const candidate = `${base.slice(0, 50 - suffix.length)}${suffix}`
|
||||
if (!(await this.authModel.getUserByLogin(candidate))) return candidate
|
||||
}
|
||||
|
||||
return generateString(7)
|
||||
}
|
||||
|
||||
private redirectSsoError(res: Response, error: SsoCallbackError) {
|
||||
return res.redirect(`${process.env.APP_URL}/login?sso_error=${error}`)
|
||||
}
|
||||
|
||||
private async createSsoUser(args: ResolveSsoUserArgs): Promise<UserDbRecord | false> {
|
||||
const password = generateString(16)
|
||||
const login = await this.resolveLogin(args.preferredUsername)
|
||||
const id = await this.authModel.registerUserInDb({
|
||||
login,
|
||||
email: args.email,
|
||||
password: hashSync(password, 10),
|
||||
block: 0,
|
||||
confirmEmailCode: '',
|
||||
})
|
||||
|
||||
if (!id) {
|
||||
$logger.error('Failed to create user during SSO login')
|
||||
return false
|
||||
}
|
||||
|
||||
const personalOrgSlug = `org-${crypto.randomUUID().slice(0, 8)}`
|
||||
const personalOrg = await this.orgRepo.create({ name: `${login}'s workspace`, slug: personalOrgSlug }, id, true)
|
||||
if (personalOrg) {
|
||||
await this.orgRepo.addMember(personalOrg.id, args.email, 'owner')
|
||||
await this.goalsRepo.createInboxGoal({ ownerId: id, organizationId: personalOrg.id })
|
||||
}
|
||||
|
||||
return await this.authModel.fetchUserById(id)
|
||||
}
|
||||
|
||||
private async applyIdpEmail(args: ApplySsoIdpEmailArgs): Promise<'ok' | 'email_in_use' | 'error'> {
|
||||
if (args.user.email.toLowerCase() === args.email) return 'ok'
|
||||
|
||||
const taken = await this.authModel.getUserByLogin(args.email, true)
|
||||
if (taken && taken.id !== args.user.id) return 'email_in_use'
|
||||
|
||||
const result = await this.authModel.updateUserEmail({
|
||||
userId: args.user.id,
|
||||
oldEmail: args.user.email,
|
||||
email: args.email,
|
||||
})
|
||||
if (result === 'conflict') return 'email_in_use'
|
||||
if (result !== 'ok') return 'error'
|
||||
return 'ok'
|
||||
}
|
||||
|
||||
private async resolveSsoUser(args: ResolveSsoUserArgs): Promise<ResolveSsoUserResult> {
|
||||
const identity = await this.ssoRepo.findIdentity({
|
||||
ssoConfigId: args.ssoConfigId,
|
||||
externalId: args.externalId,
|
||||
})
|
||||
|
||||
if (identity) {
|
||||
const user = await this.authModel.fetchUserById(identity.userId)
|
||||
if (!user) return { ok: false, error: 'authentication_failed' }
|
||||
|
||||
const emailResult = await this.applyIdpEmail({ user, email: args.email })
|
||||
if (emailResult === 'email_in_use') return { ok: false, error: 'email_in_use' }
|
||||
if (emailResult !== 'ok') return { ok: false, error: 'authentication_failed' }
|
||||
|
||||
const refreshed = await this.authModel.fetchUserById(user.id)
|
||||
if (!refreshed) return { ok: false, error: 'authentication_failed' }
|
||||
return { ok: true, user: refreshed }
|
||||
}
|
||||
|
||||
const existing = await this.authModel.getUserByLogin(args.email, true)
|
||||
if (existing) {
|
||||
const linked = await this.ssoRepo.findIdentityByUser({
|
||||
ssoConfigId: args.ssoConfigId,
|
||||
userId: existing.id,
|
||||
})
|
||||
if (linked && linked.externalId !== args.externalId) {
|
||||
return { ok: false, error: 'email_in_use' }
|
||||
}
|
||||
return { ok: true, user: existing }
|
||||
}
|
||||
|
||||
const created = await this.createSsoUser(args)
|
||||
if (!created) return { ok: false, error: 'authentication_failed' }
|
||||
return { ok: true, user: created }
|
||||
}
|
||||
|
||||
initiateLogin = async (req: Request, res: Response) => {
|
||||
const configId = Number(req.params.configId)
|
||||
if (!configId) return res.status(400).tvJson({ message: 'Invalid config ID' })
|
||||
@@ -28,6 +134,10 @@ export class SsoController {
|
||||
const config = await this.ssoRepo.findEnabledById(configId)
|
||||
if (!config) return res.status(404).tvJson({ message: 'SSO provider not found' })
|
||||
|
||||
if (!isSsoDomainVerified(config)) {
|
||||
return res.redirect(`${process.env.APP_URL}/login?sso_error=domain_unverified`)
|
||||
}
|
||||
|
||||
try {
|
||||
const provider = createSsoProvider(config)
|
||||
const relayState = JSON.stringify({ platform: req.query.platform || '' })
|
||||
@@ -45,50 +155,40 @@ export class SsoController {
|
||||
const config = await this.ssoRepo.findEnabledById(configId)
|
||||
if (!config) return res.status(404).tvJson({ message: 'SSO provider not found' })
|
||||
|
||||
if (!isSsoDomainVerified(config)) {
|
||||
return res.redirect(`${process.env.APP_URL}/login?sso_error=domain_unverified`)
|
||||
}
|
||||
|
||||
try {
|
||||
const provider = createSsoProvider(config)
|
||||
const ssoResult = await provider.handleCallback(req)
|
||||
|
||||
if (config.emailDomainRestriction) {
|
||||
const domain = ssoResult.email.split('@')[1]
|
||||
if (domain !== config.emailDomainRestriction) {
|
||||
return res.status(403).tvJson({ message: 'Email domain not allowed for this SSO provider' })
|
||||
}
|
||||
if (!config.emailDomainRestriction) {
|
||||
return this.redirectSsoError(res, 'authentication_failed')
|
||||
}
|
||||
|
||||
let userData = await this.authModel.getUserByLogin(ssoResult.email, isEmail(ssoResult.email))
|
||||
|
||||
if (!userData) {
|
||||
const password = generateString(16)
|
||||
const login = generateString(7)
|
||||
const id = await this.authModel.registerUserInDb({
|
||||
login,
|
||||
email: ssoResult.email,
|
||||
password: hashSync(password, 10),
|
||||
block: 0,
|
||||
confirmEmailCode: '',
|
||||
})
|
||||
|
||||
if (!id) {
|
||||
$logger.error('Failed to create user during SSO login')
|
||||
return res.status(500).tvJson({ message: 'Failed to create user' })
|
||||
}
|
||||
|
||||
const personalOrgSlug = `org-${crypto.randomUUID().slice(0, 8)}`
|
||||
const personalOrg = await this.orgRepo.create({ name: `${login}'s workspace`, slug: personalOrgSlug }, id, true)
|
||||
if (personalOrg) {
|
||||
await this.orgRepo.addMember(personalOrg.id, ssoResult.email, 'owner')
|
||||
await this.goalsRepo.createInboxGoal({ ownerId: id, organizationId: personalOrg.id })
|
||||
}
|
||||
|
||||
userData = await this.authModel.getUserByLogin(ssoResult.email, isEmail(ssoResult.email))
|
||||
const domain = ssoResult.email.split('@')[1]
|
||||
if (domain !== config.emailDomainRestriction) {
|
||||
return res.status(403).tvJson({ message: 'Email domain not allowed for this SSO provider' })
|
||||
}
|
||||
|
||||
if (!userData) {
|
||||
return res.status(500).tvJson({ message: 'Failed to resolve user after SSO login' })
|
||||
const resolved = await this.resolveSsoUser({
|
||||
ssoConfigId: config.id,
|
||||
email: ssoResult.email,
|
||||
externalId: ssoResult.externalId,
|
||||
preferredUsername: ssoResult.preferredUsername,
|
||||
})
|
||||
if (!resolved.ok) {
|
||||
return this.redirectSsoError(res, resolved.error)
|
||||
}
|
||||
|
||||
await this.orgRepo.addMember(config.organizationId, ssoResult.email, config.defaultOrgRole)
|
||||
const userData = resolved.user
|
||||
|
||||
if (userData.block && !userData.confirm_email_code) {
|
||||
return this.redirectSsoError(res, 'account_blocked')
|
||||
}
|
||||
|
||||
await this.orgRepo.addMember(config.organizationId, userData.email, config.defaultOrgRole)
|
||||
|
||||
await this.ssoRepo.upsertIdentity({
|
||||
userId: userData.id,
|
||||
@@ -132,7 +232,7 @@ export class SsoController {
|
||||
if (!domain) return res.tvJson(null)
|
||||
|
||||
const config = await this.ssoRepo.findEnabledByDomain(domain)
|
||||
if (!config) return res.tvJson(null)
|
||||
if (!config || !isSsoDomainVerified(config)) return res.tvJson(null)
|
||||
|
||||
return res.tvJson({
|
||||
id: config.id,
|
||||
@@ -165,11 +265,18 @@ export class SsoController {
|
||||
return res.status(400).send(out.summary)
|
||||
}
|
||||
|
||||
const existing = await this.ssoRepo.findEnabledByDomain(out.emailDomainRestriction)
|
||||
if (existing) {
|
||||
const domain = out.emailDomainRestriction.toLowerCase()
|
||||
|
||||
const sameOrg = await this.ssoRepo.findByDomainAndOrg({ domain, organizationId: out.organizationId })
|
||||
if (sameOrg) {
|
||||
return res.status(409).tvJson({ message: 'SSO config for this domain already exists' })
|
||||
}
|
||||
|
||||
const verified = await this.ssoRepo.findVerifiedByDomain(domain)
|
||||
if (verified) {
|
||||
return res.status(409).tvJson({ message: 'This domain is already verified by another organization' })
|
||||
}
|
||||
|
||||
const config = await req.appUser.ssoManager.createConfig(out).catch(logError)
|
||||
if (!config) {
|
||||
return res.status(500).tvJson({ message: 'Failed to create SSO config' })
|
||||
@@ -186,8 +293,33 @@ export class SsoController {
|
||||
return res.status(400).send(out.summary)
|
||||
}
|
||||
|
||||
const config = await req.appUser.ssoManager.updateConfig(configId, out).catch(logError)
|
||||
return res.tvJson(config ? stripSecrets(config) : null)
|
||||
if (out.emailDomainRestriction) {
|
||||
const domain = out.emailDomainRestriction.toLowerCase()
|
||||
|
||||
const verified = await this.ssoRepo.findVerifiedByDomain(domain)
|
||||
if (verified && verified.id !== configId) {
|
||||
return res.status(409).tvJson({ message: 'This domain is already verified by another organization' })
|
||||
}
|
||||
|
||||
const current = await this.ssoRepo.findById(configId)
|
||||
if (current) {
|
||||
const sameOrg = await this.ssoRepo.findByDomainAndOrg({ domain, organizationId: current.organizationId })
|
||||
if (sameOrg && sameOrg.id !== configId) {
|
||||
return res.status(409).tvJson({ message: 'SSO config for this domain already exists' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await req.appUser.ssoManager.updateConfig(configId, out)
|
||||
return res.tvJson(config ? stripSecrets(config) : null)
|
||||
} catch (error) {
|
||||
if (error instanceof SsoDomainNotVerifiedError) {
|
||||
return res.status(403).tvJson({ message: 'Domain is not verified' })
|
||||
}
|
||||
logError(error)
|
||||
return res.tvJson(null)
|
||||
}
|
||||
}
|
||||
|
||||
parseMetadata = async (req: Request, res: Response) => {
|
||||
@@ -213,6 +345,28 @@ export class SsoController {
|
||||
}
|
||||
}
|
||||
|
||||
startDomainVerification = async (req: Request, res: Response) => {
|
||||
const configId = Number(req.params.configId)
|
||||
if (!configId) return res.status(400).end()
|
||||
|
||||
const result = await req.appUser.ssoManager.startDomainVerification(configId).catch(logError)
|
||||
if (!result) {
|
||||
return res.status(404).tvJson({ message: 'SSO config not found' })
|
||||
}
|
||||
return res.tvJson(result)
|
||||
}
|
||||
|
||||
checkDomainVerification = async (req: Request, res: Response) => {
|
||||
const configId = Number(req.params.configId)
|
||||
if (!configId) return res.status(400).end()
|
||||
|
||||
const result = await req.appUser.ssoManager.checkDomainVerification(configId).catch(logError)
|
||||
if (!result) {
|
||||
return res.status(404).tvJson({ message: 'SSO config not found' })
|
||||
}
|
||||
return res.tvJson(result)
|
||||
}
|
||||
|
||||
generateScimToken = async (req: Request, res: Response) => {
|
||||
const configId = Number(req.params.configId)
|
||||
if (!configId) return res.status(400).end()
|
||||
|
||||
@@ -1,8 +1,22 @@
|
||||
import type { AppUser } from '../../core/AppUser'
|
||||
import { encrypt, encryptField } from '../../utils/crypto'
|
||||
import { SsoRepository } from './SsoRepository'
|
||||
import { SSO_SECRET_FIELDS } from './sso.utils'
|
||||
import type { SsoConfigArgCreate, SsoConfigArgUpdate } from './types'
|
||||
import {
|
||||
SSO_SECRET_FIELDS,
|
||||
generateDomainVerifyToken,
|
||||
isSsoDomainVerified,
|
||||
isTrustedSsoDomain,
|
||||
proveSsoDomainOwnership,
|
||||
ssoDomainVerifyDnsRecord,
|
||||
ssoDomainVerifyHttpUrl,
|
||||
} from './sso.utils'
|
||||
import {
|
||||
SsoDomainNotVerifiedError,
|
||||
type CheckDomainVerificationResult,
|
||||
type SsoConfigArgCreate,
|
||||
type SsoConfigArgUpdate,
|
||||
type StartDomainVerificationResult,
|
||||
} from './types'
|
||||
|
||||
export class SsoManager {
|
||||
public readonly repository: SsoRepository
|
||||
@@ -18,11 +32,14 @@ export class SsoManager {
|
||||
}
|
||||
|
||||
async createConfig(data: SsoConfigArgCreate) {
|
||||
const domain = data.emailDomainRestriction.toLowerCase()
|
||||
const trusted = isTrustedSsoDomain(domain)
|
||||
|
||||
return await this.repository.create({
|
||||
organizationId: data.organizationId,
|
||||
protocol: data.protocol,
|
||||
displayName: data.displayName,
|
||||
enabled: data.enabled ?? 1,
|
||||
enabled: trusted ? (data.enabled ?? 1) : 0,
|
||||
samlEntryPoint: data.samlEntryPoint ?? null,
|
||||
samlIssuer: data.samlIssuer ?? null,
|
||||
samlCert: encryptField(data.samlCert),
|
||||
@@ -36,12 +53,22 @@ export class SsoManager {
|
||||
oidcCallbackUrl: data.oidcCallbackUrl ?? null,
|
||||
oidcScope: data.oidcScope ?? null,
|
||||
defaultOrgRole: data.defaultOrgRole ?? 'member',
|
||||
emailDomainRestriction: data.emailDomainRestriction.toLowerCase(),
|
||||
emailDomainRestriction: domain,
|
||||
domainVerifyToken: generateDomainVerifyToken(),
|
||||
domainVerifiedAt: trusted ? new Date() : null,
|
||||
})
|
||||
}
|
||||
|
||||
async updateConfig(configId: number, data: SsoConfigArgUpdate) {
|
||||
const encrypted: Partial<SsoConfigArgUpdate> = { ...data }
|
||||
const current = await this.repository.findById(configId)
|
||||
if (!current) return null
|
||||
|
||||
const encrypted: Partial<SsoConfigArgUpdate> & {
|
||||
domainVerifyToken?: string
|
||||
domainVerifiedAt?: Date | null
|
||||
enabled?: number
|
||||
} = { ...data }
|
||||
|
||||
for (const field of SSO_SECRET_FIELDS) {
|
||||
if (field in encrypted) {
|
||||
if (encrypted[field]) {
|
||||
@@ -51,9 +78,87 @@ export class SsoManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (data.emailDomainRestriction) {
|
||||
const domain = data.emailDomainRestriction.toLowerCase()
|
||||
encrypted.emailDomainRestriction = domain
|
||||
if (domain !== current.emailDomainRestriction) {
|
||||
const trusted = isTrustedSsoDomain(domain)
|
||||
encrypted.domainVerifyToken = generateDomainVerifyToken()
|
||||
encrypted.domainVerifiedAt = trusted ? new Date() : null
|
||||
if (!trusted) encrypted.enabled = 0
|
||||
await this.repository.deleteIdentitiesByConfig(configId)
|
||||
}
|
||||
}
|
||||
|
||||
const nextDomain = encrypted.emailDomainRestriction ?? current.emailDomainRestriction
|
||||
const nextVerifiedAt = 'domainVerifiedAt' in encrypted
|
||||
? encrypted.domainVerifiedAt
|
||||
: current.domainVerifiedAt
|
||||
const wouldBeVerified = isTrustedSsoDomain(nextDomain) || !!nextVerifiedAt
|
||||
|
||||
if (data.enabled === 1 && !wouldBeVerified) {
|
||||
throw new SsoDomainNotVerifiedError()
|
||||
}
|
||||
|
||||
return await this.repository.update(configId, encrypted)
|
||||
}
|
||||
|
||||
async startDomainVerification(configId: number): Promise<StartDomainVerificationResult | null> {
|
||||
const config = await this.repository.findById(configId)
|
||||
if (!config) return null
|
||||
|
||||
let token = config.domainVerifyToken
|
||||
if (!token) {
|
||||
token = generateDomainVerifyToken()
|
||||
const updated = await this.repository.update(configId, { domainVerifyToken: token })
|
||||
if (!updated) return null
|
||||
}
|
||||
|
||||
return {
|
||||
token,
|
||||
dnsRecord: ssoDomainVerifyDnsRecord(token),
|
||||
httpUrl: ssoDomainVerifyHttpUrl(config.emailDomainRestriction),
|
||||
isDomainVerified: isSsoDomainVerified({ ...config, domainVerifyToken: token }),
|
||||
isDomainTrusted: isTrustedSsoDomain(config.emailDomainRestriction),
|
||||
}
|
||||
}
|
||||
|
||||
async checkDomainVerification(configId: number): Promise<CheckDomainVerificationResult | null> {
|
||||
const config = await this.repository.findById(configId)
|
||||
if (!config) return null
|
||||
|
||||
if (!config.domainVerifyToken) {
|
||||
return {
|
||||
verified: isSsoDomainVerified(config),
|
||||
method: isTrustedSsoDomain(config.emailDomainRestriction) ? 'trusted' : null
|
||||
}
|
||||
}
|
||||
|
||||
const method = await proveSsoDomainOwnership({
|
||||
domain: config.emailDomainRestriction,
|
||||
token: config.domainVerifyToken,
|
||||
})
|
||||
|
||||
if (!method) {
|
||||
return { verified: isSsoDomainVerified(config), method: null }
|
||||
}
|
||||
|
||||
if (!config.domainVerifiedAt || method === 'trusted') {
|
||||
const updated = await this.repository.update(configId, {
|
||||
domainVerifiedAt: new Date(),
|
||||
enabled: 1,
|
||||
})
|
||||
// The partial unique index rejects a second verified config for the same
|
||||
// domain another organization proved ownership first.
|
||||
if (!updated) {
|
||||
return { verified: false, method: null }
|
||||
}
|
||||
}
|
||||
|
||||
return { verified: true, method }
|
||||
}
|
||||
|
||||
async deleteConfig(configId: number) {
|
||||
return await this.repository.delete(configId)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, eq } from 'drizzle-orm'
|
||||
import { and, eq, isNotNull } from 'drizzle-orm'
|
||||
import {
|
||||
SsoConfigsSchema,
|
||||
SsoIdentitiesSchema,
|
||||
@@ -8,6 +8,12 @@ import {
|
||||
} from 'taskview-db-schemas'
|
||||
import { Database } from '../../modules/db'
|
||||
import { callWithCatch } from '../../utils/helpers'
|
||||
import type {
|
||||
FindSsoConfigByDomainAndOrgArgs,
|
||||
FindSsoIdentityArgs,
|
||||
FindSsoIdentityByUserArgs,
|
||||
UpsertSsoIdentityArgs,
|
||||
} from './types'
|
||||
|
||||
export class SsoRepository {
|
||||
private readonly db: Database
|
||||
@@ -16,6 +22,38 @@ export class SsoRepository {
|
||||
this.db = Database.getInstance()
|
||||
}
|
||||
|
||||
async findVerifiedByDomain(domain: string): Promise<SsoConfigsSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select()
|
||||
.from(SsoConfigsSchema)
|
||||
.where(
|
||||
and(
|
||||
eq(SsoConfigsSchema.emailDomainRestriction, domain.toLowerCase()),
|
||||
isNotNull(SsoConfigsSchema.domainVerifiedAt),
|
||||
)
|
||||
)
|
||||
)
|
||||
if (!result || result.length === 0) return null
|
||||
return result[0]
|
||||
}
|
||||
|
||||
async findByDomainAndOrg(args: FindSsoConfigByDomainAndOrgArgs): Promise<SsoConfigsSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select()
|
||||
.from(SsoConfigsSchema)
|
||||
.where(
|
||||
and(
|
||||
eq(SsoConfigsSchema.emailDomainRestriction, args.domain.toLowerCase()),
|
||||
eq(SsoConfigsSchema.organizationId, args.organizationId),
|
||||
)
|
||||
)
|
||||
)
|
||||
if (!result || result.length === 0) return null
|
||||
return result[0]
|
||||
}
|
||||
|
||||
async findEnabledByDomain(domain: string): Promise<SsoConfigsSchemaTypeForSelect | null> {
|
||||
const result = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
@@ -146,12 +184,41 @@ export class SsoRepository {
|
||||
return !!(result?.rowCount && result.rowCount > 0)
|
||||
}
|
||||
|
||||
async upsertIdentity(data: {
|
||||
userId: number
|
||||
ssoConfigId: number
|
||||
externalId: string
|
||||
email: string
|
||||
}): Promise<SsoIdentitiesSchemaTypeForSelect | null> {
|
||||
async findIdentity(args: FindSsoIdentityArgs): Promise<SsoIdentitiesSchemaTypeForSelect | null> {
|
||||
const result = await this.db.dbDrizzle
|
||||
.select()
|
||||
.from(SsoIdentitiesSchema)
|
||||
.where(
|
||||
and(
|
||||
eq(SsoIdentitiesSchema.ssoConfigId, args.ssoConfigId),
|
||||
eq(SsoIdentitiesSchema.externalId, args.externalId),
|
||||
)
|
||||
)
|
||||
if (result.length === 0) return null
|
||||
return result[0]
|
||||
}
|
||||
|
||||
async findIdentityByUser(args: FindSsoIdentityByUserArgs): Promise<SsoIdentitiesSchemaTypeForSelect | null> {
|
||||
const result = await this.db.dbDrizzle
|
||||
.select()
|
||||
.from(SsoIdentitiesSchema)
|
||||
.where(
|
||||
and(
|
||||
eq(SsoIdentitiesSchema.ssoConfigId, args.ssoConfigId),
|
||||
eq(SsoIdentitiesSchema.userId, args.userId),
|
||||
)
|
||||
)
|
||||
if (result.length === 0) return null
|
||||
return result[0]
|
||||
}
|
||||
|
||||
async deleteIdentitiesByConfig(ssoConfigId: number): Promise<void> {
|
||||
await this.db.dbDrizzle
|
||||
.delete(SsoIdentitiesSchema)
|
||||
.where(eq(SsoIdentitiesSchema.ssoConfigId, ssoConfigId))
|
||||
}
|
||||
|
||||
async upsertIdentity(data: UpsertSsoIdentityArgs): Promise<SsoIdentitiesSchemaTypeForSelect | null> {
|
||||
const existing = await callWithCatch(() =>
|
||||
this.db.dbDrizzle
|
||||
.select()
|
||||
|
||||
@@ -5,6 +5,8 @@ import { IsOrgAdmin } from '../organizations/middlewares/IsOrgAdmin'
|
||||
import { IsSsoConfigAdmin } from './middlewares/IsSsoConfigAdmin'
|
||||
import { RequireLoginMethod } from '../auth/middlewares/require-login-method'
|
||||
import { SsoController } from './SsoController'
|
||||
import { RequireTokenPermission } from '../../middlewares/require-token-permission'
|
||||
import { GoalPermissions } from '../../types/auth.types'
|
||||
|
||||
export default class SsoRoutes implements Routable {
|
||||
private readonly router: ReturnType<typeof Router>
|
||||
@@ -26,13 +28,17 @@ export default class SsoRoutes implements Routable {
|
||||
this.router.get('/callback/:configId', [RequireLoginMethod('sso')], this.controller.handleCallback)
|
||||
this.router.post('/callback/:configId', [RequireLoginMethod('sso')], this.controller.handleCallback)
|
||||
|
||||
const canManageSso = RequireTokenPermission(GoalPermissions.SSO_CAN_MANAGE)
|
||||
|
||||
this.router.get('/admin/public-urls', [IsLoggedIn], this.controller.getPublicUrls)
|
||||
this.router.get('/admin/metadata', [IsLoggedIn, IsOrgAdmin], this.controller.parseMetadata)
|
||||
this.router.get('/admin/configs', [IsLoggedIn, IsOrgAdmin], this.controller.listConfigs)
|
||||
this.router.post('/admin/configs', [IsLoggedIn, IsOrgAdmin], this.controller.createConfig)
|
||||
this.router.patch('/admin/configs/:configId', [IsLoggedIn, IsSsoConfigAdmin], this.controller.updateConfig)
|
||||
this.router.delete('/admin/configs/:configId', [IsLoggedIn, IsSsoConfigAdmin], this.controller.deleteConfig)
|
||||
this.router.post('/admin/configs/:configId/scim-token', [IsLoggedIn, IsSsoConfigAdmin], this.controller.generateScimToken)
|
||||
this.router.patch('/admin/configs/:configId/scim', [IsLoggedIn, IsSsoConfigAdmin], this.controller.toggleScim)
|
||||
this.router.get('/admin/metadata', [IsLoggedIn, IsOrgAdmin, canManageSso], this.controller.parseMetadata)
|
||||
this.router.get('/admin/configs', [IsLoggedIn, IsOrgAdmin, canManageSso], this.controller.listConfigs)
|
||||
this.router.post('/admin/configs', [IsLoggedIn, IsOrgAdmin, canManageSso], this.controller.createConfig)
|
||||
this.router.patch('/admin/configs/:configId', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.updateConfig)
|
||||
this.router.delete('/admin/configs/:configId', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.deleteConfig)
|
||||
this.router.post('/admin/configs/:configId/verify-domain', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.startDomainVerification)
|
||||
this.router.post('/admin/configs/:configId/verify-domain/check', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.checkDomainVerification)
|
||||
this.router.post('/admin/configs/:configId/scim-token', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.generateScimToken)
|
||||
this.router.patch('/admin/configs/:configId/scim', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.toggleScim)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { deriveSamlEmail } from '../sso.utils'
|
||||
|
||||
const EMAIL_NAMEID_FORMAT = 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'
|
||||
const PERSISTENT_NAMEID_FORMAT = 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent'
|
||||
const EMAIL_CLAIM = 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'
|
||||
|
||||
describe('deriveSamlEmail', () => {
|
||||
it('takes the email attribute and lowercases it', () => {
|
||||
expect(deriveSamlEmail({ email: 'User@Company.com', nameID: 'abc' })).toBe('user@company.com')
|
||||
})
|
||||
|
||||
it('falls back to the xmlsoap emailaddress claim', () => {
|
||||
expect(deriveSamlEmail({ [EMAIL_CLAIM]: 'a@b.com', nameID: 'abc' })).toBe('a@b.com')
|
||||
})
|
||||
|
||||
it('uses nameID only when the NameID Format is emailAddress', () => {
|
||||
expect(deriveSamlEmail({
|
||||
nameID: 'user@company.com',
|
||||
nameIDFormat: EMAIL_NAMEID_FORMAT,
|
||||
})).toBe('user@company.com')
|
||||
})
|
||||
|
||||
it('does not use nameID for a non-email NameID Format', () => {
|
||||
expect(deriveSamlEmail({
|
||||
nameID: 'user@company.com',
|
||||
nameIDFormat: PERSISTENT_NAMEID_FORMAT,
|
||||
})).toBeNull()
|
||||
})
|
||||
|
||||
it('does not use nameID when no format is provided', () => {
|
||||
expect(deriveSamlEmail({ nameID: 'user@company.com' })).toBeNull()
|
||||
})
|
||||
|
||||
it('prefers the email attribute over an emailAddress-format nameID', () => {
|
||||
expect(deriveSamlEmail({
|
||||
email: 'attr@company.com',
|
||||
nameID: 'name@company.com',
|
||||
nameIDFormat: EMAIL_NAMEID_FORMAT,
|
||||
})).toBe('attr@company.com')
|
||||
})
|
||||
|
||||
it('returns null for a blank or non-string email attribute', () => {
|
||||
expect(deriveSamlEmail({ email: ' ', nameID: 'abc' })).toBeNull()
|
||||
expect(deriveSamlEmail({ email: 123, nameID: 'abc' })).toBeNull()
|
||||
expect(deriveSamlEmail({ nameID: 'abc' })).toBeNull()
|
||||
expect(deriveSamlEmail({})).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import { randomBytes } from 'crypto'
|
||||
import * as client from 'openid-client'
|
||||
import type { Request, Response } from 'express'
|
||||
import type { SsoConfigsSchemaTypeForSelect } from 'taskview-db-schemas'
|
||||
import { PublicApiUrl } from '../../../modules/public-url'
|
||||
import type { SsoProvider, SsoAuthResult } from './sso-provider.interface'
|
||||
|
||||
export class OidcProvider implements SsoProvider {
|
||||
@@ -28,7 +29,12 @@ export class OidcProvider implements SsoProvider {
|
||||
return this.oidcConfig
|
||||
}
|
||||
|
||||
async initiateLogin(_req: Request, res: Response, relayState?: string): Promise<void> {
|
||||
private resolveCallbackUrl(req: Request): string {
|
||||
return this.config.oidcCallbackUrl?.trim()
|
||||
|| `${PublicApiUrl.base(req)}/module/sso/callback/${this.config.id}`
|
||||
}
|
||||
|
||||
async initiateLogin(req: Request, res: Response, relayState?: string): Promise<void> {
|
||||
const config = await this.getOidcConfig()
|
||||
const scope = this.config.oidcScope ?? 'openid email profile'
|
||||
const codeVerifier = client.randomPKCECodeVerifier()
|
||||
@@ -63,7 +69,7 @@ export class OidcProvider implements SsoProvider {
|
||||
})
|
||||
|
||||
const params = new URLSearchParams({
|
||||
redirect_uri: this.config.oidcCallbackUrl!,
|
||||
redirect_uri: this.resolveCallbackUrl(req),
|
||||
scope,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
@@ -110,7 +116,7 @@ export class OidcProvider implements SsoProvider {
|
||||
throw new Error('CSRF state mismatch — possible CSRF attack')
|
||||
}
|
||||
|
||||
const callbackOrigin = new URL(this.config.oidcCallbackUrl!).origin
|
||||
const callbackOrigin = new URL(this.resolveCallbackUrl(req)).origin
|
||||
const currentUrl = new URL(req.originalUrl, callbackOrigin)
|
||||
const tokens = await client.authorizationCodeGrant(config, currentUrl, {
|
||||
pkceCodeVerifier: codeVerifier,
|
||||
@@ -128,6 +134,7 @@ export class OidcProvider implements SsoProvider {
|
||||
email: (claims.email as string).toLowerCase(),
|
||||
externalId: claims.sub,
|
||||
displayName: claims.name as string | undefined,
|
||||
preferredUsername: claims.preferred_username as string | undefined,
|
||||
provider: `oidc-${this.config.id}`,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { SAML, ValidateInResponseTo } from '@node-saml/node-saml'
|
||||
import type { Request, Response } from 'express'
|
||||
import type { SsoConfigsSchemaTypeForSelect } from 'taskview-db-schemas'
|
||||
import { PublicApiUrl } from '../../../modules/public-url'
|
||||
import { deriveSamlEmail } from '../sso.utils'
|
||||
import type { SamlOptionsArgs } from '../types'
|
||||
import type { SsoProvider, SsoAuthResult } from './sso-provider.interface'
|
||||
import { SamlDbCacheProvider } from './saml-cache-provider'
|
||||
|
||||
@@ -11,12 +14,12 @@ function normalizeCert(cert: string): string {
|
||||
.replace(/[\s\r\n]/g, '')
|
||||
}
|
||||
|
||||
function buildSamlOptions(config: SsoConfigsSchemaTypeForSelect, mode: 'assertion' | 'response') {
|
||||
function buildSamlOptions({ config, mode, callbackUrl }: SamlOptionsArgs) {
|
||||
return {
|
||||
entryPoint: config.samlEntryPoint!,
|
||||
issuer: config.samlIssuer!,
|
||||
idpCert: normalizeCert(config.samlCert!),
|
||||
callbackUrl: config.samlCallbackUrl!,
|
||||
callbackUrl,
|
||||
wantAssertionsSigned: mode === 'assertion',
|
||||
wantAuthnResponseSigned: mode === 'response',
|
||||
validateInResponseTo: ValidateInResponseTo.always,
|
||||
@@ -31,29 +34,38 @@ function buildSamlOptions(config: SsoConfigsSchemaTypeForSelect, mode: 'assertio
|
||||
}
|
||||
|
||||
export class SamlProvider implements SsoProvider {
|
||||
private readonly samlAssertion: SAML
|
||||
private readonly samlResponse: SAML
|
||||
private readonly config: SsoConfigsSchemaTypeForSelect
|
||||
|
||||
constructor(config: SsoConfigsSchemaTypeForSelect) {
|
||||
this.config = config
|
||||
this.samlAssertion = new SAML(buildSamlOptions(config, 'assertion'))
|
||||
this.samlResponse = new SAML(buildSamlOptions(config, 'response'))
|
||||
}
|
||||
|
||||
private resolveCallbackUrl(req: Request): string {
|
||||
return this.config.samlCallbackUrl?.trim()
|
||||
|| `${PublicApiUrl.base(req)}/module/sso/callback/${this.config.id}`
|
||||
}
|
||||
|
||||
async initiateLogin(req: Request, res: Response, relayState?: string): Promise<void> {
|
||||
const loginUrl = await this.samlAssertion.getAuthorizeUrlAsync(relayState ?? '', req.hostname, {})
|
||||
const saml = new SAML(buildSamlOptions({
|
||||
config: this.config,
|
||||
mode: 'assertion',
|
||||
callbackUrl: this.resolveCallbackUrl(req),
|
||||
}))
|
||||
const loginUrl = await saml.getAuthorizeUrlAsync(relayState ?? '', req.hostname, {})
|
||||
res.redirect(loginUrl)
|
||||
}
|
||||
|
||||
async handleCallback(req: Request): Promise<SsoAuthResult> {
|
||||
const callbackUrl = this.resolveCallbackUrl(req)
|
||||
let profile
|
||||
|
||||
try {
|
||||
const result = await this.samlAssertion.validatePostResponseAsync(req.body)
|
||||
const saml = new SAML(buildSamlOptions({ config: this.config, mode: 'assertion', callbackUrl }))
|
||||
const result = await saml.validatePostResponseAsync(req.body)
|
||||
profile = result.profile
|
||||
} catch {
|
||||
const result = await this.samlResponse.validatePostResponseAsync(req.body)
|
||||
const saml = new SAML(buildSamlOptions({ config: this.config, mode: 'response', callbackUrl }))
|
||||
const result = await saml.validatePostResponseAsync(req.body)
|
||||
profile = result.profile
|
||||
}
|
||||
|
||||
@@ -61,14 +73,13 @@ export class SamlProvider implements SsoProvider {
|
||||
throw new Error('SAML response missing nameID')
|
||||
}
|
||||
|
||||
const email = (
|
||||
profile.email
|
||||
?? profile['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress']
|
||||
?? profile.nameID
|
||||
) as string
|
||||
const email = deriveSamlEmail(profile as Record<string, unknown>)
|
||||
if (!email) {
|
||||
throw new Error('SAML response missing email attribute')
|
||||
}
|
||||
|
||||
return {
|
||||
email: email.toLowerCase(),
|
||||
email,
|
||||
externalId: profile.nameID,
|
||||
displayName: (profile.displayName
|
||||
?? profile['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name']) as string | undefined,
|
||||
|
||||
@@ -4,6 +4,7 @@ export type SsoAuthResult = {
|
||||
email: string
|
||||
externalId: string
|
||||
displayName?: string
|
||||
preferredUsername?: string
|
||||
provider: string
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,64 @@
|
||||
import { randomBytes } from 'crypto'
|
||||
import { resolveTxt } from 'node:dns/promises'
|
||||
import type { SsoConfigsSchemaTypeForSelect } from 'taskview-db-schemas'
|
||||
import { decryptField } from '../../utils/crypto'
|
||||
import { generateString } from '../../utils/helpers'
|
||||
import type { CheckSsoDomainProofArgs, SsoDomainVerificationMethod } from './types'
|
||||
|
||||
export const SSO_SECRET_FIELDS = ['samlCert', 'samlSigningKey', 'samlSigningCert', 'oidcClientSecret'] as const
|
||||
|
||||
export function stripSecrets(config: SsoConfigsSchemaTypeForSelect) {
|
||||
export const SSO_DOMAIN_TXT_PREFIX = 'taskview-sso-verify='
|
||||
export const SSO_DOMAIN_WELL_KNOWN_PATH = '/.well-known/taskview-sso-verify.txt'
|
||||
|
||||
export function generateDomainVerifyToken(): string {
|
||||
return `tvdom_${randomBytes(32).toString('hex')}`
|
||||
}
|
||||
|
||||
const SAML_EMAIL_NAMEID_FORMAT = 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'
|
||||
const SAML_EMAIL_CLAIM = 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'
|
||||
|
||||
export function deriveSamlEmail(profile: Record<string, unknown>): string | null {
|
||||
const fromAttribute = profile.email ?? profile[SAML_EMAIL_CLAIM]
|
||||
if (typeof fromAttribute === 'string' && fromAttribute.trim()) {
|
||||
return fromAttribute.trim().toLowerCase()
|
||||
}
|
||||
if (profile.nameIDFormat === SAML_EMAIL_NAMEID_FORMAT
|
||||
&& typeof profile.nameID === 'string' && profile.nameID.trim()) {
|
||||
return profile.nameID.trim().toLowerCase()
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function trustedSsoDomains(): string[] {
|
||||
const raw = process.env.SSO_TRUSTED_DOMAINS
|
||||
if (!raw?.trim()) return []
|
||||
return raw
|
||||
.split(',')
|
||||
.map((domain) => domain.trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
export function isTrustedSsoDomain(domain: string): boolean {
|
||||
return trustedSsoDomains().includes(domain.trim().toLowerCase())
|
||||
}
|
||||
|
||||
export function isSsoDomainVerified(config: SsoConfigsSchemaTypeForSelect): boolean {
|
||||
if (isTrustedSsoDomain(config.emailDomainRestriction)) return true
|
||||
return !!config.domainVerifiedAt
|
||||
}
|
||||
|
||||
export function ssoDomainVerifyHttpUrl(domain: string): string {
|
||||
const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http'
|
||||
return `${protocol}://${domain}${SSO_DOMAIN_WELL_KNOWN_PATH}`
|
||||
}
|
||||
|
||||
export function ssoDomainVerifyDnsRecord(token: string): string {
|
||||
return `${SSO_DOMAIN_TXT_PREFIX}${token}`
|
||||
}
|
||||
|
||||
export function toClientSsoConfig(config: SsoConfigsSchemaTypeForSelect) {
|
||||
const { samlCert, samlSigningKey, samlSigningCert, oidcClientSecret, scimToken, ...safe } = config
|
||||
const token = config.domainVerifyToken
|
||||
return {
|
||||
...safe,
|
||||
hasSamlCert: !!samlCert,
|
||||
@@ -13,9 +66,65 @@ export function stripSecrets(config: SsoConfigsSchemaTypeForSelect) {
|
||||
hasSamlSigningCert: !!samlSigningCert,
|
||||
hasOidcClientSecret: !!oidcClientSecret,
|
||||
hasScimToken: !!scimToken,
|
||||
isDomainVerified: isSsoDomainVerified(config),
|
||||
isDomainTrusted: isTrustedSsoDomain(config.emailDomainRestriction),
|
||||
domainVerifyDnsRecord: token ? ssoDomainVerifyDnsRecord(token) : null,
|
||||
domainVerifyHttpUrl: ssoDomainVerifyHttpUrl(config.emailDomainRestriction),
|
||||
}
|
||||
}
|
||||
|
||||
export function stripSecrets(config: SsoConfigsSchemaTypeForSelect) {
|
||||
return toClientSsoConfig(config)
|
||||
}
|
||||
|
||||
function tokenMatchesProof(body: string, token: string): boolean {
|
||||
const trimmed = body.trim()
|
||||
return trimmed === token || trimmed === ssoDomainVerifyDnsRecord(token)
|
||||
}
|
||||
|
||||
export async function checkSsoDomainDnsTxt(args: CheckSsoDomainProofArgs): Promise<boolean> {
|
||||
try {
|
||||
const records = await resolveTxt(args.domain)
|
||||
return records.some((chunks) => tokenMatchesProof(chunks.join(''), args.token))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkSsoDomainHttpFile(args: CheckSsoDomainProofArgs): Promise<boolean> {
|
||||
const urls = process.env.NODE_ENV === 'production'
|
||||
? [`https://${args.domain}${SSO_DOMAIN_WELL_KNOWN_PATH}`]
|
||||
: [
|
||||
`https://${args.domain}${SSO_DOMAIN_WELL_KNOWN_PATH}`,
|
||||
`http://${args.domain}${SSO_DOMAIN_WELL_KNOWN_PATH}`,
|
||||
]
|
||||
|
||||
for (const url of urls) {
|
||||
const urlError = validateMetadataUrl(url)
|
||||
if (urlError) continue
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
if (!response.ok) continue
|
||||
if (tokenMatchesProof(await response.text(), args.token)) return true
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
export async function proveSsoDomainOwnership(args: CheckSsoDomainProofArgs): Promise<SsoDomainVerificationMethod | null> {
|
||||
if (isTrustedSsoDomain(args.domain)) return 'trusted'
|
||||
if (await checkSsoDomainDnsTxt(args)) return 'dns'
|
||||
if (await checkSsoDomainHttpFile(args)) return 'http'
|
||||
return null
|
||||
}
|
||||
|
||||
export function decryptSsoConfig(config: SsoConfigsSchemaTypeForSelect): SsoConfigsSchemaTypeForSelect {
|
||||
return {
|
||||
...config,
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { type } from 'arktype'
|
||||
import type { SsoConfigsSchemaTypeForSelect } from 'taskview-db-schemas'
|
||||
import type { UserDbRecord } from '../../types/auth.types'
|
||||
|
||||
export type SamlOptionsArgs = {
|
||||
config: SsoConfigsSchemaTypeForSelect
|
||||
mode: 'assertion' | 'response'
|
||||
callbackUrl: string
|
||||
}
|
||||
|
||||
export const SsoProtocols = {
|
||||
SAML: 'saml',
|
||||
@@ -52,7 +60,76 @@ export const SsoConfigArkTypeUpdate = type({
|
||||
'oidcScope?': 'string',
|
||||
|
||||
'defaultOrgRole?': "'admin' | 'member'",
|
||||
'emailDomainRestriction?': 'string',
|
||||
'emailDomainRestriction?': 'string > 0',
|
||||
})
|
||||
|
||||
export type SsoConfigArgUpdate = typeof SsoConfigArkTypeUpdate.infer
|
||||
|
||||
export type CheckSsoDomainProofArgs = {
|
||||
domain: string
|
||||
token: string
|
||||
}
|
||||
|
||||
export type SsoDomainVerificationMethod = 'dns' | 'http' | 'trusted'
|
||||
|
||||
export type StartDomainVerificationResult = {
|
||||
token: string
|
||||
dnsRecord: string
|
||||
httpUrl: string
|
||||
isDomainVerified: boolean
|
||||
isDomainTrusted: boolean
|
||||
}
|
||||
|
||||
export type CheckDomainVerificationResult = {
|
||||
verified: boolean
|
||||
method: SsoDomainVerificationMethod | null
|
||||
}
|
||||
|
||||
export class SsoDomainNotVerifiedError extends Error {
|
||||
readonly code = 'domain_unverified'
|
||||
|
||||
constructor() {
|
||||
super('SSO domain is not verified')
|
||||
this.name = 'SsoDomainNotVerifiedError'
|
||||
}
|
||||
}
|
||||
|
||||
export type FindSsoConfigByDomainAndOrgArgs = {
|
||||
domain: string
|
||||
organizationId: number
|
||||
}
|
||||
|
||||
export type FindSsoIdentityArgs = {
|
||||
ssoConfigId: number
|
||||
externalId: string
|
||||
}
|
||||
|
||||
export type FindSsoIdentityByUserArgs = {
|
||||
ssoConfigId: number
|
||||
userId: number
|
||||
}
|
||||
|
||||
export type UpsertSsoIdentityArgs = {
|
||||
userId: number
|
||||
ssoConfigId: number
|
||||
externalId: string
|
||||
email: string
|
||||
}
|
||||
|
||||
export type ResolveSsoUserArgs = {
|
||||
ssoConfigId: number
|
||||
email: string
|
||||
externalId: string
|
||||
preferredUsername?: string
|
||||
}
|
||||
|
||||
export type ApplySsoIdpEmailArgs = {
|
||||
user: UserDbRecord
|
||||
email: string
|
||||
}
|
||||
|
||||
export type SsoCallbackError = 'authentication_failed' | 'email_in_use' | 'account_blocked'
|
||||
|
||||
export type ResolveSsoUserResult =
|
||||
| { ok: true, user: UserDbRecord }
|
||||
| { ok: false, error: SsoCallbackError }
|
||||
|
||||
@@ -2,25 +2,14 @@ import { Router } from 'express';
|
||||
import type { Routable } from '../../types/routable.type';
|
||||
import { IsLoggedIn } from '../auth/middlewares/is-logged-in';
|
||||
import { CanAddTaskNew } from './middlewares/CanAddTaskNew';
|
||||
// import { CanAddTask } from './middlewares/CanAddTask';
|
||||
// import { CanUpdateTaskStatus } from './middlewares/CanUpdateTaskStatus';
|
||||
import { CanDeleteTask } from './middlewares/CanDeleteTask';
|
||||
// import { CanUpdateTaskAssignee } from './middlewares/CanUpdateTaskAssignee';
|
||||
import { CanFetchTask } from './middlewares/CanFetchTask';
|
||||
// import { CanUpdateTaskDescription } from './middlewares/CanUpdateTaskDescription';
|
||||
// import { CanUpdateTaskNote } from './middlewares/CanUpdateTaskNote';
|
||||
// import { CanUpdateTaskDeadline } from './middlewares/CanUpdateTaskDeadline';
|
||||
// import { CanFetchSubtasks } from './middlewares/CanFetchSubtasks';
|
||||
// import { CanUpdateTaskPriority } from './middlewares/CanUpdateTaskPriority';
|
||||
// import { CanMoveTask } from './middlewares/CanMoveTask';
|
||||
// import { CanSeeTaskAssignedUsers } from './middlewares/CanSeeTaskAssignedUsers';
|
||||
import { CanFetchTaskHistory } from './middlewares/CanFetchTaskHistory';
|
||||
import { CanFetchTasks } from './middlewares/CanFetchTasks';
|
||||
import { CanRecoveryTaskHistory } from './middlewares/CanRecoveryTaskHistory';
|
||||
import { CanUpdateTask } from './middlewares/CanUpdateTask';
|
||||
import { CanUpdateTaskAssigneeNew } from './middlewares/CanUpdateTaskAssigneeNew';
|
||||
import { TasksController } from './TasksController';
|
||||
// import { MainCanCreateTaskAction } from './middlewares/MainCanCreateTaskAction';
|
||||
|
||||
export default class TasksRoutes implements Routable {
|
||||
private readonly router: ReturnType<typeof Router>;
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { ALL_TASKS_LIST_ID, DEFAULT_ID } from '../../../types/tasks.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
export const CanAddTask = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const listId = req.body.componentId;
|
||||
|
||||
if (!listId) {
|
||||
return res.status(400).end();
|
||||
}
|
||||
|
||||
let permissions;
|
||||
if (Number(listId) === ALL_TASKS_LIST_ID && req.body.goalId && req.body.goalId !== DEFAULT_ID) {
|
||||
permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(Number(req.body.goalId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)
|
||||
.catch(logError);
|
||||
} else {
|
||||
permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(Number(listId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASKLIST)
|
||||
.catch(logError);
|
||||
}
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanAddTask middleware');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (
|
||||
permissions.hasPermissions(GoalPermissions.COMPONENT_CAN_ADD_TASKS) ||
|
||||
permissions.hasPermissions(GoalPermissions.TASKS_CAN_ADD_SUBTASKS)
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
export const CanFetchSubtasks = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const taskId = req.query.taskId;
|
||||
|
||||
if (!taskId) {
|
||||
return res.status(400).end();
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)
|
||||
.catch(logError);
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanFetchSubtasks');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_WATCH_SUBTASKS)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -5,7 +5,7 @@ import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
export const CanFetchTask = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const taskId = req.query.taskId || req.params.taskId;
|
||||
const taskId = req.params.taskId;
|
||||
|
||||
if (!taskId) {
|
||||
return res.status(400).end();
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
export const CanMoveTask = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const taskId = req.body.taskId;
|
||||
|
||||
if (!taskId) {
|
||||
return res.status(400).end();
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)
|
||||
.catch(logError);
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanMoveTask');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_DELETE)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
export const CanSeeTaskAssignedUsers = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const taskId = req.body.taskId;
|
||||
|
||||
if (!taskId) {
|
||||
return res.status(400).end();
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)
|
||||
.catch(logError);
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanSeeTaskAssignedUsers');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_WATCH_ASSIGNED_USERS)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -1,29 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
/** @deprecated */
|
||||
export const CanUpdateTaskAssignee = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const taskId = req.body.taskId;
|
||||
|
||||
if (!taskId) {
|
||||
return res.status(400).end();
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)
|
||||
.catch(logError);
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanUpdateTaskDescription');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_ASSIGN_USERS)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
export const CanUpdateTaskDeadline = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const taskId = req.body.taskId;
|
||||
|
||||
if (!taskId) {
|
||||
return res.status(400).end();
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)
|
||||
.catch(logError);
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanUpdateTaskDeadline');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_EDIT_DEADLINE)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
export const CanUpdateTaskDescription = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const taskId = req.body.taskId;
|
||||
|
||||
if (!taskId) {
|
||||
return res.status(400).end();
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)
|
||||
.catch(logError);
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanUpdateTaskDescription');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_EDIT_DESCRIPTION)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
export const CanUpdateTaskNote = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const taskId = req.body.taskId;
|
||||
|
||||
if (!taskId) {
|
||||
return res.status(400).end();
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)
|
||||
.catch(logError);
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanUpdateTaskNote');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_EDIT_NOTE)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
export const CanUpdateTaskPriority = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const taskId = req.body.taskId;
|
||||
|
||||
if (!taskId) {
|
||||
return res.status(400).end();
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)
|
||||
.catch(logError);
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanUpdateTaskPriority');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_EDIT_PRIORITY)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';
|
||||
import { $logger } from '../../../modules/logget';
|
||||
import { GoalPermissions } from '../../../types/auth.types';
|
||||
import { logError } from '../../../utils/api';
|
||||
|
||||
export const CanUpdateTaskStatus = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const taskId = req.body.taskId;
|
||||
|
||||
if (!taskId) {
|
||||
return res.status(400).end();
|
||||
}
|
||||
|
||||
const permissions = await req.appUser.permissionsFetcher
|
||||
.getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)
|
||||
.catch(logError);
|
||||
|
||||
if (!permissions) {
|
||||
$logger.error('Can not get permissions for CanAddTask middleware');
|
||||
return res.status(500).end();
|
||||
}
|
||||
|
||||
if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_EDIT_STATUS)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(403).end();
|
||||
};
|
||||
@@ -3,6 +3,8 @@ import type { Routable } from '../../types/routable.type'
|
||||
import { IsLoggedIn } from '../auth/middlewares/is-logged-in'
|
||||
import { WebhooksController } from './WebhooksController'
|
||||
import { IsGoalOwnerByGoalId, IsGoalOwnerByWebhookId } from './middlewares/IsGoalOwner'
|
||||
import { RequireTokenPermission } from '../../middlewares/require-token-permission';
|
||||
import { GoalPermissions } from '../../types/auth.types';
|
||||
|
||||
export default class WebhooksRoutes implements Routable {
|
||||
private readonly router: ReturnType<typeof Router>
|
||||
@@ -19,13 +21,15 @@ export default class WebhooksRoutes implements Routable {
|
||||
}
|
||||
|
||||
initRoutes() {
|
||||
this.router.get('', [IsLoggedIn, IsGoalOwnerByGoalId], this.controller.fetch)
|
||||
this.router.post('', [IsLoggedIn, IsGoalOwnerByGoalId], this.controller.create)
|
||||
this.router.patch('', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.update)
|
||||
this.router.delete('', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.delete)
|
||||
this.router.post('/rotate-secret', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.rotateSecret)
|
||||
this.router.post('/test', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.testDelivery)
|
||||
this.router.get('/deliveries/:id', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.fetchDeliveries)
|
||||
this.router.post('/retry', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.retryDelivery)
|
||||
const canManageWebhooks = RequireTokenPermission(GoalPermissions.WEBHOOKS_CAN_MANAGE)
|
||||
|
||||
this.router.get('', [IsLoggedIn, IsGoalOwnerByGoalId, canManageWebhooks], this.controller.fetch)
|
||||
this.router.post('', [IsLoggedIn, IsGoalOwnerByGoalId, canManageWebhooks], this.controller.create)
|
||||
this.router.patch('', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.update)
|
||||
this.router.delete('', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.delete)
|
||||
this.router.post('/rotate-secret', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.rotateSecret)
|
||||
this.router.post('/test', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.testDelivery)
|
||||
this.router.get('/deliveries/:id', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.fetchDeliveries)
|
||||
this.router.post('/retry', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.retryDelivery)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,6 +115,12 @@ export type UpdateUserCredentialsArgs = {
|
||||
passwordHash: string;
|
||||
};
|
||||
|
||||
export type UpdateUserEmailArgs = {
|
||||
userId: number;
|
||||
oldEmail: string;
|
||||
email: string;
|
||||
};
|
||||
|
||||
export type UpdateUserCredentialsResult = 'ok' | 'conflict' | 'error';
|
||||
|
||||
export const RefreshTokenSchema = z.object({
|
||||
@@ -188,6 +194,13 @@ export const GoalPermissions = {
|
||||
TIMETRACKING_CAN_LOG: 'timetracking_can_log',
|
||||
TIMETRACKING_CAN_MANAGE_ALL: 'timetracking_can_manage_all',
|
||||
|
||||
ORG_CAN_VIEW: 'org_can_view',
|
||||
ORG_CAN_MANAGE: 'org_can_manage',
|
||||
ORG_CAN_MANAGE_MEMBERS: 'org_can_manage_members',
|
||||
SSO_CAN_MANAGE: 'sso_can_manage',
|
||||
WEBHOOKS_CAN_MANAGE: 'webhooks_can_manage',
|
||||
BILLING_CAN_MANAGE: 'billing_can_manage',
|
||||
|
||||
SPRINT_CAN_VIEW: 'sprint_can_view',
|
||||
SPRINT_CAN_MANAGE: 'sprint_can_manage',
|
||||
SPRINT_CAN_ASSIGN_TASKS: 'sprint_can_assign_tasks',
|
||||
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
declare module 'pdfmake/build/vfs_fonts.js' {
|
||||
const vfs: Record<string, string>
|
||||
export default vfs
|
||||
}
|
||||
@@ -29,6 +29,15 @@ export function generateString(length: number) {
|
||||
return result
|
||||
}
|
||||
|
||||
export function generateLetters(length: number) {
|
||||
let result = ''
|
||||
const characters = 'abcdefghijklmnopqrstuvwxyz'
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += characters.charAt(randomInt(characters.length))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function time() {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user