redwax-cli 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +90 -3
  2. package/dashboard/apple-touch-icon.png +0 -0
  3. package/dashboard/assets/data-DnUM1Mpn.js +17 -0
  4. package/dashboard/assets/index-Cb3ZdSPZ.js +191 -0
  5. package/dashboard/assets/index-GSeTo6vS.css +1 -0
  6. package/dashboard/assets/radix-Cu8wEyce.js +41 -0
  7. package/dashboard/assets/react-Cnjii2my.js +59 -0
  8. package/dashboard/favicon.svg +12 -0
  9. package/dashboard/index.html +37 -0
  10. package/package.json +68 -6
  11. package/scripts/bundle.cjs +56 -0
  12. package/server/package.json +5 -0
  13. package/server/src/app.js +141 -0
  14. package/server/src/config/env.js +102 -0
  15. package/server/src/config/keys.js +81 -0
  16. package/server/src/config/metrics.js +161 -0
  17. package/server/src/config/openapi.js +507 -0
  18. package/server/src/controllers/auth.controller.js +115 -0
  19. package/server/src/controllers/project.controller.js +154 -0
  20. package/server/src/controllers/secret.controller.js +138 -0
  21. package/server/src/domain.js +49 -0
  22. package/server/src/middleware/auth.middleware.js +26 -0
  23. package/server/src/middleware/rateLimit.middleware.js +49 -0
  24. package/server/src/middleware/rbac.middleware.js +47 -0
  25. package/server/src/middleware/validate.middleware.js +35 -0
  26. package/server/src/models/AuditLog.model.js +32 -0
  27. package/server/src/models/Project.model.js +33 -0
  28. package/server/src/models/Secret.model.js +30 -0
  29. package/server/src/models/SecretVersion.model.js +25 -0
  30. package/server/src/models/User.model.js +31 -0
  31. package/server/src/routes/auth.routes.js +15 -0
  32. package/server/src/routes/project.routes.js +45 -0
  33. package/server/src/routes/secret.routes.js +44 -0
  34. package/server/src/services/audit.service.js +65 -0
  35. package/server/src/services/auth.service.js +130 -0
  36. package/server/src/services/crypto.service.js +73 -0
  37. package/server/src/services/project.service.js +178 -0
  38. package/server/src/services/secret.service.js +198 -0
  39. package/server/src/start.js +49 -0
  40. package/server/src/store/index.js +60 -0
  41. package/server/src/store/mongo.js +336 -0
  42. package/server/src/store/sqlite.js +538 -0
  43. package/server/src/store/sqliteRuntime.js +64 -0
  44. package/server/src/utils/apiError.js +10 -0
  45. package/server/src/utils/asyncHandler.js +8 -0
  46. package/server/src/utils/logger.js +20 -0
  47. package/server/src/utils/requestContext.js +19 -0
  48. package/src/commands/diff.js +64 -0
  49. package/src/commands/history.js +56 -0
  50. package/src/commands/init.js +59 -0
  51. package/src/commands/login.js +53 -0
  52. package/src/commands/logout.js +30 -0
  53. package/src/commands/pull.js +82 -0
  54. package/src/commands/push.js +76 -0
  55. package/src/commands/server.js +313 -0
  56. package/src/commands/whoami.js +26 -0
  57. package/src/index.js +52 -0
  58. package/src/lib/api.js +137 -0
  59. package/src/lib/config.js +36 -0
  60. package/src/lib/credentials.js +43 -0
  61. package/src/lib/dotenv.js +88 -0
  62. package/src/lib/prompt.js +50 -0
  63. package/src/lib/runtime.js +88 -0
  64. package/src/lib/ui.js +68 -0
@@ -0,0 +1,45 @@
1
+ const { z } = require('zod');
2
+ const router = require('express').Router();
3
+
4
+ const {
5
+ PERMISSIONS,
6
+ createProjectSchema,
7
+ updateProjectSchema,
8
+ inviteMemberSchema,
9
+ updateMemberRoleSchema,
10
+ auditQuerySchema,
11
+ objectIdSchema,
12
+ } = require('@redwax/shared');
13
+
14
+ const { protect } = require('../middleware/auth.middleware');
15
+ const { requirePermission } = require('../middleware/rbac.middleware');
16
+ const { validate, validateQuery } = require('../middleware/validate.middleware');
17
+ const controller = require('../controllers/project.controller');
18
+ const secretRoutes = require('./secret.routes');
19
+
20
+ const transferSchema = z.object({ userId: objectIdSchema });
21
+
22
+ router.use(protect);
23
+
24
+ router.get('/', controller.list);
25
+ router.post('/', validate(createProjectSchema), controller.create);
26
+
27
+ // Two segments, so it cannot collide with GET /:id. Used by `redwax init`.
28
+ router.get('/slug/:slug', controller.getBySlug);
29
+
30
+ router.get('/:id', requirePermission(PERMISSIONS.READ_SECRETS), controller.get);
31
+ router.patch('/:id', requirePermission(PERMISSIONS.UPDATE_PROJECT), validate(updateProjectSchema), controller.update);
32
+ router.delete('/:id', requirePermission(PERMISSIONS.DELETE_PROJECT), controller.remove);
33
+
34
+ router.post('/:id/members', requirePermission(PERMISSIONS.MANAGE_MEMBERS), validate(inviteMemberSchema), controller.addMember);
35
+ router.patch('/:id/members/:uid', requirePermission(PERMISSIONS.MANAGE_MEMBERS), validate(updateMemberRoleSchema), controller.updateMemberRole);
36
+ router.delete('/:id/members/:uid', requirePermission(PERMISSIONS.MANAGE_MEMBERS), controller.removeMember);
37
+
38
+ // Handing over the owner role is an owner-only action.
39
+ router.post('/:id/transfer', requirePermission(PERMISSIONS.DELETE_PROJECT), validate(transferSchema), controller.transferOwnership);
40
+
41
+ router.get('/:id/audit', requirePermission(PERMISSIONS.VIEW_AUDIT), validateQuery(auditQuerySchema), controller.auditLog);
42
+
43
+ router.use('/:id/secrets', secretRoutes);
44
+
45
+ module.exports = router;
@@ -0,0 +1,44 @@
1
+ // Mounted at /api/v1/projects/:id/secrets — `protect` already ran on the
2
+ // parent router, so these routes only add the RBAC and validation layers.
3
+ const { z } = require('zod');
4
+ const router = require('express').Router({ mergeParams: true });
5
+
6
+ const {
7
+ PERMISSIONS,
8
+ environmentQuerySchema,
9
+ createSecretSchema,
10
+ updateSecretSchema,
11
+ bulkImportSchema,
12
+ secretKeySchema,
13
+ } = require('@redwax/shared');
14
+
15
+ const { requirePermission } = require('../middleware/rbac.middleware');
16
+ const { validate, validateQuery, validateParams } = require('../middleware/validate.middleware');
17
+ const controller = require('../controllers/secret.controller');
18
+
19
+ // The key in the URL must obey the same rules as a key in a body; otherwise
20
+ // PATCH /:key would create secrets that POST would have rejected.
21
+ const keyParam = validateParams(z.object({ key: secretKeySchema }));
22
+
23
+ const exportQuerySchema = environmentQuerySchema.extend({
24
+ format: z.enum(['env', 'json']).default('env'),
25
+ });
26
+
27
+ const canRead = requirePermission(PERMISSIONS.READ_SECRETS);
28
+ const canWrite = requirePermission(PERMISSIONS.WRITE_SECRETS);
29
+ const canDelete = requirePermission(PERMISSIONS.DELETE_SECRETS);
30
+
31
+ router.get('/', canRead, validateQuery(environmentQuerySchema), controller.list);
32
+ router.post('/', canWrite, validate(createSecretSchema), controller.upsert);
33
+
34
+ // Literal paths must precede /:key or they would be swallowed by it.
35
+ router.post('/bulk', canWrite, validate(bulkImportSchema), controller.bulkImport);
36
+ router.get('/export', canRead, validateQuery(exportQuerySchema), controller.exportEnv);
37
+
38
+ router.get('/:key/history', canRead, keyParam, validateQuery(environmentQuerySchema), controller.history);
39
+
40
+ router.get('/:key', canRead, keyParam, validateQuery(environmentQuerySchema), controller.reveal);
41
+ router.patch('/:key', canWrite, keyParam, validate(updateSecretSchema), controller.update);
42
+ router.delete('/:key', canDelete, keyParam, validateQuery(environmentQuerySchema), controller.remove);
43
+
44
+ module.exports = router;
@@ -0,0 +1,65 @@
1
+ const store = require('../store');
2
+ const logger = require('../utils/logger');
3
+
4
+ /**
5
+ * Fire-and-forget audit logger.
6
+ * Never throws — an audit failure must not break the request it describes.
7
+ */
8
+ async function logEvent(event) {
9
+ try {
10
+ await store.audit.add(event);
11
+ } catch (err) {
12
+ logger.error('Audit log write failed', { error: err.message, action: event.action });
13
+ }
14
+ }
15
+
16
+ /** Batch variant for bulk operations — one write instead of N. */
17
+ async function logEvents(events) {
18
+ if (!events.length) return;
19
+ try {
20
+ await store.audit.addMany(events);
21
+ } catch (err) {
22
+ logger.error('Audit log batch write failed', { error: err.message, count: events.length });
23
+ }
24
+ }
25
+
26
+ /** Paginated, filtered audit trail for a project. */
27
+ async function listAuditLogs({ projectId, page = 1, limit = 50, user, action, from, to }) {
28
+ const { entries, total } = await store.audit.list({ projectId, userId: user, action, from, to, page, limit });
29
+ return {
30
+ entries,
31
+ pagination: { page, limit, total, pages: Math.max(1, Math.ceil(total / limit)) },
32
+ };
33
+ }
34
+
35
+ const CSV_COLUMNS = ['timestamp', 'action', 'user', 'email', 'secretKey', 'environment', 'ip', 'userAgent'];
36
+
37
+ function escapeCsv(value) {
38
+ let str = value === null || value === undefined ? '' : String(value);
39
+ // Neutralise spreadsheet formula injection: user names and User-Agent
40
+ // strings are attacker-controlled, and Excel/Sheets execute cells that start
41
+ // with these characters (e.g. =HYPERLINK(...)).
42
+ if (/^[=+\-@\t\r]/.test(str)) str = `'${str}`;
43
+ return /[",\n\r]/.test(str) ? `"${str.replace(/"/g, '""')}"` : str;
44
+ }
45
+
46
+ /** Render audit entries as CSV (FR-AUDIT-04). */
47
+ function toCsv(entries) {
48
+ const rows = entries.map((e) =>
49
+ [
50
+ e.timestamp instanceof Date ? e.timestamp.toISOString() : e.timestamp,
51
+ e.action,
52
+ e.user?.name || '',
53
+ e.user?.email || '',
54
+ e.secretKey || '',
55
+ e.environment || '',
56
+ e.ip || '',
57
+ e.userAgent || '',
58
+ ]
59
+ .map(escapeCsv)
60
+ .join(',')
61
+ );
62
+ return [CSV_COLUMNS.join(','), ...rows].join('\n');
63
+ }
64
+
65
+ module.exports = { logEvent, logEvents, listAuditLogs, toCsv };
@@ -0,0 +1,130 @@
1
+ const bcrypt = require('bcryptjs');
2
+ const jwt = require('jsonwebtoken');
3
+ const crypto = require('crypto');
4
+
5
+ const { privateKey, publicKey } = require('../config/keys');
6
+ const { JWT_EXPIRES_IN, REFRESH_TOKEN_EXPIRES_IN } = require('../config/env');
7
+
8
+ const SALT_ROUNDS = 12;
9
+ const ISSUER = 'redwax';
10
+ const ALGORITHM = 'RS256';
11
+
12
+ /* ── passwords ──────────────────────────────────────────────────────────── */
13
+
14
+ async function hashPassword(password) {
15
+ return bcrypt.hash(password, SALT_ROUNDS);
16
+ }
17
+
18
+ async function verifyPassword(password, hash) {
19
+ return bcrypt.compare(password, hash);
20
+ }
21
+
22
+ // Hash compared against when the email is unknown, so a failed login takes the
23
+ // same time whether or not the account exists (no timing-based enumeration).
24
+ let dummyHashPromise = null;
25
+ async function burnPasswordCheck(password) {
26
+ dummyHashPromise = dummyHashPromise || bcrypt.hash(crypto.randomBytes(16).toString('hex'), SALT_ROUNDS);
27
+ await bcrypt.compare(password, await dummyHashPromise);
28
+ return false;
29
+ }
30
+
31
+ /* ── access tokens (stateless, RS256) ───────────────────────────────────── */
32
+
33
+ function signAccessToken(user) {
34
+ return jwt.sign(
35
+ { sub: String(user.id), email: user.email, name: user.name },
36
+ privateKey,
37
+ { algorithm: ALGORITHM, expiresIn: JWT_EXPIRES_IN, issuer: ISSUER }
38
+ );
39
+ }
40
+
41
+ function verifyAccessToken(token) {
42
+ return jwt.verify(token, publicKey, { algorithms: [ALGORITHM], issuer: ISSUER });
43
+ }
44
+
45
+ /* ── refresh tokens (opaque, hashed at rest, rotated on use) ────────────── */
46
+
47
+ /**
48
+ * The cookie/credential value is `<userId>.<secret>`; only the SHA-256 of the
49
+ * secret half is persisted, so a database leak cannot be replayed.
50
+ */
51
+ function generateRefreshToken(userId) {
52
+ const secret = crypto.randomBytes(48).toString('hex');
53
+ return { token: `${userId}.${secret}`, hash: hashRefreshToken(secret) };
54
+ }
55
+
56
+ function hashRefreshToken(secret) {
57
+ return crypto.createHash('sha256').update(secret).digest('hex');
58
+ }
59
+
60
+ function parseRefreshToken(value) {
61
+ if (typeof value !== 'string' || value.length > 256) return null;
62
+ const index = value.indexOf('.');
63
+ if (index <= 0) return null;
64
+ const secret = value.slice(index + 1);
65
+ if (!secret) return null;
66
+ return { userId: value.slice(0, index), secret };
67
+ }
68
+
69
+ /**
70
+ * Timing-safe comparison of a presented refresh secret against the stored
71
+ * hash. Also rejects tokens past their server-side expiry.
72
+ */
73
+ function refreshTokenMatches(secret, storedHash, expiresAt) {
74
+ if (!storedHash) return false;
75
+ if (expiresAt !== undefined && (!expiresAt || new Date(expiresAt).getTime() <= Date.now())) return false;
76
+ const candidate = Buffer.from(hashRefreshToken(secret));
77
+ const stored = Buffer.from(storedHash);
78
+ if (candidate.length !== stored.length) return false;
79
+ return crypto.timingSafeEqual(candidate, stored);
80
+ }
81
+
82
+ /* ── cookies ────────────────────────────────────────────────────────────── */
83
+
84
+ const REFRESH_COOKIE = 'redwax_refresh';
85
+
86
+ /** Parse a duration like `15m` or `7d` into milliseconds. */
87
+ function parseDuration(value, fallbackMs = 7 * 24 * 60 * 60 * 1000) {
88
+ const match = /^(\d+)\s*([smhd])$/.exec(String(value).trim());
89
+ if (!match) return fallbackMs;
90
+ const multipliers = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
91
+ return Number(match[1]) * multipliers[match[2]];
92
+ }
93
+
94
+ /** When a refresh token issued now stops being accepted. */
95
+ function refreshTokenExpiry() {
96
+ return new Date(Date.now() + parseDuration(REFRESH_TOKEN_EXPIRES_IN));
97
+ }
98
+
99
+ /**
100
+ * `secure` follows how the request actually arrived, not NODE_ENV. Marking the
101
+ * cookie Secure on a plain-http office network makes the browser drop it, and
102
+ * everyone is silently logged out when their 15-minute access token expires.
103
+ * Behind a TLS-terminating proxy, req.secure is true via TRUST_PROXY.
104
+ */
105
+ function refreshCookieOptions(req) {
106
+ return {
107
+ httpOnly: true,
108
+ secure: Boolean(req?.secure),
109
+ sameSite: 'lax',
110
+ path: '/api/v1/auth',
111
+ maxAge: parseDuration(REFRESH_TOKEN_EXPIRES_IN),
112
+ };
113
+ }
114
+
115
+ module.exports = {
116
+ hashPassword,
117
+ verifyPassword,
118
+ burnPasswordCheck,
119
+ refreshTokenExpiry,
120
+ signAccessToken,
121
+ verifyAccessToken,
122
+ generateRefreshToken,
123
+ hashRefreshToken,
124
+ parseRefreshToken,
125
+ refreshTokenMatches,
126
+ refreshCookieOptions,
127
+ parseDuration,
128
+ REFRESH_COOKIE,
129
+ ISSUER,
130
+ };
@@ -0,0 +1,73 @@
1
+ const crypto = require('crypto');
2
+ const { MASTER_KEY } = require('../config/env');
3
+
4
+ const ALGORITHM = 'aes-256-gcm';
5
+ const IV_BYTES = 12; // 96-bit IV, the GCM-recommended size
6
+ const KEY_BYTES = 32; // AES-256
7
+ const TAG_BYTES = 16; // 128-bit auth tag
8
+
9
+ const KEY = Buffer.from(MASTER_KEY, 'hex');
10
+ if (KEY.length !== KEY_BYTES) {
11
+ throw new Error(`MASTER_KEY must decode to ${KEY_BYTES} bytes, got ${KEY.length}`);
12
+ }
13
+
14
+ /**
15
+ * Encrypt a plaintext value with AES-256-GCM.
16
+ * A fresh IV is generated on every call — an IV must never be reused with the
17
+ * same key, so callers must store the returned iv alongside the ciphertext.
18
+ *
19
+ * @returns {{ ciphertext: string, iv: string, authTag: string }}
20
+ * ciphertext is base64; iv and authTag are hex.
21
+ */
22
+ function encrypt(plaintext) {
23
+ if (typeof plaintext !== 'string') {
24
+ throw new TypeError('encrypt() expects a string');
25
+ }
26
+
27
+ const iv = crypto.randomBytes(IV_BYTES);
28
+ const cipher = crypto.createCipheriv(ALGORITHM, KEY, iv);
29
+ const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
30
+
31
+ return {
32
+ ciphertext: encrypted.toString('base64'),
33
+ iv: iv.toString('hex'),
34
+ authTag: cipher.getAuthTag().toString('hex'),
35
+ };
36
+ }
37
+
38
+ /**
39
+ * Decrypt a value produced by encrypt(). Throws if the ciphertext, IV or auth
40
+ * tag has been tampered with — GCM verifies integrity as part of decryption.
41
+ */
42
+ function decrypt({ ciphertext, iv, authTag } = {}) {
43
+ // An empty string is a valid ciphertext (the secret was ""), so test for
44
+ // absence rather than falsiness.
45
+ if (typeof ciphertext !== 'string' || !iv || !authTag) {
46
+ throw new Error('decrypt() requires ciphertext, iv and authTag');
47
+ }
48
+
49
+ const ivBuffer = Buffer.from(iv, 'hex');
50
+ const tagBuffer = Buffer.from(authTag, 'hex');
51
+
52
+ if (ivBuffer.length !== IV_BYTES) throw new Error('Invalid IV length');
53
+ if (tagBuffer.length !== TAG_BYTES) throw new Error('Invalid auth tag length');
54
+
55
+ const decipher = crypto.createDecipheriv(ALGORITHM, KEY, ivBuffer);
56
+ decipher.setAuthTag(tagBuffer);
57
+
58
+ const decrypted = Buffer.concat([
59
+ decipher.update(Buffer.from(ciphertext, 'base64')),
60
+ decipher.final(),
61
+ ]);
62
+ return decrypted.toString('utf8');
63
+ }
64
+
65
+ /** Constant-time comparison, for tokens and digests. */
66
+ function safeEqual(a, b) {
67
+ const bufA = Buffer.from(String(a));
68
+ const bufB = Buffer.from(String(b));
69
+ if (bufA.length !== bufB.length) return false;
70
+ return crypto.timingSafeEqual(bufA, bufB);
71
+ }
72
+
73
+ module.exports = { encrypt, decrypt, safeEqual, ALGORITHM, IV_BYTES };
@@ -0,0 +1,178 @@
1
+ const { ROLES, DEFAULT_ENVIRONMENTS, slugify } = require('@redwax/shared');
2
+
3
+ const store = require('../store');
4
+ const ApiError = require('../utils/apiError');
5
+ const { roleOf } = require('../domain');
6
+ const { logEvent } = require('./audit.service');
7
+
8
+ /** Every project the user belongs to, newest first. */
9
+ async function listProjects(userId) {
10
+ return store.projects.listForUser(userId);
11
+ }
12
+
13
+ async function getProject(projectId) {
14
+ const project = await store.projects.findById(projectId);
15
+ if (!project) throw new ApiError(404, 'Project not found');
16
+ return project;
17
+ }
18
+
19
+ async function getProjectBySlug(slug, userId) {
20
+ const project = await store.projects.findBySlug(slug);
21
+ // 404 for non-members too, matching requirePermission: the API must not
22
+ // confirm that a slug exists to someone with no access to it.
23
+ if (!project || !roleOf(project, userId)) throw new ApiError(404, 'Project not found');
24
+ return project;
25
+ }
26
+
27
+ async function createProject({ name, slug, description, environments, userId, ip, userAgent }) {
28
+ const finalSlug = slug || slugify(name);
29
+ if (!finalSlug) throw new ApiError(400, 'Could not derive a slug from the project name');
30
+
31
+ if (await store.projects.existsBySlug(finalSlug)) {
32
+ throw new ApiError(409, `A project with slug '${finalSlug}' already exists`);
33
+ }
34
+
35
+ const project = await store.projects.create({
36
+ name,
37
+ slug: finalSlug,
38
+ description: description || '',
39
+ environments: environments?.length ? [...new Set(environments)] : [...DEFAULT_ENVIRONMENTS],
40
+ ownerId: userId,
41
+ });
42
+
43
+ await logEvent({ action: 'project.create', project: project.id, user: userId, ip, userAgent });
44
+ return project;
45
+ }
46
+
47
+ async function updateProject({ projectId, name, description, addEnvironment, removeEnvironment }) {
48
+ const project = await getProject(projectId);
49
+
50
+ if (name !== undefined) project.name = name;
51
+ if (description !== undefined) project.description = description;
52
+
53
+ if (addEnvironment && !project.environments.includes(addEnvironment)) {
54
+ project.environments.push(addEnvironment);
55
+ }
56
+
57
+ if (removeEnvironment) {
58
+ if (!project.environments.includes(removeEnvironment)) {
59
+ throw new ApiError(404, `Environment '${removeEnvironment}' does not exist`);
60
+ }
61
+ if (project.environments.length === 1) {
62
+ throw new ApiError(400, 'A project must keep at least one environment');
63
+ }
64
+ const secretCount = await store.secrets.countLive(projectId, removeEnvironment);
65
+ if (secretCount > 0) {
66
+ throw new ApiError(409, `Environment '${removeEnvironment}' still holds ${secretCount} secret(s)`);
67
+ }
68
+ project.environments = project.environments.filter((e) => e !== removeEnvironment);
69
+ }
70
+
71
+ return store.projects.save(project);
72
+ }
73
+
74
+ /** Deletes the project and cascades to secrets, version history and audit logs. */
75
+ async function deleteProject({ projectId, userId, ip, userAgent }) {
76
+ const project = await getProject(projectId);
77
+ await store.projects.removeCascade(projectId);
78
+ await logEvent({ action: 'project.delete', user: userId, ip, userAgent, metadata: { slug: project.slug } });
79
+ return { deleted: true };
80
+ }
81
+
82
+ /* ── members ────────────────────────────────────────────────────────────── */
83
+
84
+ const findMember = (project, userId) => project.members.find((m) => String(m.userId) === String(userId));
85
+
86
+ async function addMember({ projectId, email, role, actorId, ip, userAgent }) {
87
+ const project = await getProject(projectId);
88
+
89
+ const user = await store.users.findByEmail(email);
90
+ // No email delivery in v1 — the invitee must already have an account.
91
+ if (!user) throw new ApiError(404, `No registered user with email '${email}'`);
92
+
93
+ if (roleOf(project, user.id)) throw new ApiError(409, 'User is already a member of this project');
94
+ if (role === ROLES.OWNER) throw new ApiError(400, 'Use ownership transfer to assign the owner role');
95
+
96
+ project.members.push({ userId: user.id, role, addedAt: new Date() });
97
+ const saved = await store.projects.save(project);
98
+
99
+ await logEvent({
100
+ action: 'member.invite', project: projectId, user: actorId, ip, userAgent,
101
+ metadata: { targetUser: user.id, email: user.email, role },
102
+ });
103
+
104
+ return saved;
105
+ }
106
+
107
+ async function updateMemberRole({ projectId, memberId, role, actorId, ip, userAgent }) {
108
+ const project = await getProject(projectId);
109
+
110
+ const member = findMember(project, memberId);
111
+ if (!member) throw new ApiError(404, 'Member not found');
112
+
113
+ if (member.role === ROLES.OWNER) throw new ApiError(400, 'Transfer ownership instead of changing the owner role');
114
+ if (role === ROLES.OWNER) throw new ApiError(400, 'Use ownership transfer to assign the owner role');
115
+
116
+ member.role = role;
117
+ const saved = await store.projects.save(project);
118
+
119
+ await logEvent({
120
+ action: 'member.role_change', project: projectId, user: actorId, ip, userAgent,
121
+ metadata: { targetUser: String(memberId), role },
122
+ });
123
+
124
+ return saved;
125
+ }
126
+
127
+ async function removeMember({ projectId, memberId, actorId, ip, userAgent }) {
128
+ const project = await getProject(projectId);
129
+
130
+ const member = findMember(project, memberId);
131
+ if (!member) throw new ApiError(404, 'Member not found');
132
+ if (member.role === ROLES.OWNER) throw new ApiError(400, 'The owner cannot be removed — transfer ownership first');
133
+
134
+ project.members = project.members.filter((m) => String(m.userId) !== String(memberId));
135
+ const saved = await store.projects.save(project);
136
+
137
+ await logEvent({
138
+ action: 'member.remove', project: projectId, user: actorId, ip, userAgent,
139
+ metadata: { targetUser: String(memberId) },
140
+ });
141
+
142
+ return saved;
143
+ }
144
+
145
+ /** Hands the owner role to an existing member; the previous owner becomes an admin. */
146
+ async function transferOwnership({ projectId, newOwnerId, actorId, ip, userAgent }) {
147
+ const project = await getProject(projectId);
148
+
149
+ const target = findMember(project, newOwnerId);
150
+ if (!target) throw new ApiError(404, 'New owner must already be a member of the project');
151
+ if (String(newOwnerId) === String(actorId)) throw new ApiError(400, 'You already own this project');
152
+
153
+ const currentOwner = project.members.find((m) => m.role === ROLES.OWNER);
154
+ if (currentOwner) currentOwner.role = ROLES.ADMIN;
155
+ target.role = ROLES.OWNER;
156
+
157
+ const saved = await store.projects.save(project);
158
+
159
+ await logEvent({
160
+ action: 'project.transfer', project: projectId, user: actorId, ip, userAgent,
161
+ metadata: { newOwner: String(newOwnerId) },
162
+ });
163
+
164
+ return saved;
165
+ }
166
+
167
+ module.exports = {
168
+ listProjects,
169
+ getProject,
170
+ getProjectBySlug,
171
+ createProject,
172
+ updateProject,
173
+ deleteProject,
174
+ addMember,
175
+ updateMemberRole,
176
+ removeMember,
177
+ transferOwnership,
178
+ };