@bongos/core 1.24.5 → 1.24.6

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 (44) hide show
  1. package/.bongos-core.json +70 -45
  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 +7 -0
  6. package/clients/bongos-client/index.mjs +6 -0
  7. package/docs/adr/0396-google-sign-in-a-stand-in-login-and-a-browser-approved-cli-sign-in.md +8 -0
  8. package/docs/api/openapi.json +110 -5
  9. package/docs/api-reference.md +6 -3
  10. package/docs/copy-inventory.md +36 -32
  11. package/docs/copy-registry.json +69 -33
  12. package/docs/module-api-changelog.md +2 -0
  13. package/docs/page-inventory.json +2 -1
  14. package/docs/page-readings.json +63 -55
  15. package/migrations/core_286_credit_log_no_spend.sql +128 -0
  16. package/modules/copy-desk/auto-close.js +5 -3
  17. package/modules/copy-desk/page-status.js +7 -4
  18. package/modules/copy-desk/tests/copy_page_auto_close.mjs +4 -4
  19. package/modules/lifecycle/routes/claims.js +7 -1
  20. package/modules/platform-identity/account-logins.js +131 -0
  21. package/modules/platform-identity/migrations/platform_identity_035_account_login_email_idx.sql +19 -0
  22. package/modules/platform-identity/routes/profile.js +29 -1
  23. package/modules/platform-identity/routes/sso.js +25 -3
  24. package/modules/public-landing/public/account.html +114 -0
  25. package/modules/public-landing/public/account.states.json +1 -0
  26. package/modules/ui-design/kit/serve.js +24 -0
  27. package/package-lock.json +2 -2
  28. package/package.json +1 -1
  29. package/release-notes.json +18 -0
  30. package/scripts/bongos/run-unit-tests.js +4 -0
  31. package/src/bongos/auth-github.js +24 -7
  32. package/src/bongos/routes/auth-google.js +71 -5
  33. package/src/bongos/routes/auth-link.js +132 -0
  34. package/src/bongos/routes.js +2 -0
  35. package/src/bongos/sign-in-pages.js +20 -1
  36. package/src/module-api.js +1 -1
  37. package/tests/account_linking.mjs +289 -0
  38. package/tests/account_logins_db.mjs +56 -0
  39. package/tests/claims_batch_routes.mjs +79 -12
  40. package/tests/copy_desk_page_release.mjs +20 -0
  41. package/tests/copy_stuck_page_tweaks.mjs +2 -2
  42. package/tests/credit_log_no_spend_db.mjs +160 -0
  43. package/tests/effective_visibility_predicate.mjs +8 -0
  44. package/tests/hub_account_page.mjs +91 -5
@@ -0,0 +1,128 @@
1
+ -- core_286_credit_log_no_spend.sql — task 1004988 (goal 1000092; ADR 0385
2
+ -- decision 2, ADR 0387).
3
+ --
4
+ -- Credits measure contribution. They are never spent, transferred or redeemed,
5
+ -- so the ledger has no row that takes credits away for something in return.
6
+ -- Until now that was a convention: credit_log's own column notes listed
7
+ -- 'redemption' as a reason and called a negative delta "spent (future)", and
8
+ -- nothing in Postgres stopped a negative spend row. This makes the DATABASE
9
+ -- refuse it, so no code path — present or future, ours or a module's — can
10
+ -- book one.
11
+ --
12
+ -- WHAT IS ADMITTED. A row with delta >= 0 is admitted as before (earning, and the
13
+ -- delta-0 audit rows rank changes and builder exits write). A NEGATIVE row is
14
+ -- admitted only as a REVERSAL of an existing positive row, in one of two shapes:
15
+ --
16
+ -- 1. reason = 'reversal:<credit_log id>' — the general shape. The named row
17
+ -- must exist, belong to the same builder and be positive, and all the
18
+ -- reversals of it together may not exceed it.
19
+ -- 2. reason = '<original reason>_reversal' with task_id set — the shape
20
+ -- core_194 (ADR 0120's one-time clawback, reason 'task.confirmed_reversal')
21
+ -- already wrote. The reference is the (builder, task, original reason)
22
+ -- rows, which must exist and sum positive; reversals may not exceed them.
23
+ -- Kept so that migration, and the integration test that re-runs it, stay
24
+ -- valid on a database that carries this trigger.
25
+ --
26
+ -- Any other negative row is refused. A row whose reason names a spend,
27
+ -- redemption or transfer is refused at any sign: a positive "transfer in" is
28
+ -- the other half of a transfer, and decision 2 forbids the transfer itself.
29
+ --
30
+ -- WHAT IS NOT CHANGED (ADR 0387). No column is added and no existing row is
31
+ -- read, converted or rewritten: the trigger is BEFORE INSERT only, so history —
32
+ -- including core_194's reversal rows — stays exactly as booked. This does not
33
+ -- contradict ADR 0387's "the only schema change is the money record": that
34
+ -- sentence is about the SHAPE of credit_log (no money column, no backfill), and
35
+ -- this adds none. It enforces ADR 0387 decision 1 ("never redeemable") in the
36
+ -- database rather than in the code that writes the ledger.
37
+ --
38
+ -- Concurrency: the reversed row(s) are locked FOR UPDATE before the reversal
39
+ -- total is summed, so two reversals racing for the same row cannot both pass
40
+ -- the "may not exceed" check.
41
+ --
42
+ -- Cost: a positive row (every normal earning) pays one regex test and returns.
43
+ -- Only a negative row reads the ledger, and every read is indexed: the reversed
44
+ -- row by its primary key (shape 1), the original rows by idx_credit_log_task
45
+ -- (core_189, shape 2), and the reversals already booked by the PARTIAL index
46
+ -- below, which holds negative rows only — so it stays as small as the number of
47
+ -- reversals ever made, not the size of the ledger.
48
+ --
49
+ -- The refused names match as whole words: the name, then a separator (. _ : -)
50
+ -- or the end. So 'spend', 'spend.x' and 'transfer:3' are refused, and a reason
51
+ -- that merely starts with the letters ('spender-of-the-month') is not.
52
+
53
+ CREATE INDEX IF NOT EXISTS idx_credit_log_reversals
54
+ ON credit_log (builder_id, reason) WHERE delta < 0;
55
+
56
+ CREATE OR REPLACE FUNCTION credit_log_refuse_spend() RETURNS trigger AS $$
57
+ DECLARE
58
+ ref_id bigint;
59
+ orig_rec record;
60
+ orig_reason text;
61
+ orig_total bigint;
62
+ reversed bigint;
63
+ BEGIN
64
+ IF NEW.reason ~* '^(redemption|redeem|spend|spent|transfer)([._:-]|$)' THEN
65
+ RAISE EXCEPTION 'credit_log refuses %: credits are never spent, transferred or redeemed (ADR 0385 decision 2)', NEW.reason
66
+ USING ERRCODE = 'check_violation';
67
+ END IF;
68
+
69
+ IF NEW.delta >= 0 THEN
70
+ RETURN NEW;
71
+ END IF;
72
+
73
+ -- Shape 1: 'reversal:<credit_log id>'.
74
+ IF NEW.reason ~ '^reversal:[0-9]{1,18}$' THEN
75
+ ref_id := substring(NEW.reason FROM 10)::bigint;
76
+ SELECT id, builder_id, delta INTO orig_rec FROM credit_log WHERE id = ref_id FOR UPDATE;
77
+ -- Two IFs, not one OR: plpgsql does not promise to short-circuit, and the
78
+ -- fields of a record no row was selected into must not be read.
79
+ IF NOT FOUND THEN
80
+ RAISE EXCEPTION 'credit_log refuses a reversal of row %: no such row', ref_id
81
+ USING ERRCODE = 'check_violation';
82
+ END IF;
83
+ IF orig_rec.builder_id <> NEW.builder_id OR orig_rec.delta <= 0 THEN
84
+ RAISE EXCEPTION 'credit_log refuses a reversal of row %: it must name an existing positive row of the same builder', ref_id
85
+ USING ERRCODE = 'check_violation';
86
+ END IF;
87
+ SELECT COALESCE(SUM(delta), 0) INTO reversed
88
+ FROM credit_log WHERE builder_id = NEW.builder_id AND reason = NEW.reason AND delta < 0;
89
+ IF orig_rec.delta + reversed + NEW.delta < 0 THEN
90
+ RAISE EXCEPTION 'credit_log refuses a reversal of row %: it would reverse more than the row booked', ref_id
91
+ USING ERRCODE = 'check_violation';
92
+ END IF;
93
+ RETURN NEW;
94
+ END IF;
95
+
96
+ -- Shape 2: '<original reason>_reversal' against the same builder and task.
97
+ IF NEW.reason ~ '^[a-z0-9_.]+_reversal$' AND NEW.task_id IS NOT NULL THEN
98
+ orig_reason := left(NEW.reason, length(NEW.reason) - length('_reversal'));
99
+ PERFORM 1 FROM credit_log
100
+ WHERE builder_id = NEW.builder_id AND task_id = NEW.task_id AND reason = orig_reason
101
+ FOR UPDATE;
102
+ SELECT COALESCE(SUM(delta), 0) INTO orig_total
103
+ FROM credit_log WHERE builder_id = NEW.builder_id AND task_id = NEW.task_id AND reason = orig_reason;
104
+ SELECT COALESCE(SUM(delta), 0) INTO reversed
105
+ FROM credit_log WHERE builder_id = NEW.builder_id AND task_id = NEW.task_id AND reason = NEW.reason AND delta < 0;
106
+ IF orig_total <= 0 OR orig_total + reversed + NEW.delta < 0 THEN
107
+ RAISE EXCEPTION 'credit_log refuses %: it must reverse existing % credit on the same task, and no more than was booked', NEW.reason, orig_reason
108
+ USING ERRCODE = 'check_violation';
109
+ END IF;
110
+ RETURN NEW;
111
+ END IF;
112
+
113
+ RAISE EXCEPTION 'credit_log refuses a negative row (reason %): credits are never spent or redeemed; only a reversal of an existing row may be negative (ADR 0385 decision 2)', NEW.reason
114
+ USING ERRCODE = 'check_violation';
115
+ END;
116
+ $$ LANGUAGE plpgsql;
117
+
118
+ DROP TRIGGER IF EXISTS trg_credit_log_refuse_spend ON credit_log;
119
+ CREATE TRIGGER trg_credit_log_refuse_spend
120
+ BEFORE INSERT ON credit_log
121
+ FOR EACH ROW EXECUTE FUNCTION credit_log_refuse_spend();
122
+
123
+ COMMENT ON TABLE credit_log IS
124
+ 'Append-only contribution ledger (ADR 0385, ADR 0387). Credits measure work: they are never money, never spent, transferred or redeemed. builders.total_credits is a cache kept by trg_credit_log_apply.';
125
+ COMMENT ON COLUMN credit_log.delta IS
126
+ 'Credits earned (positive), an audit row (0), or a reversal of an earlier row (negative). The trigger trg_credit_log_refuse_spend refuses every other negative row.';
127
+ COMMENT ON COLUMN credit_log.reason IS
128
+ 'What earned the credits, e.g. task.shipped, session.token_reward, idea.credit.*. A negative row must read reversal:<credit_log id> or <original reason>_reversal with its task_id set.';
@@ -18,8 +18,10 @@
18
18
  // (unplaced, shared or removed lines), so /tweak has no line
19
19
  // to apply and the round can never move on its own.
20
20
  // draft_expired `ready` with a draft and no batch, untouched for
21
- // page-status's DRAFT_EXPIRES_AFTER (14 days, task 1004901):
22
- // its artist was reminded at 7 days and never came back.
21
+ // page-status's DRAFT_EXPIRES_AFTER (task 1004901; one day
22
+ // since task 1004976, the owner's answer on task 1004971,
23
+ // with no reminder step first). The draft text stays on
24
+ // the task: no compose, so the description is not touched.
23
25
  //
24
26
  // All three are abandoned through the lifecycle port's releaseStuckTweak (no compose,
25
27
  // so the note is the reason and nothing is written to the description). The
@@ -38,7 +40,7 @@ const GRACE_MS = Number(process.env.COPY_AUTO_CLOSE_GRACE_MS) || 60 * 60_000;
38
40
  const NOTES = Object.freeze({
39
41
  blank: 'Closed: nothing was written. The round was opened and left blank for a day; claim the page again to start one.',
40
42
  nothing_to_apply: 'Closed by itself: every rewritten line went to an engineer task, so nothing was left to apply on the page.',
41
- draft_expired: 'Closed by itself: the draft sat untouched for two weeks. Its words stay on this task; claim the page again to start over.',
43
+ draft_expired: 'Closed by itself: the draft sat untouched for a day. Its words stay on this task; claim the page again to start over.',
42
44
  orphaned_apply: 'Released: the apply stopped without finishing. Nobody holds this round any more, so it is back in the queue.',
43
45
  });
44
46
 
@@ -311,8 +311,8 @@ function orderedSurfaces(inventory) {
311
311
  // This is every page with an open round, where it is, since when (the round's
312
312
  // last update), and whether it has sat there too long. Waiting for review is
313
313
  // the artist's own move and a draft is theirs to finish: a draft or a page
314
- // being written is stuck after 7 days and a draft expires after 14 (task
315
- // 1004901); a review is stuck after 3 days (task 1004777, so its artist is
314
+ // being written is stuck after 7 days, and a draft left untouched expires after
315
+ // one day (task 1004901, shortened by task 1004976); a review is stuck after 3 days (task 1004777, so its artist is
316
316
  // told); a state the reads cannot name always needs to be reviewed.
317
317
  // ---------------------------------------------------------------------------
318
318
 
@@ -322,12 +322,15 @@ const DAY_MS = 24 * 60 * 60 * 1000;
322
322
  // work) and WHEN it is overdue (stuck_after: then it is pushed to that person on
323
323
  // Home and in the daily digest). A draft nobody touches also EXPIRES
324
324
  // (expires_after): the auto-close sweep abandons it, its words kept on the task.
325
- const DRAFT_EXPIRES_AFTER = 14 * DAY_MS;
325
+ // task 1004976 (owner, task 1004971): a draft expires after ONE day, and there
326
+ // is no separate reminder step at that length, so the draft is due when it
327
+ // expires (stuck_after = expires_after), not reminded a week before.
328
+ const DRAFT_EXPIRES_AFTER = DAY_MS;
326
329
  // task 1004972 (owner, task 1004971): a round opened and left blank closes after a day.
327
330
  const BLANK_CLOSES_AFTER = DAY_MS;
328
331
  const IN_FLIGHT = Object.freeze({
329
332
  blank: { word: 'Opened, nothing written yet', stuck_after: BLANK_CLOSES_AFTER, waits_on: 'artist', expires_after: BLANK_CLOSES_AFTER },
330
- draft: { word: 'Being written', stuck_after: 7 * DAY_MS, waits_on: 'artist', expires_after: DRAFT_EXPIRES_AFTER },
333
+ draft: { word: 'Being written', stuck_after: DRAFT_EXPIRES_AFTER, waits_on: 'artist', expires_after: DRAFT_EXPIRES_AFTER },
331
334
  writing: { word: 'Being written', stuck_after: 7 * DAY_MS, waits_on: 'artist' },
332
335
  words_review: { word: 'Words waiting for review', stuck_after: 3 * DAY_MS, waits_on: 'artist' },
333
336
  submitted: { word: 'Approved, waiting to be applied', stuck_after: 3 * DAY_MS, waits_on: 'appliers' },
@@ -33,7 +33,7 @@ const ROUNDS = {
33
33
  blank: round({ id: '11' }),
34
34
  empty_batch: round({ id: '12', description: `${draft}\n\n${batch([])}` }),
35
35
  real_batch: round({ id: '13', description: `${draft}\n\n${batch([line])}` }),
36
- draft_only: round({ id: '14', description: draft }),
36
+ draft_only: round({ id: '14', description: draft, updated_at: new Date(NOW - 12 * 3600_000).toISOString() }),
37
37
  held: round({ id: '15', status: 'active', holder_id: '7' }),
38
38
  waiting: round({ id: '16', status: 'completed', description: `${draft}\n\n${batch([line])}` }),
39
39
  fresh_blank: round({ id: '17', updated_at: new Date(NOW - 5 * 60_000).toISOString() }),
@@ -56,11 +56,11 @@ await test('a blank round and an empty batch are the only two that close', () =>
56
56
  });
57
57
  });
58
58
 
59
- await test('a draft left untouched for two weeks expires; a younger one stays (task 1004901)', () => {
59
+ await test('a draft left untouched for a day expires; a younger one stays (task 1004901, one day since task 1004976)', () => {
60
60
  const D = 86400000;
61
61
  const at = (days) => round({ description: draft, updated_at: new Date(NOW - days * D).toISOString() });
62
- assert.equal(autoClose.closeReason(at(13.9), { now: NOW }), null);
63
- assert.equal(autoClose.closeReason(at(14.1), { now: NOW }), 'draft_expired');
62
+ assert.equal(autoClose.closeReason(at(0.9), { now: NOW }), null);
63
+ assert.equal(autoClose.closeReason(at(1.1), { now: NOW }), 'draft_expired');
64
64
  assert.equal(autoClose.closeReason({ ...at(30), holder_id: '7' }, { now: NOW }), null, 'a held draft is being written, never expired');
65
65
  });
66
66
 
@@ -443,7 +443,13 @@ module.exports = function buildClaimsRouter() {
443
443
  // rank: any-builder — atomic multi-claim; same Xenos row-level filter applies.
444
444
  // V3.R13 (#237): same newcomer gate as POST /claims — a fresh builder can't
445
445
  // sneak around the "one claim at a time" rule by batching.
446
- router.post('/claims/batch', auth.requireBuilder, gateNewcomerClaim, async (req, res) => {
446
+ // task 1005005: and the same gateOneActiveClaimPerSession as POST /claims, in
447
+ // the same order, so a session already holding a claim in this tree cannot
448
+ // batch more work into it. It reads the SESSION's existing active claims (the
449
+ // batch's own rows do not exist yet), keyed on the body's worktree_name — the
450
+ // caller's tree, which a batch also uses as its row-name prefix. A
451
+ // bind_session:false batch (the hall) has no session and passes, as on /claims.
452
+ router.post('/claims/batch', auth.requireBuilder, gateOneActiveClaimPerSession, gateNewcomerClaim, async (req, res) => {
447
453
  if (validateOrRespond(req, res, {
448
454
  task_ids: { required: true, type: 'array', maxItems: 20 },
449
455
  worktree_name: { type: 'string', maxLength: LIMITS.WORKTREE_NAME },
@@ -192,6 +192,131 @@ async function listLoginsForPerson(personKey, { pool = defaultPool } = {}) {
192
192
  return rows;
193
193
  }
194
194
 
195
+ // ── Linking (task 1004995) ──────────────────────────────────────────────────
196
+ // A signed-in person adds a second way in by signing in with it. Never a merge:
197
+ // a way in that already reaches ANOTHER person is refused with 'taken', because
198
+ // both accounts may hold credits, ranks and history and joining them is a
199
+ // decision the server must not make on anyone's behalf (owner, 2026-10-29).
200
+
201
+ // Who signs in with this GitHub user id? → the person key, or null when no one
202
+ // does yet. Every GitHub sign-in on the hub asks this first, so a GitHub account
203
+ // linked to someone who joined with Google reaches THEM, not a second person
204
+ // keyed on the GitHub id (the ADR 0393 carry-over).
205
+ async function personKeyForGithub(githubId, { pool = defaultPool } = {}) {
206
+ const person = await findPersonByLogin({ provider: 'github', subject: githubId }, { pool });
207
+ return person ? person.personKey : null;
208
+ }
209
+
210
+ // Add a way in to the signed-in person → { linked: true, already } or
211
+ // { refused: 'taken' | 'already_linked' | 'no_account' }. For GitHub the linked
212
+ // login is also written on the account (ADR 0393 §4: NULL until linking sets it).
213
+ async function linkLogin({ personKey, provider, subject, email, githubLogin } = {}, { pool = defaultPool } = {}) {
214
+ const l = normalizeLogin({ provider, subject });
215
+ if (!l || !pi.isNumericGithubId(personKey)) throw new Error('linkLogin: not a valid person or provider identity');
216
+ const owner = await findPersonByLogin(l, { pool });
217
+ if (owner) return owner.personKey === String(personKey) ? { linked: true, already: true } : { refused: 'taken' };
218
+ try {
219
+ return await withTx(async (client) => {
220
+ const { rows } = await client.query(
221
+ `SELECT id FROM platform_identity_accounts WHERE github_id = $1`, [String(personKey)],
222
+ );
223
+ if (!rows[0]) return { refused: 'no_account' };
224
+ await client.query(
225
+ `INSERT INTO platform_identity_account_logins (account_id, provider, subject, email, last_used_at)
226
+ VALUES ($1, $2, $3, $4, now())`,
227
+ [rows[0].id, l.provider, l.subject, cleanEmail(email)],
228
+ );
229
+ if (l.provider === 'github') {
230
+ await client.query(
231
+ `UPDATE platform_identity_accounts SET github_login = $2 WHERE id = $1`,
232
+ [rows[0].id, typeof githubLogin === 'string' && githubLogin ? githubLogin.slice(0, 100) : null],
233
+ );
234
+ }
235
+ return { linked: true, already: false };
236
+ }, { pool });
237
+ } catch (err) {
238
+ if (err && err.code === '23505') {
239
+ // Which UNIQUE fired decides the answer: another person took this way in
240
+ // a moment ago, or this person already holds one for the provider.
241
+ const raced = await findPersonByLogin(l, { pool });
242
+ if (raced && raced.personKey !== String(personKey)) return { refused: 'taken' };
243
+ if (raced) return { linked: true, already: true };
244
+ return { refused: 'already_linked' };
245
+ }
246
+ throw err;
247
+ }
248
+ }
249
+
250
+ // Why this way in cannot be removed, or null when it can. Never the last way in
251
+ // (owner, 2026-10-29); and never GitHub from an account born with it, because
252
+ // that account's key IS its GitHub id, so a GitHub sign-in would still reach it.
253
+ function unlinkRefusal({ personKey, provider, count }) {
254
+ if (provider === 'github' && !isMintedPersonKey(personKey)) return 'born_with';
255
+ if (count <= 1) return 'last_way_in';
256
+ return null;
257
+ }
258
+
259
+ // Remove a way in from the signed-in person → { unlinked: true } or
260
+ // { refused: 'not_linked' | 'last_way_in' | 'born_with' }. The count and the
261
+ // delete share one transaction, with the rows locked, so two racing removals
262
+ // cannot both pass the last-way-in check.
263
+ async function unlinkLogin({ personKey, provider } = {}, { pool = defaultPool } = {}) {
264
+ if (!LOGIN_PROVIDERS.includes(provider) || !pi.isNumericGithubId(personKey)) return { refused: 'not_linked' };
265
+ return withTx(async (client) => {
266
+ const { rows } = await client.query(
267
+ `SELECT l.id, l.provider, a.id AS account_id
268
+ FROM platform_identity_account_logins l
269
+ JOIN platform_identity_accounts a ON a.id = l.account_id
270
+ WHERE a.github_id = $1
271
+ FOR UPDATE OF l`,
272
+ [String(personKey)],
273
+ );
274
+ const row = rows.find((r) => r.provider === provider);
275
+ if (!row) return { refused: 'not_linked' };
276
+ const why = unlinkRefusal({ personKey: String(personKey), provider, count: rows.length });
277
+ if (why) return { refused: why };
278
+ await client.query(`DELETE FROM platform_identity_account_logins WHERE id = $1`, [row.id]);
279
+ if (provider === 'github') {
280
+ await client.query(`UPDATE platform_identity_accounts SET github_login = NULL WHERE id = $1`, [row.account_id]);
281
+ }
282
+ return { unlinked: true };
283
+ }, { pool });
284
+ }
285
+
286
+ // A first sign-in whose address another way in already carries → the providers
287
+ // to suggest instead, e.g. ['github'], or [] (task 1004995). Asked only while
288
+ // this provider identity reaches no one yet, so the person can sign in with the
289
+ // account they already have and link this one there, rather than make a second
290
+ // account they would never be able to join to the first. Only provider NAMES
291
+ // come back — never who, never the address — and nothing is joined: owning a
292
+ // matching address must not reach anyone's account (owner, 2026-10-29). This is
293
+ // the one read that compares emails.
294
+ async function existingAccountHint({ provider, subject, email } = {}, { pool = defaultPool } = {}) {
295
+ const l = normalizeLogin({ provider, subject });
296
+ const e = cleanEmail(email);
297
+ if (!l || !e) return [];
298
+ if (await findPersonByLogin(l, { pool })) return [];
299
+ const { rows } = await pool.query(
300
+ `SELECT DISTINCT provider FROM platform_identity_account_logins
301
+ WHERE provider <> $1 AND lower(email) = lower($2)`,
302
+ [l.provider, e],
303
+ );
304
+ return LOGIN_PROVIDERS.filter((p) => rows.some((r) => r.provider === p));
305
+ }
306
+
307
+ // The hub's own GitHub sign-in stamps its way in as used, and keeps the address
308
+ // GitHub showed (its public one), so a later Google sign-in can be offered a
309
+ // link. Display and suggestion only, like every email here.
310
+ async function touchGithubLogin({ githubId, email } = {}, { pool = defaultPool } = {}) {
311
+ const l = normalizeLogin({ provider: 'github', subject: githubId });
312
+ if (!l) return;
313
+ await pool.query(
314
+ `UPDATE platform_identity_account_logins SET last_used_at = now(), email = COALESCE($2, email)
315
+ WHERE provider = 'github' AND subject = $1`,
316
+ [l.subject, cleanEmail(email)],
317
+ );
318
+ }
319
+
195
320
  module.exports = {
196
321
  LOGIN_PROVIDERS,
197
322
  normalizeLogin,
@@ -202,4 +327,10 @@ module.exports = {
202
327
  createAccountForLogin,
203
328
  signInWithLogin,
204
329
  listLoginsForPerson,
330
+ personKeyForGithub,
331
+ linkLogin,
332
+ unlinkRefusal,
333
+ unlinkLogin,
334
+ existingAccountHint,
335
+ touchGithubLogin,
205
336
  };
@@ -0,0 +1,19 @@
1
+ -- platform_identity_035 — index the ways in by address, for the one email read
2
+ -- (task 1004995, ADR 0396 amendment "linking").
3
+ --
4
+ -- existingAccountHint (account-logins.js) asks, on a first Google sign-in, whether
5
+ -- another way in shows the address Google verified, so the person can be offered
6
+ -- the account they already have instead of a second one. It compares
7
+ -- lower(email) = lower($2), which no index served: every first Google sign-in
8
+ -- would scan the whole table. This partial expression index serves exactly that
9
+ -- read and skips the rows with no address (most GitHub ways in).
10
+ --
11
+ -- Additive and idempotent: an index only, no column or constraint changes, so a
12
+ -- reader that never applies this file still works, only slower.
13
+
14
+ CREATE INDEX IF NOT EXISTS platform_identity_account_logins_lower_email_idx
15
+ ON platform_identity_account_logins (lower(email))
16
+ WHERE email IS NOT NULL;
17
+
18
+ COMMENT ON INDEX platform_identity_account_logins_lower_email_idx IS
19
+ 'Serves existingAccountHint''s lower(email) match on a first Google sign-in (task 1004995). A suggestion read only: no sign-in or link is decided by an email.';
@@ -239,9 +239,17 @@ module.exports = function profileRoutes() {
239
239
  // ADR 0393): GitHub, Google, or both, with the address each provider vouched
240
240
  // for. Keyed on the authenticated github_id (the person key); the provider's
241
241
  // user id never crosses. A system:* principal has no platform account: [].
242
+ //
243
+ // Each method carries `unlink_refused` (null, 'last_way_in' or 'born_with') so the
244
+ // page can say why a Remove is missing (task 1004995).
242
245
  router.get('/me/sign-in-methods', requireBuilder, async (req, res) => {
243
246
  try {
244
- const methods = await logins.listLoginsForPerson(req.builder.github_id, { pool });
247
+ const key = req.builder.github_id;
248
+ const rows = await logins.listLoginsForPerson(key, { pool });
249
+ const methods = rows.map((m) => ({
250
+ ...m,
251
+ unlink_refused: logins.unlinkRefusal({ personKey: String(key), provider: m.provider, count: rows.length }),
252
+ }));
245
253
  res.set('Cache-Control', 'no-store');
246
254
  res.json({ methods, providers: logins.LOGIN_PROVIDERS });
247
255
  } catch (err) {
@@ -250,5 +258,25 @@ module.exports = function profileRoutes() {
250
258
  }
251
259
  });
252
260
 
261
+ // rank: any-builder — remove one way in from the caller's OWN account (task
262
+ // 1004995), keyed on the authenticated person key. Never the last way in, and
263
+ // never GitHub from an account born with it (its key is its GitHub id). Adding
264
+ // a way in is a sign-in, so it lives with the sign-in routes, not here.
265
+ router.delete('/me/sign-in-methods/:provider', requireBuilder, async (req, res) => {
266
+ const provider = String(req.params.provider || '');
267
+ if (!logins.LOGIN_PROVIDERS.includes(provider)) return res.fail('unknown_provider', 404);
268
+ try {
269
+ const out = await logins.unlinkLogin({ personKey: req.builder.github_id, provider }, { pool });
270
+ res.set('Cache-Control', 'no-store');
271
+ if (out.unlinked) return res.json({ ok: true });
272
+ if (out.refused === 'not_linked') return res.fail('not_linked', { status: 404, message: 'that way in is not linked to your account' });
273
+ if (out.refused === 'last_way_in') return res.fail('last_way_in', { status: 409, message: 'this is your only way in, so it cannot be removed — link another first' });
274
+ return res.fail('born_with', { status: 409, message: 'your account was made with GitHub, so GitHub stays linked' });
275
+ } catch (err) {
276
+ api.logger('platform-identity').error(`DELETE /me/sign-in-methods/:provider failed: ${err && err.message}`);
277
+ res.fail('sign_in_method_unlink_failed', { status: 500, message: 'internal error' });
278
+ }
279
+ });
280
+
253
281
  return router;
254
282
  };
@@ -32,7 +32,8 @@ const guildEngagements = require('../guild-engagements');
32
32
  const instanceFeedback = require('../instance-feedback');
33
33
  const projectStats = require('../project-stats');
34
34
  // Ways in other than GitHub (task 1004993, ADR 0393/0396).
35
- const { signInWithLogin, hallTakesPersonKey } = require('../account-logins');
35
+ const logins = require('../account-logins');
36
+ const { signInWithLogin, hallTakesPersonKey } = logins;
36
37
 
37
38
  // What a Google-only person reads when a project's hall runs a core too old to
38
39
  // take them (task 1004994).
@@ -243,8 +244,21 @@ function registerSeams() {
243
244
  // a human accepts the platform terms, beside /sso/authorize. Core passes the
244
245
  // identity GitHub returned for the code it exchanged, never a request field,
245
246
  // and `activate: true` is a source literal here exactly as it is there.
246
- recordHubSignin: ({ githubId, githubLogin, displayName, avatarUrl }) => pi.upsertAccount({
247
- githubId, githubLogin, displayName, avatarUrl, activate: true,
247
+ // `githubId` is the PERSON key the sign-in resolved (task 1004995: a GitHub
248
+ // account linked to someone who joined with Google reaches their key), and
249
+ // `githubUserId` + `email` stamp the GitHub way in itself as used.
250
+ recordHubSignin: async ({ githubId, githubLogin, displayName, avatarUrl, githubUserId, email }) => {
251
+ await pi.upsertAccount({ githubId, githubLogin, displayName, avatarUrl, activate: true }, { pool });
252
+ await logins.touchGithubLogin({ githubId: githubUserId || githubId, email }, { pool });
253
+ },
254
+ // task 1004995: who a GitHub sign-in reaches (null = no one yet, so the
255
+ // GitHub id itself), and linking a second way in to the signed-in person.
256
+ personKeyForGithub: (githubUserId) => logins.personKeyForGithub(githubUserId, { pool }),
257
+ // A first Google sign-in whose verified address another way in carries →
258
+ // the providers to offer instead (names only; nothing is joined).
259
+ googleSignInHint: ({ subject, email }) => logins.existingAccountHint({ provider: 'google', subject, email }, { pool }),
260
+ linkLogin: ({ personKey, provider, subject, email, githubLogin }) => logins.linkLogin({
261
+ personKey, provider, subject, email, githubLogin,
248
262
  }, { pool }),
249
263
  // task 1004993 (ADR 0396): the hub's own Google sign-in. Finds the person by
250
264
  // Google's own id or creates them; never by an email. Core passes only what it
@@ -501,6 +515,14 @@ module.exports = function ssoRoutes() {
501
515
  if (out.state !== 'ok') return res.json(out); // pending | slow_down | expired | denied
502
516
  if (!out.client_id) return res.fail('device_poll_failed', { status: 500, message: 'internal error' });
503
517
  const id = out.identity;
518
+ // A GitHub account linked to someone who joined with Google is THAT person
519
+ // (task 1004995). This leg carries no sign of whether the project's core can
520
+ // take their key, so it never mints one for them: it says to sign in to the
521
+ // project in the browser, where /sso/authorize can tell.
522
+ const personKey = await logins.personKeyForGithub(id.github_id);
523
+ if (personKey && personKey !== String(id.github_id)) {
524
+ return res.fail('sign_in_in_browser', { status: 409, message: 'This GitHub account is linked to an account that joined with Google. Sign in to the project in your browser instead.' });
525
+ }
504
526
  await pi.upsertAccount({
505
527
  githubId: id.github_id,
506
528
  githubLogin: id.github_login,
@@ -214,6 +214,22 @@
214
214
  </form>
215
215
  </section>
216
216
 
217
+ <!-- WAYS TO SIGN IN — GET/DELETE /me/sign-in-methods (task 1004995). Linking is
218
+ a sign-in with the other account, so Link is a link to the sign-in routes,
219
+ and their answer comes back here as ?linked= or ?link_refused=. A way in
220
+ the server says cannot be removed shows why instead of a Remove. The rows
221
+ are cosmos.css's .mineRow, as under "projects you build on". -->
222
+ <section class="aSec" id="aWaysIn" aria-labelledby="aWaysIn-h">
223
+ <h2 id="aWaysIn-h">ways to sign in</h2>
224
+ <p class="aSide">GitHub, Google or both. Each one opens this same account, with the same credits, ranks and history.</p>
225
+ <div class="aBody">
226
+ <p class="aWhat" id="waysLoading">Reading your ways to sign in…</p>
227
+ <ul class="mineRows" id="waysList"></ul>
228
+ <p class="finePrint">Linking never joins two accounts. If the other one already has its own account here, we say so and change nothing.</p>
229
+ <p class="projMsg" id="waysMsg" role="status" aria-live="polite"></p>
230
+ </div>
231
+ </section>
232
+
217
233
  <!-- WHO CAN FIND YOU — account_visibility + recruiter_discoverable (privacy
218
234
  spec D1/D3, task 1002966), PATCH /me/cross-project. Ported from the hall's
219
235
  old "Profile privacy" section. The recruiter copy must name EXACTLY what
@@ -378,6 +394,7 @@
378
394
  }
379
395
  loadBuilding();
380
396
  loadGuilds();
397
+ loadWaysIn();
381
398
  }, function () { showAlert('Couldn’t reach the server — check your connection and refresh.'); });
382
399
  }
383
400
 
@@ -697,6 +714,103 @@
697
714
  }, function () { restore(); say(msg, 'Couldn’t reach the server. Try again.', 'err'); });
698
715
  }
699
716
 
717
+ // ---- ways to sign in (task 1004995). Read once the account is shown. A
718
+ // link's answer arrives in the address (?linked= / ?link_refused=) from the
719
+ // sign-in routes, and is said here in the page's own words. ----
720
+ var PROVIDER_NAME = { github: 'GitHub', google: 'Google' };
721
+ var LINK_START = { github: '/auth/link/github/start', google: '/auth/google/start?link=1' };
722
+ var KEPT_WHY = {
723
+ last_way_in: 'Your only way in, so it stays. Link another to be able to remove it.',
724
+ born_with: 'Your account was made with GitHub, so GitHub stays linked.',
725
+ };
726
+ function linkAnswer() {
727
+ var q = window.location.search || '';
728
+ var linked = /[?&]linked=(github|google)(&|$)/.exec(q);
729
+ if (linked) return { text: PROVIDER_NAME[linked[1]] + ' is linked. You can now sign in with either.', kind: 'ok' };
730
+ var refused = /[?&]link_refused=([a-z_]+)/.exec(q);
731
+ if (!refused) return null;
732
+ var p = /[?&]provider=(github|google)(&|$)/.exec(q);
733
+ var name = p ? PROVIDER_NAME[p[1]] : 'That';
734
+ var words = {
735
+ taken: 'That ' + name + ' account already has its own account here, so it was not linked. We never join two accounts; nothing changed.',
736
+ already_linked: 'Your account already has a ' + name + ' account linked. Remove it first to link a different one.',
737
+ cancelled: 'You cancelled linking ' + name + '. Nothing changed.',
738
+ expired: 'Linking ' + name + ' took too long. Try again.',
739
+ };
740
+ return { text: words[refused[1]] || 'Couldn’t link ' + name + '. Try again.', kind: 'err' };
741
+ }
742
+ function loadWaysIn() {
743
+ var msg = $('waysMsg');
744
+ var answer = linkAnswer();
745
+ if (answer) say(msg, answer.text, answer.kind);
746
+ return request('GET', '/me/sign-in-methods').then(function (res) {
747
+ $('waysLoading').hidden = true;
748
+ if (!res.ok || !res.data) { say(msg, 'Couldn’t read your ways to sign in — refresh in a moment.', 'err'); return; }
749
+ paintWaysIn(res.data.methods || [], res.data.providers || []);
750
+ }, function () {
751
+ $('waysLoading').hidden = true;
752
+ say(msg, 'Couldn’t reach the server — check your connection and refresh.', 'err');
753
+ });
754
+ }
755
+ function paintWaysIn(methods, providers) {
756
+ var ul = $('waysList');
757
+ ul.textContent = '';
758
+ providers.forEach(function (p) {
759
+ var held = methods.filter(function (m) { return m.provider === p; })[0];
760
+ ul.appendChild(wayRow(p, held));
761
+ });
762
+ }
763
+ function wayRow(provider, held) {
764
+ var name = PROVIDER_NAME[provider] || provider;
765
+ var row = rowEl('li', 'mineRow');
766
+ var main = rowEl('div', 'mineRow__main');
767
+ var title = rowEl('div', 'mineRow__name');
768
+ title.textContent = name;
769
+ main.appendChild(title);
770
+ var line = rowEl('span', 'mineRow__host');
771
+ line.textContent = held ? (held.email || 'linked') : 'not linked';
772
+ main.appendChild(line);
773
+ if (held && held.unlink_refused && KEPT_WHY[held.unlink_refused]) {
774
+ var why = rowEl('span', 'aTag');
775
+ why.textContent = KEPT_WHY[held.unlink_refused];
776
+ main.appendChild(why);
777
+ }
778
+ row.appendChild(main);
779
+ var actions = rowEl('div', 'mineRow__actions');
780
+ if (!held) {
781
+ var a = document.createElement('a');
782
+ a.className = 'btn small';
783
+ a.href = API + LINK_START[provider];
784
+ a.textContent = 'Link ' + name;
785
+ actions.appendChild(a);
786
+ } else if (!held.unlink_refused) {
787
+ var btn = document.createElement('button');
788
+ btn.type = 'button';
789
+ btn.className = 'btn small ghost';
790
+ btn.textContent = 'Remove';
791
+ btn.setAttribute('aria-label', 'Remove ' + name);
792
+ btn.addEventListener('click', function () { unlinkWay(provider, name, btn); });
793
+ actions.appendChild(btn);
794
+ }
795
+ row.appendChild(actions);
796
+ return row;
797
+ }
798
+ function unlinkWay(provider, name, btn) {
799
+ var msg = $('waysMsg');
800
+ btn.disabled = true;
801
+ btn.textContent = 'Removing…';
802
+ request('DELETE', '/me/sign-in-methods/' + provider).then(function (res) {
803
+ if (res.status === 401) { btn.disabled = false; btn.textContent = 'Remove'; sessionGone(msg); return; }
804
+ if (!res.ok) {
805
+ btn.disabled = false; btn.textContent = 'Remove';
806
+ say(msg, serverWords(res, 'Couldn’t remove ' + name + '. Try again.'), 'err');
807
+ return;
808
+ }
809
+ say(msg, name + ' is removed. It no longer opens this account.', 'ok');
810
+ loadWaysIn();
811
+ }, function () { btn.disabled = false; btn.textContent = 'Remove'; say(msg, 'Couldn’t reach the server. Try again.', 'err'); });
812
+ }
813
+
700
814
  // The identity read failing is not a sign-out. If the account itself was
701
815
  // read, the chip names it from that answer, so the way out is never lost.
702
816
  load().then(function () { return bar.ready; }).then(function () {
@@ -13,6 +13,7 @@
13
13
  "in-projects-band": { "auth": true, "actions": [["wait", 400], ["click", "#projTrig"], ["wait", 300]], "expect": { "visible": ["#menuProjects", "#mineCell"], "hidden": ["#menuProfile"] } },
14
14
  "in-profile-band": { "auth": true, "actions": [["wait", 400], ["click", "#who"], ["wait", 300]], "expect": { "visible": ["#menuProfile"], "hidden": ["#menuProjects"], "text": [["#bandWhoLogin", "builder"], ["#menuProfile [aria-current=\"page\"]", "Account"]] } },
15
15
  "in-building": { "auth": true, "url": "/account#aBuilding", "actions": [["wait", 500]], "expect": { "visible": ["#aBuilding", "#buildingList"], "hidden": ["#buildingEmpty", "#buildingLoading"], "count": [["#buildingList .mineRow", 2]], "text": [["#buildingList .mineRow:first-child .mineRow__name", "Example World"], ["#buildingList .mineRow:first-child .mineRow__host", "example.com"]], "attr": [["#buildingList .mineRow:first-child button", "aria-label", "Leave Example World"]] } },
16
+ "in-ways": { "auth": true, "url": "/account#aWaysIn", "actions": [["wait", 500]], "expect": { "visible": ["#aWaysIn", "#waysList"], "hidden": ["#waysLoading"], "count": [["#waysList .mineRow", 2]], "text": [["#waysList .mineRow:first-child .mineRow__name", "GitHub"], ["#waysList .mineRow:nth-child(2) .mineRow__host", "octo@example.com"]], "attr": [["#waysList .mineRow:nth-child(2) button", "aria-label", "Remove Google"]] } },
16
17
  "in-privacy": { "auth": true, "actions": [["wait", 400], ["click", "#aPrivacy .aOpt:nth-child(2)"], ["wait", 150]], "expect": { "checked": "input[name=visibility][value=private]", "visible": ["#visGuilds"], "hidden": ["#recordGuilds"], "count": [["#visGuildList li", 2]], "attr": [["#visGuildList li:first-child a", "href", "/g/forge-crew"]], "text": [["#visGuildList li:first-child a", "Forge Crew"], ["#recWhat", "They will see your name, your picture, your roles, and whether you have been active in the last 30 days — never your credits, works shipped, karma, or the projects you build on. This is the one thing a recruiter can see while your profile page is private. Turning this off removes you from both recruiting surfaces — the recruiting directory, and a recruiter’s look-up of one builder — straight away. · For now this follows your profile page setting."]] } }
17
18
  },
18
19
  "reducedMotion": { "auth": true, "actions": [["wait", 300]] }