@bongos/core 1.24.5 → 1.24.7

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 (53) hide show
  1. package/.bongos-core.json +79 -54
  2. package/clients/bongos-client/README.md +1 -1
  3. package/clients/bongos-client/bongos-client.global.js +6 -0
  4. package/clients/bongos-client/index.cjs +6 -0
  5. package/clients/bongos-client/index.d.ts +8 -1
  6. package/clients/bongos-client/index.mjs +6 -0
  7. package/docs/adr/0371-auto-pickup-applies-a-submitted-tweak-on-the-runner.md +1 -0
  8. package/docs/adr/0396-google-sign-in-a-stand-in-login-and-a-browser-approved-cli-sign-in.md +8 -0
  9. package/docs/api/openapi.json +114 -6
  10. package/docs/api-reference.md +7 -4
  11. package/docs/copy-inventory.md +52 -43
  12. package/docs/copy-registry.json +145 -63
  13. package/docs/module-api-changelog.md +4 -0
  14. package/docs/page-inventory.json +2 -1
  15. package/docs/page-readings.json +71 -63
  16. package/migrations/core_286_credit_log_no_spend.sql +128 -0
  17. package/modules/copy-desk/auto-close.js +5 -3
  18. package/modules/copy-desk/page-status.js +7 -4
  19. package/modules/copy-desk/tests/copy_page_auto_close.mjs +4 -4
  20. package/modules/hall-ui/public/project-settings.html +4 -4
  21. package/modules/hall-ui/public/project-settings.js +51 -1
  22. package/modules/lifecycle/autopickup.js +26 -9
  23. package/modules/lifecycle/db-claims.js +1 -1
  24. package/modules/lifecycle/routes/claims.js +7 -1
  25. package/modules/lifecycle/routes/project-settings.js +71 -10
  26. package/modules/platform-identity/account-logins.js +131 -0
  27. package/modules/platform-identity/migrations/platform_identity_035_account_login_email_idx.sql +19 -0
  28. package/modules/platform-identity/routes/profile.js +29 -1
  29. package/modules/platform-identity/routes/sso.js +25 -3
  30. package/modules/public-landing/public/account.html +114 -0
  31. package/modules/public-landing/public/account.states.json +1 -0
  32. package/modules/ui-design/kit/serve.js +24 -0
  33. package/package-lock.json +2 -2
  34. package/package.json +1 -1
  35. package/release-notes.json +24 -0
  36. package/scripts/bongos/run-unit-tests.js +4 -0
  37. package/src/bongos/auth-github.js +24 -7
  38. package/src/bongos/project-settings.js +59 -15
  39. package/src/bongos/routes/auth-google.js +71 -5
  40. package/src/bongos/routes/auth-link.js +132 -0
  41. package/src/bongos/routes.js +2 -0
  42. package/src/bongos/sign-in-pages.js +20 -1
  43. package/src/module-api.js +1 -1
  44. package/tests/account_linking.mjs +289 -0
  45. package/tests/account_logins_db.mjs +56 -0
  46. package/tests/autopickup_cap.mjs +203 -11
  47. package/tests/claims_batch_routes.mjs +79 -12
  48. package/tests/copy_desk_page_release.mjs +20 -0
  49. package/tests/copy_stuck_page_tweaks.mjs +2 -2
  50. package/tests/credit_log_no_spend_db.mjs +160 -0
  51. package/tests/effective_visibility_predicate.mjs +8 -0
  52. package/tests/hub_account_page.mjs +91 -5
  53. package/tests/project_settings_page.mjs +8 -5
@@ -0,0 +1,289 @@
1
+ // tests/account_linking.mjs — GitHub and Google as two ways into ONE account,
2
+ // linked and unlinked by the person (task 1004995, ADR 0393/0396).
3
+ //
4
+ // WHY. The owner's rules: a signed-in person can link the other provider and
5
+ // both open the same account; never remove the last way in; when emails match,
6
+ // suggest — never join; and an account that already exists separately is said
7
+ // plainly and never merged. And the ADR 0393 carry-over: once linking exists,
8
+ // every GitHub sign-in must find the person first, or a GitHub account linked to
9
+ // someone who joined with Google signs in as a second person.
10
+ // No database, no network: a recording fake pool, a stubbed fetch for GitHub,
11
+ // and the db-kernel functions stubbed before the files that destructure them load.
12
+ //
13
+ // Run: node --test tests/account_linking.mjs
14
+
15
+ import assert from 'node:assert/strict';
16
+ import { test, before, after } from 'node:test';
17
+ import http from 'node:http';
18
+ import { createRequire } from 'node:module';
19
+
20
+ const require = createRequire(import.meta.url);
21
+ const express = require('express');
22
+
23
+ process.env.BONGOS_GITHUB_CLIENT_ID = process.env.BONGOS_GITHUB_CLIENT_ID || 'gh-test-client';
24
+ process.env.BONGOS_GITHUB_CLIENT_SECRET = process.env.BONGOS_GITHUB_CLIENT_SECRET || 'gh-test-secret';
25
+ process.env.BONGOS_OPEN_XENOS_ENROLLMENT = '1';
26
+
27
+ function fakePool(script) {
28
+ const p = { log: [], script };
29
+ const run = async (sql, params = []) => {
30
+ p.log.push({ sql, params });
31
+ for (const [re, answer] of p.script) {
32
+ if (re.test(sql)) return typeof answer === 'function' ? answer(sql, params, p.log) : answer;
33
+ }
34
+ return { rows: [], rowCount: 0 };
35
+ };
36
+ p.query = run;
37
+ p.connect = async () => ({ query: run, release() {} });
38
+ return p;
39
+ }
40
+
41
+ // ── stubs, installed before anything destructures them ──
42
+ const kernel = require('../src/bongos/db-kernel.js');
43
+ const upserts = [];
44
+ kernel.getBuilderByGithubId = async () => null;
45
+ kernel.upsertBuilder = async (b) => { upserts.push(b); return { id: 9, github_id: String(b.githubId), github_login: b.githubLogin, status: 'active', rank: 'xenos' }; };
46
+ kernel.createSession = async () => ({ id: 1 });
47
+ const dbMod = require('../src/bongos/db.js');
48
+ dbMod.createSession = kernel.createSession;
49
+ const admission = require('../src/bongos/auth-admission.js');
50
+ admission.safeSyncRankRole = async () => {};
51
+ let ME = '-7';
52
+ const apiPath = require.resolve('../src/module-api.js');
53
+ const realApi = require(apiPath);
54
+ const routePool = fakePool([]);
55
+ require.cache[apiPath].exports = {
56
+ ...realApi,
57
+ pool: routePool,
58
+ requireBuilder: (req, _res, next) => { req.builder = { id: 1, github_id: ME, github_login: '~ana' }; next(); },
59
+ };
60
+ const seams = require('../src/module-seams.js');
61
+ const hub = { personKeyForGithub: async () => null, recordHubSignin: async () => {} };
62
+ if (!seams.hasProvider('platform-identity.hub')) seams.registerProvider('platform-identity.hub', hub);
63
+ const registered = seams.resolveOptional('platform-identity.hub');
64
+
65
+ const logins = require('../modules/platform-identity/account-logins.js');
66
+ const profileRoutes = require('../modules/platform-identity/routes/profile.js');
67
+ const { attachFail } = require('../src/bongos/middleware/error-envelope.js');
68
+ const { completeWebFlow } = require('../src/bongos/auth-github.js');
69
+ const { linkLanding } = require('../src/bongos/routes/auth-link.js');
70
+ const { renderExistingAccountHint } = require('../src/bongos/sign-in-pages.js');
71
+
72
+ const dupe = () => { const e = new Error('duplicate key'); e.code = '23505'; throw e; };
73
+
74
+ // ── 1. who a GitHub sign-in reaches ──────────────────────────────────────────
75
+
76
+ test('a GitHub id linked to someone who joined with Google reaches THEIR key; an unknown one reaches no one', async () => {
77
+ const pool = fakePool([[/FROM platform_identity_account_logins l/, (_s, params) => (params[1] === '555' ? { rows: [{ account_id: 3, person_key: '-7' }] } : { rows: [] })]]);
78
+ assert.equal(await logins.personKeyForGithub('555', { pool }), '-7');
79
+ assert.equal(await logins.personKeyForGithub('556', { pool }), null);
80
+ assert.equal(await logins.personKeyForGithub('-7', { pool }), null, 'a minted key is never a GitHub id');
81
+ });
82
+
83
+ test('the hub’s GitHub web sign-in signs a linked GitHub account in as the person, not a second account', async () => {
84
+ const realFetch = globalThis.fetch;
85
+ globalThis.fetch = async (url) => ({
86
+ ok: true,
87
+ json: async () => (String(url).includes('access_token') ? { access_token: 't', scope: '' } : { id: 555, login: 'ana-gh', name: 'Ana', avatar_url: null, email: 'ana@example.com' }),
88
+ });
89
+ const asked = [];
90
+ const signins = [];
91
+ registered.personKeyForGithub = async (id) => { asked.push(id); return id === '555' ? '-7' : null; };
92
+ registered.recordHubSignin = async (r) => { signins.push(r); };
93
+ upserts.length = 0;
94
+ try {
95
+ await completeWebFlow({ code: 'c', redirectUri: 'https://hub.example/cb' });
96
+ } finally { globalThis.fetch = realFetch; }
97
+ assert.deepEqual(asked, ['555'], 'the hub is asked who the GitHub id reaches, first');
98
+ assert.equal(upserts[0].githubId, '-7', 'the builder row is the person’s, keyed on their minted key');
99
+ assert.equal(upserts[0].githubLogin, 'ana-gh', 'with the real GitHub login, now that GitHub is linked');
100
+ assert.equal(signins[0].githubId, '-7', 'the hub account touched is the person’s');
101
+ assert.equal(signins[0].githubUserId, '555', 'and the GitHub way in itself is stamped as used');
102
+ });
103
+
104
+ test('with no hub (any other instance) the GitHub id is the key, exactly as before', async () => {
105
+ const realFetch = globalThis.fetch;
106
+ globalThis.fetch = async (url) => ({ ok: true, json: async () => (String(url).includes('access_token') ? { access_token: 't' } : { id: 42, login: 'octo' }) });
107
+ const saved = registered.personKeyForGithub;
108
+ delete registered.personKeyForGithub;
109
+ upserts.length = 0;
110
+ try { await completeWebFlow({ code: 'c', redirectUri: 'https://x.example/cb' }); } finally { globalThis.fetch = realFetch; registered.personKeyForGithub = saved; }
111
+ assert.equal(upserts[0].githubId, '42');
112
+ });
113
+
114
+ // ── 2. linking — never a merge ───────────────────────────────────────────────
115
+
116
+ const ownedBy = (key) => [/FROM platform_identity_account_logins l\s+JOIN/, key ? { rows: [{ account_id: 1, person_key: key }] } : { rows: [] }];
117
+
118
+ test('a way in that already reaches ANOTHER person is refused as taken, and nothing is written', async () => {
119
+ const pool = fakePool([ownedBy('99')]);
120
+ assert.deepEqual(await logins.linkLogin({ personKey: '-7', provider: 'github', subject: '555', githubLogin: 'x' }, { pool }), { refused: 'taken' });
121
+ assert.equal(pool.log.filter((q) => /INSERT|UPDATE|DELETE/.test(q.sql)).length, 0);
122
+ });
123
+
124
+ test('linking what is already yours is a no-op success', async () => {
125
+ const pool = fakePool([ownedBy('-7')]);
126
+ assert.deepEqual(await logins.linkLogin({ personKey: '-7', provider: 'google', subject: 'g-1' }, { pool }), { linked: true, already: true });
127
+ });
128
+
129
+ test('linking GitHub adds the way in and writes the real login on the account', async () => {
130
+ const pool = fakePool([ownedBy(null), [/SELECT id FROM platform_identity_accounts WHERE github_id/, { rows: [{ id: 4 }] }]]);
131
+ assert.deepEqual(await logins.linkLogin({ personKey: '-7', provider: 'github', subject: '555', email: 'ana@example.com', githubLogin: 'ana-gh' }, { pool }), { linked: true, already: false });
132
+ const ins = pool.log.find((q) => /INSERT INTO platform_identity_account_logins/.test(q.sql));
133
+ assert.deepEqual(ins.params, [4, 'github', '555', 'ana@example.com']);
134
+ const upd = pool.log.find((q) => /UPDATE platform_identity_accounts SET github_login/.test(q.sql));
135
+ assert.deepEqual(upd.params, [4, 'ana-gh']);
136
+ });
137
+
138
+ test('linking Google writes no GitHub login', async () => {
139
+ const pool = fakePool([ownedBy(null), [/SELECT id FROM platform_identity_accounts WHERE github_id/, { rows: [{ id: 4 }] }]]);
140
+ await logins.linkLogin({ personKey: '42', provider: 'google', subject: 'g-1' }, { pool });
141
+ assert.equal(pool.log.filter((q) => /github_login/.test(q.sql) && /UPDATE/.test(q.sql)).length, 0);
142
+ });
143
+
144
+ test('a race: someone else took it a moment ago → taken; you already hold that provider → already_linked', async () => {
145
+ let n = 0;
146
+ const raced = fakePool([
147
+ [/FROM platform_identity_account_logins l\s+JOIN/, () => (n++ === 0 ? { rows: [] } : { rows: [{ account_id: 2, person_key: '99' }] })],
148
+ [/SELECT id FROM platform_identity_accounts WHERE github_id/, { rows: [{ id: 4 }] }],
149
+ [/INSERT INTO platform_identity_account_logins/, dupe],
150
+ ]);
151
+ assert.deepEqual(await logins.linkLogin({ personKey: '-7', provider: 'google', subject: 'g-1' }, { pool: raced }), { refused: 'taken' });
152
+ const held = fakePool([ownedBy(null), [/SELECT id FROM platform_identity_accounts WHERE github_id/, { rows: [{ id: 4 }] }], [/INSERT INTO platform_identity_account_logins/, dupe]]);
153
+ assert.deepEqual(await logins.linkLogin({ personKey: '-7', provider: 'google', subject: 'g-2' }, { pool: held }), { refused: 'already_linked' });
154
+ });
155
+
156
+ // ── 3. unlinking — never the last way in ─────────────────────────────────────
157
+
158
+ test('the refusal rule: never the last way in; never GitHub from an account born with it', () => {
159
+ assert.equal(logins.unlinkRefusal({ personKey: '-7', provider: 'google', count: 1 }), 'last_way_in');
160
+ assert.equal(logins.unlinkRefusal({ personKey: '-7', provider: 'github', count: 2 }), null, 'a Google-born person may drop GitHub');
161
+ assert.equal(logins.unlinkRefusal({ personKey: '-7', provider: 'google', count: 2 }), null);
162
+ assert.equal(logins.unlinkRefusal({ personKey: '42', provider: 'github', count: 2 }), 'born_with', 'its key IS its GitHub id');
163
+ assert.equal(logins.unlinkRefusal({ personKey: '42', provider: 'google', count: 2 }), null);
164
+ });
165
+
166
+ const held = (...providers) => [/FOR UPDATE OF l/, { rows: providers.map((provider, i) => ({ id: 10 + i, provider, account_id: 4 })) }];
167
+
168
+ test('unlink counts and deletes under one lock, and clears the GitHub login with GitHub', async () => {
169
+ const pool = fakePool([held('github', 'google')]);
170
+ assert.deepEqual(await logins.unlinkLogin({ personKey: '-7', provider: 'github' }, { pool }), { unlinked: true });
171
+ assert.ok(pool.log.some((q) => /BEGIN/i.test(q.sql)), 'inside a transaction');
172
+ assert.deepEqual(pool.log.find((q) => /DELETE FROM platform_identity_account_logins/.test(q.sql)).params, [10]);
173
+ assert.deepEqual(pool.log.find((q) => /SET github_login = NULL/.test(q.sql)).params, [4]);
174
+ });
175
+
176
+ test('unlink refuses the last way in, a GitHub-born account’s GitHub, and one not linked — deleting nothing', async () => {
177
+ for (const [key, provider, rows, want] of [
178
+ ['-7', 'google', ['google'], 'last_way_in'],
179
+ ['42', 'github', ['github', 'google'], 'born_with'],
180
+ ['-7', 'github', ['google'], 'not_linked'],
181
+ ]) {
182
+ const pool = fakePool([held(...rows)]);
183
+ assert.deepEqual(await logins.unlinkLogin({ personKey: key, provider }, { pool }), { refused: want }, `${key} ${provider}`);
184
+ assert.equal(pool.log.filter((q) => /^\s*(DELETE|UPDATE)/.test(q.sql)).length, 0);
185
+ }
186
+ });
187
+
188
+ // ── 4. a matching email suggests, never joins ────────────────────────────────
189
+
190
+ test('the first-sign-in hint names providers only, and only while the identity reaches no one', async () => {
191
+ const pool = fakePool([ownedBy(null), [/SELECT DISTINCT provider/, { rows: [{ provider: 'github' }] }]]);
192
+ assert.deepEqual(await logins.existingAccountHint({ provider: 'google', subject: 'g-1', email: 'Ana@Example.com' }, { pool }), ['github']);
193
+ const q = pool.log.find((x) => /SELECT DISTINCT provider/.test(x.sql));
194
+ assert.match(q.sql, /provider <> \$1 AND lower\(email\) = lower\(\$2\)/);
195
+ assert.doesNotMatch(q.sql, /github_id|handle|account_id|SELECT[^F]*email/, 'it reads back no key, handle or address');
196
+ const known = fakePool([ownedBy('-7')]);
197
+ assert.deepEqual(await logins.existingAccountHint({ provider: 'google', subject: 'g-1', email: 'a@b.c' }, { pool: known }), [], 'a returning person is never stopped');
198
+ assert.deepEqual(await logins.existingAccountHint({ provider: 'google', subject: 'g-1', email: null }, { pool }), []);
199
+ });
200
+
201
+ test('the hint page offers the existing account or a new one, joins nothing and names no one', () => {
202
+ const html = renderExistingAccountHint({ githubHref: '/api/bongos/auth/web/start?via=github&return=%2Faccount%23aWaysIn', newAccountHref: '/api/bongos/auth/google/start?fresh=1' });
203
+ assert.match(html, /Sign in with GitHub/);
204
+ assert.match(html, /Make a new account with Google/);
205
+ assert.match(html, /href="\/api\/bongos\/auth\/google\/start\?fresh=1"/);
206
+ assert.match(html, /We never join accounts on our own, even when the emails match\./);
207
+ });
208
+
209
+ test('every link answer lands on the account page’s ways section', () => {
210
+ assert.equal(linkLanding('github', { linked: true }), '/account?linked=github#aWaysIn');
211
+ assert.equal(linkLanding('google', { refused: 'taken' }), '/account?link_refused=taken&provider=google#aWaysIn');
212
+ assert.equal(linkLanding('google', null), '/account?link_refused=failed&provider=google#aWaysIn');
213
+ });
214
+
215
+ // ── 5. the own-scoped routes ─────────────────────────────────────────────────
216
+
217
+ let server; let port;
218
+ before(async () => {
219
+ const app = express();
220
+ app.use(express.json());
221
+ app.use(attachFail);
222
+ app.use('/api/bongos', profileRoutes());
223
+ server = http.createServer(app);
224
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
225
+ port = server.address().port;
226
+ });
227
+ after(() => server.close());
228
+ const call = (method, path) => new Promise((resolve, reject) => {
229
+ const r = http.request({ host: '127.0.0.1', port, path, method }, (resp) => {
230
+ let data = ''; resp.on('data', (c) => { data += c; }); resp.on('end', () => resolve({ status: resp.statusCode, body: data ? JSON.parse(data) : null }));
231
+ });
232
+ r.on('error', reject); r.end();
233
+ });
234
+
235
+ test('GET /me/sign-in-methods says, per way in, why it cannot be removed', async () => {
236
+ ME = '-7';
237
+ routePool.script = [[/FROM platform_identity_account_logins l\s+JOIN platform_identity_accounts a ON a.id = l.account_id\s+WHERE a.github_id/, { rows: [{ provider: 'google', email: 'ana@example.com' }] }]];
238
+ const res = await call('GET', '/api/bongos/me/sign-in-methods');
239
+ assert.equal(res.status, 200);
240
+ assert.deepEqual(res.body.methods, [{ provider: 'google', email: 'ana@example.com', unlink_refused: 'last_way_in' }]);
241
+ });
242
+
243
+ test('DELETE /me/sign-in-methods/:provider removes one, keyed on the session, and refuses in plain words', async () => {
244
+ ME = '-7';
245
+ routePool.script = [held('github', 'google')];
246
+ routePool.log.length = 0;
247
+ assert.equal((await call('DELETE', '/api/bongos/me/sign-in-methods/google')).status, 200);
248
+ assert.deepEqual(routePool.log.find((q) => /FOR UPDATE/.test(q.sql)).params, ['-7'], 'the person is the session’s, never a parameter');
249
+ routePool.script = [held('google')];
250
+ const last = await call('DELETE', '/api/bongos/me/sign-in-methods/google');
251
+ assert.equal(last.status, 409);
252
+ assert.equal(last.body.error.code, 'last_way_in');
253
+ assert.equal((await call('DELETE', '/api/bongos/me/sign-in-methods/discord')).status, 404, 'only the known providers');
254
+ });
255
+
256
+ // ── 6. Link GitHub, end to end through its callback ──────────────────────────
257
+
258
+ test('Link GitHub: a GitHub account that already has its own account here is refused, never merged', async () => {
259
+ const auth = require('../src/bongos/auth.js');
260
+ const buildAuthLinkRouter = require('../src/bongos/routes/auth-link.js');
261
+ const linked = [];
262
+ registered.linkLogin = async (r) => { linked.push(r); return { linked: true, already: false }; };
263
+ const realSession = auth.resolveSession;
264
+ auth.resolveSession = async () => ({ github_id: '-7', display_name: 'Ana', status: 'active' });
265
+ const realFetch = globalThis.fetch;
266
+ globalThis.fetch = async (url) => ({ ok: true, json: async () => (String(url).includes('access_token') ? { access_token: 't' } : { id: 555, login: 'ana-gh' }) });
267
+ const realGet = dbMod.getBuilderByGithubId;
268
+ const app = express();
269
+ app.use(buildAuthLinkRouter());
270
+ const srv = http.createServer(app);
271
+ await new Promise((r) => srv.listen(0, '127.0.0.1', r));
272
+ const hit = () => new Promise((resolve, reject) => {
273
+ http.get({ host: '127.0.0.1', port: srv.address().port, path: '/auth/web/callback/link?state=s1&code=c', headers: { cookie: 'bongos_link_state=s1' } },
274
+ (resp) => { resp.resume(); resolve(resp.headers.location); }).on('error', reject);
275
+ });
276
+ try {
277
+ dbMod.getBuilderByGithubId = async (id) => (id === '555' ? { id: 3 } : null);
278
+ assert.equal(await hit(), '/account?link_refused=taken&provider=github#aWaysIn');
279
+ assert.equal(linked.length, 0, 'the hub was never asked to link it');
280
+ dbMod.getBuilderByGithubId = async () => null;
281
+ upserts.length = 0;
282
+ assert.equal(await hit(), '/account?linked=github#aWaysIn');
283
+ assert.deepEqual(linked[0], { personKey: '-7', provider: 'github', subject: '555', email: null, githubLogin: 'ana-gh' });
284
+ assert.equal(upserts[0].githubId, '-7');
285
+ assert.equal(upserts[0].githubLogin, 'ana-gh', 'the hall shows the real login from now on');
286
+ } finally {
287
+ auth.resolveSession = realSession; globalThis.fetch = realFetch; dbMod.getBuilderByGithubId = realGet; srv.close();
288
+ }
289
+ });
@@ -154,6 +154,62 @@ try {
154
154
  const after = await accountRow(first.personKey);
155
155
  same([after.github_login, after.profile_state], [null, 'active'], 'the hub sign-in activates the person and writes no login');
156
156
 
157
+ // 9 — linking and removing ways in (task 1004995), against the real constraints
158
+ // and real row locks, which a fake pool cannot execute.
159
+ await q(migrationSql('platform_identity_035_account_login_email_idx.sql'));
160
+ await q(migrationSql('platform_identity_035_account_login_email_idx.sql'));
161
+ ok((await q(`SELECT 1 FROM pg_indexes WHERE indexname = 'platform_identity_account_logins_lower_email_idx'`)).rows.length === 1,
162
+ 'the address index exists, and its migration re-runs safely');
163
+
164
+ const GH_LINK = '90499203'; // a GitHub id nobody holds yet
165
+ const ana = await logins.signInWithLogin({ provider: 'google', subject: SUB('ana'), email: 'ana@example.com', displayName: 'Ana' }, { pool });
166
+ const bo = await logins.signInWithLogin({ provider: 'google', subject: SUB('bo'), email: 'bo@example.com', displayName: 'Bo' }, { pool });
167
+
168
+ // Two people link the same GitHub account at once: the UNIQUE (provider, subject)
169
+ // decides, so exactly one gets it and the other is told it is taken.
170
+ const racedLinks = await Promise.all([
171
+ logins.linkLogin({ personKey: ana.personKey, provider: 'github', subject: GH_LINK, githubLogin: 'ana-gh' }, { pool }),
172
+ logins.linkLogin({ personKey: bo.personKey, provider: 'github', subject: GH_LINK, githubLogin: 'ana-gh' }, { pool }),
173
+ ]);
174
+ same(racedLinks.map((r) => (r.linked ? 'linked' : r.refused)).sort(), ['linked', 'taken'], 'two people racing for one GitHub account: one links, one is refused, nothing merges');
175
+ const winner = racedLinks[0].linked ? ana : bo;
176
+ const loser = racedLinks[0].linked ? bo : ana;
177
+ same((await accountRow(winner.personKey)).github_login, 'ana-gh', 'the winner’s account now shows the real GitHub login');
178
+ same((await accountRow(loser.personKey)).github_login, null, 'the other account is untouched');
179
+ same(await logins.personKeyForGithub(GH_LINK, { pool }), winner.personKey, 'a GitHub sign-in with that id now reaches the winner');
180
+ same(await logins.linkLogin({ personKey: loser.personKey, provider: 'github', subject: GH_LINK, githubLogin: 'x' }, { pool }), { refused: 'taken' },
181
+ 'linking it again later is still refused');
182
+ same(await logins.linkLogin({ personKey: winner.personKey, provider: 'github', subject: '90499204', githubLogin: 'y' }, { pool }), { refused: 'already_linked' },
183
+ 'a person holds one GitHub way in; a second is refused by the database');
184
+
185
+ // Two removals at once on a person with two ways in: the row lock serialises
186
+ // them, so exactly one goes and the other finds it would be the last.
187
+ const removed = await Promise.all([
188
+ logins.unlinkLogin({ personKey: winner.personKey, provider: 'google' }, { pool }),
189
+ logins.unlinkLogin({ personKey: winner.personKey, provider: 'github' }, { pool }),
190
+ ]);
191
+ same(removed.filter((r) => r.unlinked).length, 1, 'two racing removals: exactly one goes through');
192
+ same(removed.filter((r) => r.refused === 'last_way_in').length, 1, 'the other is refused as the last way in');
193
+ same((await logins.listLoginsForPerson(winner.personKey, { pool })).length, 1, 'the person keeps one way in');
194
+
195
+ // GitHub never comes off an account born with it (its key IS its GitHub id).
196
+ same(await logins.unlinkLogin({ personKey: String(GH), provider: 'github' }, { pool }), { refused: 'born_with' }, 'a GitHub-born account keeps GitHub');
197
+ same((await logins.listLoginsForPerson(String(GH), { pool })).map((m) => m.provider), ['github', 'google'], 'and nothing was deleted');
198
+
199
+ // A GitHub way in removed from a person who joined with Google clears the login.
200
+ const cy = await logins.signInWithLogin({ provider: 'google', subject: SUB('cy'), email: 'cy@example.com', displayName: 'Cy' }, { pool });
201
+ await logins.linkLogin({ personKey: cy.personKey, provider: 'github', subject: '90499205', githubLogin: 'cy-gh' }, { pool });
202
+ same(await logins.unlinkLogin({ personKey: cy.personKey, provider: 'github' }, { pool }), { unlinked: true }, 'a linked GitHub comes off a Google-born person');
203
+ same([(await accountRow(cy.personKey)).github_login, await logins.personKeyForGithub('90499205', { pool })], [null, null],
204
+ 'their login is cleared and that GitHub id reaches no one again');
205
+
206
+ // The first-sign-in hint: the address another way in shows, provider names only.
207
+ await logins.touchGithubLogin({ githubId: String(GH), email: 'Octo-GH@Example.com' }, { pool });
208
+ same(await logins.existingAccountHint({ provider: 'google', subject: SUB('newcomer'), email: 'octo-gh@example.com' }, { pool }), ['github'],
209
+ 'a new Google identity with a GitHub way in’s address (any case) is offered GitHub');
210
+ same(await logins.existingAccountHint({ provider: 'google', subject: SUB('octo'), email: 'octo-gh@example.com' }, { pool }), [],
211
+ 'a Google identity that already reaches someone is never stopped');
212
+
157
213
  console.log(`\naccount_logins_db.mjs: ${pass} passed`);
158
214
  } finally {
159
215
  await cleanup();
@@ -2,7 +2,8 @@
2
2
  // (task 1004677 / BV2.TW19a, ADR 0371 D3, D5, D6).
3
3
  //
4
4
  // Pinned here (DB-free; the race lives in tests/autopickup_cap_db.mjs):
5
- // 1. the two parsers and the resolver: off by default, cap 20 by default, an
5
+ // 1. the parsers and the resolver: off by default, cap 200 by default (task
6
+ // 1005003; it was 20), per-rank caps read from one JSON row, an
6
7
  // unusable stored value reported and never thrown, a dead DB answers defaults;
7
8
  // 2. the refusal ladder: not a tweak, switch off, round limit, monthly cap, and the
8
9
  // lock is taken BEFORE either count;
@@ -35,7 +36,12 @@ async function withPool(query, fn) {
35
36
  pool.query = query;
36
37
  try { return await fn(); } finally { pool.query = saved; }
37
38
  }
38
- const settingsRows = (map) => async (_sql, [key]) => ({ rows: key in map ? [{ key, value: map[key] }] : [] });
39
+ // Answers both the single-key read (getSetting) and the one-query batch read
40
+ // (key = ANY($1)) that resolveTweakAutopickup makes.
41
+ const settingsRows = (map) => async (_sql, [key]) => {
42
+ const keys = Array.isArray(key) ? key : [key];
43
+ return { rows: keys.filter((k) => k in map).map((k) => ({ key: k, value: map[k] })) };
44
+ };
39
45
 
40
46
  // ---- 1. the setting ---------------------------------------------------------
41
47
 
@@ -50,11 +56,11 @@ test('the parsers accept exactly off|on and a whole positive cap', () => {
50
56
  assert.match(parseAutopickupCap('100000').reason, /out of range/);
51
57
  });
52
58
 
53
- test('an untouched project is off with a cap of 20', async () => {
59
+ test('an untouched project is off with a cap of 200 and no rank caps', async () => {
54
60
  assert.equal(DEFAULT_AUTOPICKUP, 'off');
55
- assert.equal(DEFAULT_AUTOPICKUP_CAP, 20);
61
+ assert.equal(DEFAULT_AUTOPICKUP_CAP, 200);
56
62
  const r = await withPool(settingsRows({}), () => resolveTweakAutopickup());
57
- assert.deepEqual(r, { mode: 'off', cap: 20, source: { mode: 'default', cap: 'default' }, invalid: [] });
63
+ assert.deepEqual(r, { mode: 'off', cap: 200, rank_caps: {}, source: { mode: 'default', cap: 'default' }, invalid: [] });
58
64
  assert.match(describeTweakAutopickup(r), /waits until a person/);
59
65
  });
60
66
 
@@ -63,7 +69,7 @@ test('stored values are read; an unusable one is reported and falls back', async
63
69
  () => resolveTweakAutopickup());
64
70
  assert.equal(r.mode, 'on');
65
71
  assert.equal(r.source.mode, 'project_settings');
66
- assert.equal(r.cap, 20);
72
+ assert.equal(r.cap, 200);
67
73
  assert.equal(r.invalid.length, 1);
68
74
  assert.equal(r.invalid[0].raw, 'lots');
69
75
  assert.match(describeTweakAutopickup({ mode: 'on', cap: 7 }), /up to 7 a month/);
@@ -72,7 +78,7 @@ test('stored values are read; an unusable one is reported and falls back', async
72
78
  test('a database that cannot be read answers the defaults', async () => {
73
79
  const r = await withPool(async () => { throw new Error('db down'); }, () => resolveTweakAutopickup());
74
80
  assert.equal(r.mode, 'off');
75
- assert.equal(r.cap, 20);
81
+ assert.equal(r.cap, 200);
76
82
  });
77
83
 
78
84
  // ---- 2. the refusal ladder --------------------------------------------------
@@ -128,7 +134,7 @@ test('the monthly cap refuses at the cap and admits below it', async () => {
128
134
  test('claimTask runs the gate before the insert, and names the column only on a marked claim', () => {
129
135
  const src = fs.readFileSync(path.join(ROOT, 'modules', 'lifecycle', 'db-claims.js'), 'utf8');
130
136
  const body = src.slice(src.indexOf('async function claimTask('), src.indexOf('async function claimTasksBatch'));
131
- const gate = body.indexOf('autoPickupRefusal(client, task, autoPickupSettings)');
137
+ const gate = body.indexOf('autoPickupRefusal(client, task, autoPickupSettings, builderRank)');
132
138
  const insert = body.indexOf('INSERT INTO claims');
133
139
  assert.ok(gate > 0 && insert > gate, 'the gate runs inside the transaction, before the insert');
134
140
  assert.match(body.slice(gate, insert), /if \(refusal\) throw refusal;/, 'a refusal stops the claim');
@@ -155,15 +161,19 @@ const fakeRes = () => ({
155
161
  json(p) { this.payload = p; return this; },
156
162
  });
157
163
 
158
- function buildRouter({ used = 4 } = {}) {
164
+ function buildRouter({ used = 4, rankCaps = {} } = {}) {
159
165
  const ps = api.projectSettings;
160
166
  const saved = { resolve: ps.resolveTweakAutopickup, set: ps.set };
161
167
  const writes = [];
162
- const state = { mode: 'off', cap: 20 };
168
+ const state = { mode: 'off', cap: 20, rank_caps: { ...rankCaps } };
163
169
  ps.resolveTweakAutopickup = async () => ({ ...state, source: { mode: 'default', cap: 'default' }, invalid: [] });
164
170
  ps.set = async (key, value, by) => {
165
171
  writes.push({ key, value, by });
166
- if (key === 'tweak.autopickup') state.mode = value; else state.cap = value;
172
+ if (key === 'tweak.autopickup') state.mode = value;
173
+ else if (key.startsWith('tweak.autopickup_rank_cap.')) {
174
+ const rank = key.slice('tweak.autopickup_rank_cap.'.length);
175
+ if (value === '') delete state.rank_caps[rank]; else state.rank_caps[rank] = value;
176
+ } else state.cap = value;
167
177
  };
168
178
  const autopickup = require('../modules/lifecycle/autopickup.js');
169
179
  const savedCount = autopickup.countThisMonth;
@@ -234,3 +244,185 @@ test('core_275 is additive: one nullable column, recorded in schema_migrations',
234
244
  assert.doesNotMatch(sql, /NOT NULL|DROP /);
235
245
  assert.match(sql, /INSERT INTO schema_migrations \(version\) VALUES \('core_275_claims_auto_pickup'\)/);
236
246
  });
247
+
248
+ // ---- 5. the cap per project and per builder rank (task 1005003) ------------
249
+
250
+ const { rankCapKey } = require('../src/bongos/project-settings.js');
251
+ const { effectiveCap } = require('../modules/lifecycle/autopickup.js');
252
+ const seams = require(path.join(ROOT, 'src', 'module-seams.js'));
253
+ const { attachFail } = require(path.join(ROOT, 'src', 'bongos', 'middleware', 'error-envelope.js'));
254
+
255
+ test('a project override and a rank override are both read, in ONE query', async () => {
256
+ assert.equal(rankCapKey('xenos'), 'tweak.autopickup_rank_cap.xenos');
257
+ let queries = 0;
258
+ const rows = settingsRows({
259
+ [SETTING_KEYS.TWEAK_AUTOPICKUP]: 'on',
260
+ [SETTING_KEYS.TWEAK_AUTOPICKUP_CAP]: '40',
261
+ 'tweak.autopickup_rank_cap.xenos': '5',
262
+ 'tweak.autopickup_rank_cap.archon': '80',
263
+ 'tweak.autopickup_rank_cap.metic': '', // cleared: follows the project cap
264
+ 'tweak.autopickup_rank_cap.olympian': '9', // off the live ladder: never read
265
+ });
266
+ const r = await withPool(async (sql, params) => { queries += 1; return rows(sql, params); }, () => resolveTweakAutopickup());
267
+ assert.equal(queries, 1, 'mode, cap and every rank cap come back in one round trip');
268
+ assert.equal(r.cap, 40);
269
+ assert.deepEqual(r.rank_caps, { xenos: 5, archon: 80 });
270
+ assert.deepEqual(r.invalid, []);
271
+ assert.equal(describeTweakAutopickup(r),
272
+ 'On: a running Autobongos runner applies submitted pages on its own, up to 40 a month. Some builder ranks have their own limit: xenos 5, archon 80. The artist still approves every one.');
273
+
274
+ const bad = await withPool(settingsRows({ 'tweak.autopickup_rank_cap.xenos': '-1' }), () => resolveTweakAutopickup());
275
+ assert.deepEqual(bad.rank_caps, {}, 'an unusable rank row falls back to the project cap');
276
+ assert.equal(bad.invalid.length, 1);
277
+ assert.equal(bad.invalid[0].where, "project_settings['tweak.autopickup_rank_cap.xenos']");
278
+ });
279
+
280
+ test('the effective cap is the rank\'s own cap, else the project cap', () => {
281
+ const s = { mode: 'on', cap: 200, rank_caps: { xenos: 5 } };
282
+ assert.deepEqual(effectiveCap(s, 'xenos'), { cap: 5, from: 'rank' });
283
+ assert.deepEqual(effectiveCap(s, 'metic'), { cap: 200, from: 'project' });
284
+ assert.deepEqual(effectiveCap(s, null), { cap: 200, from: 'project' });
285
+ assert.deepEqual(effectiveCap({ cap: 200 }, 'xenos'), { cap: 200, from: 'project' }, 'no rank caps at all');
286
+ });
287
+
288
+ test('the default cap of 200 admits round 199 and refuses at 200', async () => {
289
+ const s = { mode: 'on', cap: DEFAULT_AUTOPICKUP_CAP, rank_caps: {} };
290
+ assert.equal(await autoPickupRefusal(fakeClient({ month: 199 }), tweak, s, 'metic'), null);
291
+ const r = await autoPickupRefusal(fakeClient({ month: 200 }), tweak, s, 'metic');
292
+ assert.equal(r.code, 'AUTO_PICKUP_CAP_REACHED');
293
+ assert.equal(r.cap, 200);
294
+ assert.equal(r.cap_from, 'project');
295
+ assert.equal(r.message, 'Auto-pickup has used this month\'s 200 rounds, so submitted pages wait for a person until next month.');
296
+ });
297
+
298
+ test('a rank override replaces the project cap for that rank only, both ways', async () => {
299
+ const s = { mode: 'on', cap: 50, rank_caps: { xenos: 10, archon: 80 } };
300
+ // lower than the project cap: refuses a xenos runner where a metic one is admitted
301
+ const lower = await autoPickupRefusal(fakeClient({ month: 10 }), tweak, s, 'xenos');
302
+ assert.equal(lower.code, 'AUTO_PICKUP_CAP_REACHED');
303
+ assert.equal(lower.cap, 10);
304
+ assert.equal(lower.cap_from, 'rank');
305
+ assert.match(lower.message, /reached 10, the limit this project sets for a xenos builder's runner, so submitted pages wait for a person/);
306
+ assert.equal(await autoPickupRefusal(fakeClient({ month: 10 }), tweak, s, 'metic'), null);
307
+ // higher than the project cap: admits an archon runner past the project's number
308
+ assert.equal(await autoPickupRefusal(fakeClient({ month: 60 }), tweak, s, 'archon'), null);
309
+ assert.equal((await autoPickupRefusal(fakeClient({ month: 60 }), tweak, s, 'metic')).code, 'AUTO_PICKUP_CAP_REACHED');
310
+ });
311
+
312
+ test('claimTask passes the claimer\'s rank, read inside the transaction, to the gate', () => {
313
+ const src = fs.readFileSync(path.join(ROOT, 'modules', 'lifecycle', 'db-claims.js'), 'utf8');
314
+ const body = src.slice(src.indexOf('async function claimTask('), src.indexOf('async function claimTasksBatch'));
315
+ const rankRead = body.indexOf('const builderRank = builderRows[0] ? builderRows[0].rank : null;');
316
+ const gate = body.indexOf('autoPickupRefusal(client, task, autoPickupSettings, builderRank)');
317
+ assert.ok(rankRead > 0 && gate > rankRead);
318
+ });
319
+
320
+ test('the read reports the caller\'s own cap and what is left of it', async () => {
321
+ const { route, restore } = buildRouter({ used: 4, rankCaps: { xenos: 6 } });
322
+ try {
323
+ const get = handler(route('get', '/project-settings/tweak-autopickup'));
324
+ const x = fakeRes();
325
+ await get({ builder: { id: 1, rank: 'xenos' } }, x);
326
+ assert.deepEqual([x.payload.my_cap, x.payload.my_cap_from, x.payload.remaining_this_month], [6, 'rank', 2]);
327
+ assert.deepEqual(x.payload.rank_caps, { xenos: 6 });
328
+ const m = fakeRes();
329
+ await get({ builder: { id: 2, rank: 'metic' } }, m);
330
+ assert.deepEqual([m.payload.my_cap, m.payload.my_cap_from, m.payload.remaining_this_month], [20, 'project', 16]);
331
+ } finally { restore(); }
332
+ });
333
+
334
+ test('rank_caps is a partial update: a number sets, null clears, an unnamed rank is kept', async () => {
335
+ const { route, writes, restore } = buildRouter({ rankCaps: { xenos: 5, thetes: 9 } });
336
+ try {
337
+ const patch = handler(route('patch', '/project-settings/tweak-autopickup'));
338
+ const res = fakeRes();
339
+ await patch({ body: { rank_caps: { metic: 30, xenos: null } }, builder: { id: 7, rank: 'metic' } }, res);
340
+ assert.equal(res.code, null);
341
+ // One single-row upsert per named rank — never a read-modify-write of a shared
342
+ // object, so it cannot overwrite a rank someone else is editing at the same time.
343
+ assert.deepEqual(writes, [
344
+ { key: 'tweak.autopickup_rank_cap.metic', value: 30, by: 7 },
345
+ { key: 'tweak.autopickup_rank_cap.xenos', value: '', by: 7 },
346
+ ]);
347
+ assert.deepEqual(res.payload.rank_caps, { thetes: 9, metic: 30 });
348
+ assert.equal(res.payload.my_cap, 30);
349
+ } finally { restore(); }
350
+ });
351
+
352
+ test('two people saving two different ranks at once both keep their edit', async () => {
353
+ const { route, restore } = buildRouter();
354
+ try {
355
+ const patch = handler(route('patch', '/project-settings/tweak-autopickup'));
356
+ const a = fakeRes();
357
+ const b = fakeRes();
358
+ await Promise.all([
359
+ patch({ body: { rank_caps: { xenos: 5 } }, builder: { id: 7 } }, a),
360
+ patch({ body: { rank_caps: { archon: 80 } }, builder: { id: 8 } }, b),
361
+ ]);
362
+ const after = fakeRes();
363
+ await handler(route('get', '/project-settings/tweak-autopickup'))({ builder: { id: 9, rank: 'metic' } }, after);
364
+ assert.deepEqual(after.payload.rank_caps, { xenos: 5, archon: 80 });
365
+ } finally { restore(); }
366
+ });
367
+
368
+ test('an unknown rank or a bad rank number writes nothing, the project cap included', async () => {
369
+ const { route, writes, restore } = buildRouter();
370
+ try {
371
+ const patch = handler(route('patch', '/project-settings/tweak-autopickup'));
372
+ const unknown = fakeRes();
373
+ await patch({ body: { cap: 100, rank_caps: { olympian: 5 } }, builder: { id: 7 } }, unknown);
374
+ assert.equal(unknown.code, 'bad_tweak_autopickup');
375
+ assert.match(unknown.payload.message, /unknown rank 'olympian'/);
376
+ const zero = fakeRes();
377
+ await patch({ body: { cap: 100, rank_caps: { xenos: 0 } }, builder: { id: 7 } }, zero);
378
+ assert.match(zero.payload.message, /rank_caps\.xenos: must be positive/);
379
+ assert.equal(writes.length, 0);
380
+ } finally { restore(); }
381
+ });
382
+
383
+ // The server's permission check on the write, run for real: the route's own
384
+ // requirePermission layer, against a stub government port (the
385
+ // tests/government_require_permission.mjs double). Whoever holds
386
+ // project.settings.manage — the project owner, or anyone granted it — passes; a
387
+ // builder without it is refused with 403 before the handler runs.
388
+ async function runWriteGate(heldKeys) {
389
+ const { route, restore } = buildRouter();
390
+ try {
391
+ const stack = route('patch', '/project-settings/tweak-autopickup').stack;
392
+ const gate = stack[1].handle;
393
+ assert.equal(gate.name, 'permissionGate', 'the second layer is the kernel permission gate');
394
+ seams._reset();
395
+ seams.registerProvider('government', { resolveBuilderPermissions: async () => heldKeys });
396
+ const res = { _status: null, _json: null, status(c) { this._status = c; return this; }, json(b) { this._json = b; return this; } };
397
+ attachFail({}, res, () => {});
398
+ let passed = false;
399
+ await gate({ builder: { id: 7, rank: 'metic' }, body: { rank_caps: { xenos: 5 } } }, res, () => { passed = true; });
400
+ return { passed, res };
401
+ } finally { seams._reset(); restore(); }
402
+ }
403
+
404
+ test('a builder holding project.settings.manage may set the caps', async () => {
405
+ const { passed, res } = await runWriteGate(['project.settings.manage']);
406
+ assert.equal(passed, true);
407
+ assert.equal(res._status, null);
408
+ });
409
+
410
+ test('a builder without project.settings.manage is refused', async () => {
411
+ const { passed, res } = await runWriteGate(['idea.triage']);
412
+ assert.equal(passed, false);
413
+ assert.equal(res._status, 403);
414
+ assert.equal(res._json.error.code, 'permission_forbidden');
415
+ assert.deepEqual(res._json.error.details.required, ['project.settings.manage']);
416
+ });
417
+
418
+ test('the settings page row offers the project cap and one box per live rank', () => {
419
+ const { tweakCapRow } = require('../modules/lifecycle/routes/project-settings.js');
420
+ const row = tweakCapRow({ mode: 'off', cap: 200, rank_caps: { xenos: 5 }, source: { cap: 'default' }, invalid: [] });
421
+ assert.equal(row.key, 'tweak_round_cap');
422
+ assert.equal(row.editable, true);
423
+ assert.equal(row.value.cap, 200);
424
+ assert.deepEqual(row.value.ranks, api.LIVE_RANK_LADDER.map((rank) => ({ rank, cap: rank === 'xenos' ? 5 : null })));
425
+ const page = fs.readFileSync(path.join(ROOT, 'modules', 'hall-ui', 'public', 'project-settings.js'), 'utf8');
426
+ assert.match(page, /row\.key === 'tweak_round_cap'/);
427
+ assert.match(page, /sendJson\('PATCH', '\/project-settings\/tweak-autopickup', \{ cap: Number\(\$\('ps-tweak-cap'\)\.value\), rank_caps: rankCaps \}\)/);
428
+ });