-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathlinear.ts
More file actions
1984 lines (1858 loc) · 88.7 KB
/
Copy pathlinear.ts
File metadata and controls
1984 lines (1858 loc) · 88.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* MIT No Attribution
*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { execFile } from 'child_process';
import * as readline from 'readline';
import { CloudFormationClient, DescribeStacksCommand } from '@aws-sdk/client-cloudformation';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import {
CreateSecretCommand,
GetSecretValueCommand,
ListSecretsCommand,
PutSecretValueCommand,
ResourceExistsException,
SecretsManagerClient,
} from '@aws-sdk/client-secrets-manager';
import { DynamoDBDocumentClient, PutCommand, ScanCommand } from '@aws-sdk/lib-dynamodb';
import { Command } from 'commander';
import { ApiClient } from '../api-client';
import { loadConfig, loadCredentials } from '../config';
import { CliError } from '../errors';
import { formatJson } from '../format';
import {
buildAuthorizationUrl,
computeExpiresAt,
exchangeAuthorizationCode,
generatePkce,
LINEAR_OAUTH_SECRET_PREFIX,
linearOauthSecretName,
StoredLinearOauthToken,
} from '../linear-oauth';
import { awaitOauthCallback, CALLBACK_URL } from '../oauth-callback-server';
import { checkRepoOnboarding, notOnboardedGuidance } from '../repo-onboarding';
/** Default label that triggers an ABCA task when applied to a Linear issue. */
const DEFAULT_LABEL_FILTER = 'bgagent';
/** Standard RFC 4122 UUID — Linear's `projects.nodes[].id` matches this shape. */
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/** Width of the `═` banner bars in printed setup output. */
const BANNER_WIDTH = 72;
/**
* Render the printable Linear OAuth app config. Standalone export so
* `bgagent linear setup` can call it inline (Phase 2.0b setup wizard
* Step 2 — show the user what to paste into Linear's app form).
*/
export interface LinearAppTemplateOptions {
readonly botName?: string;
readonly developerName?: string;
readonly developerUrl?: string;
readonly description?: string;
readonly awsCallbackUrl?: string;
}
export function renderLinearAppTemplate(opts: LinearAppTemplateOptions = {}): string {
// Defaults match the upstream sample so unmodified `bgagent linear app-template`
// produces a usable config without forcing every operator to invent strings.
// Operators with custom branding override via flags.
const botName = opts.botName ?? 'bgagent[bot]';
const developerName = opts.developerName ?? 'ABCA';
const developerUrl = opts.developerUrl ?? 'https://github.com/aws-samples/sample-autonomous-cloud-coding-agents';
const description = opts.description ?? 'Autonomous Background Coding Agent';
// Phase 2.0b-O2 (shipped) uses a localhost callback that
// `bgagent linear setup` listens on for the one-time redirect. The
// `awsCallbackUrl` option is retained for the parked Phase 2.0a flow
// and (rare) operators forwarding the callback through a fixed
// upstream URL — but the localhost default works for everyone running
// setup interactively from their machine.
const callbackUrl = opts.awsCallbackUrl ?? 'http://localhost:8080/oauth/callback';
const bar = '═'.repeat(BANNER_WIDTH);
return [
bar,
'Linear OAuth app template',
bar,
'',
'Open https://linear.app/settings/api/applications/new and paste:',
'',
' Application name: bgagent',
` Developer name: ${developerName}`,
` Developer URL: ${developerUrl}`,
` Description: ${description}`,
'',
' Callback URLs (one per line, NO line wrapping):',
` ${callbackUrl}`,
'',
` GitHub username: ${botName} ← REQUIRED for actor=app`,
' Public: OFF',
' Client credentials: OFF',
' Webhooks: ON ← REQUIRED for actor=app',
' Webhook URL: https://example.com/placeholder ← any HTTPS URL',
' (You do NOT need to subscribe to any events for the OAuth flow itself)',
'',
'Click Save, copy the Client ID and Client Secret, then return here.',
'',
'Why these specific fields:',
' • GitHub username with [bot] suffix gates the actor=app agent flow.',
' Without it, Linear surfaces a misleading "Invalid redirect_uri" error.',
' • Webhooks toggle must be ON for the same reason; the URL value is unused',
' by the OAuth dance and can be a placeholder.',
' • Wildcard callback URLs are not accepted by Linear; list each URL fully.',
bar,
].join('\n');
}
/**
* Validate a Linear workspace slug. Used to keep the per-workspace
* Secrets Manager secret name (`bgagent-linear-oauth-<slug>`) within
* AWS's 64-char limit and to confirm the slug is the Linear `urlKey`
* shape (Linear's `urlKey` matches `[a-zA-Z0-9_-]+`).
*/
const SLUG_RE = /^[a-zA-Z0-9_-]{4,50}$/;
/**
* Open `url` in the user's default browser. Returns true on best-effort
* success, false if no opener is available (e.g. headless SSH session) so
* callers can fall back to printing the URL.
*
* Uses `child_process.execFile` directly rather than a dependency like
* `open` — no need for a 200-line module to spawn one shell command.
*/
export function openBrowser(url: string): Promise<boolean> {
return new Promise((resolve) => {
let opener: { cmd: string; args: string[] };
if (process.platform === 'darwin') {
opener = { cmd: 'open', args: [url] };
} else if (process.platform === 'win32') {
// `start` is a cmd.exe builtin; URLs need empty title arg + escaping.
opener = { cmd: 'cmd', args: ['/c', 'start', '""', url] };
} else {
opener = { cmd: 'xdg-open', args: [url] };
}
execFile(opener.cmd, opener.args, (err) => {
resolve(!err);
});
});
}
/**
* Check whether the LinearWebhookSecret already holds a real Linear
* signing secret (vs CDK's autogenerated placeholder). Used to decide
* whether to prompt for the webhook secret on subsequent setup runs.
*
* Linear's webhook signing secrets start with `lin_wh_` — the placeholder
* is a CDK-generated random JSON-encoded string that doesn't match.
*
* Returns true if a real secret is stored, false otherwise (including
* any error fetching — best-effort; a re-prompt is harmless).
*/
export async function isWebhookSecretConfigured(
client: SecretsManagerClient,
secretArn: string,
): Promise<boolean> {
try {
const result = await client.send(new GetSecretValueCommand({ SecretId: secretArn }));
const value = result.SecretString;
return typeof value === 'string' && value.startsWith('lin_wh_');
} catch (err) {
// Only treat "secret doesn't exist yet" as a clean false — any
// other error (AccessDenied, KMS decrypt failure, throttling) is
// actionable and we should surface it. A bare `catch { return
// false }` here makes setup re-prompt for a webhook secret when
// the real problem is IAM, which is a confusing UX for operators.
const errorName = (err as { name?: string }).name;
if (errorName === 'ResourceNotFoundException') {
return false;
}
const message = err instanceof Error ? err.message : String(err);
throw new CliError(
`Failed to read Linear webhook secret '${secretArn}': ${errorName ?? 'Error'}: ${message}. `
+ 'Likely IAM permission gap — confirm your CLI principal has '
+ '`secretsmanager:GetSecretValue` on this ARN.',
);
}
}
/**
* Generate an opaque, URL-safe `state` value for OAuth CSRF protection.
* 32 bytes of crypto-randomness — enough that collisions and guesses
* are not realistic concerns.
*/
function randomState(): string {
// Lazy import to keep `crypto` out of module-load surface for non-OAuth
// uses of this command file.
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { randomBytes } = require('crypto') as typeof import('crypto');
const STATE_BYTES = 32;
return randomBytes(STATE_BYTES).toString('base64url');
}
/**
* Idempotent secret upsert: tries CreateSecret first; if the secret
* already exists (re-running setup, rotating refresh token), falls
* back to PutSecretValue. Returns the secret ARN regardless of which
* branch ran.
*
* The Phase 2.0b-O2 design stores OAuth tokens at runtime (CLI creates
* the secret, not CDK), so the wizard owns this lifecycle.
*/
export async function upsertOauthSecret(
client: SecretsManagerClient,
secretName: string,
payload: StoredLinearOauthToken,
workspaceSlug: string,
): Promise<string> {
const secretString = JSON.stringify(payload);
try {
const create = await client.send(new CreateSecretCommand({
Name: secretName,
Description: `Linear OAuth token for workspace '${workspaceSlug}' (Phase 2.0b)`,
SecretString: secretString,
// Tags help with cost allocation and the deletion-runbook discoverability.
Tags: [
{ Key: 'bgagent:integration', Value: 'linear' },
{ Key: 'bgagent:linear:workspace_slug', Value: workspaceSlug },
],
}));
if (!create.ARN) {
throw new CliError(`CreateSecret returned no ARN for '${secretName}'.`);
}
return create.ARN;
} catch (err) {
if (err instanceof ResourceExistsException) {
const put = await client.send(new PutSecretValueCommand({
SecretId: secretName,
SecretString: secretString,
}));
if (!put.ARN) {
throw new CliError(`PutSecretValue returned no ARN for '${secretName}'.`);
}
return put.ARN;
}
throw err;
}
}
/**
* Find an OAuth credential pair (client_id + client_secret) reusable for a
* new workspace install. Returns the values from the FIRST `active` row in
* the workspace registry, by reading that row's per-workspace SM secret.
*
* Used by `bgagent linear add-workspace` so the operator doesn't have to
* re-paste the same Linear OAuth app credentials they already typed during
* the initial `bgagent linear setup`. Same Linear OAuth app can authorize
* multiple workspaces — Linear scopes consent per-workspace, but the app's
* client_id/client_secret are workspace-independent.
*
* Returns null when there's no existing active workspace, signalling that
* the operator should run `bgagent linear setup` first.
*/
export async function findReusableOauthAppCredentials(
ddb: DynamoDBDocumentClient,
sm: SecretsManagerClient,
registryTableName: string,
): Promise<{ clientId: string; clientSecret: string; sourceSlug: string } | null> {
// Limit=1 keeps the scan cheap. The registry table is one row per
// workspace install (small N) so a scan is acceptable here.
const scan = await ddb.send(new ScanCommand({
TableName: registryTableName,
FilterExpression: '#status = :active',
ExpressionAttributeNames: { '#status': 'status' },
ExpressionAttributeValues: { ':active': 'active' },
Limit: 1,
}));
const row = scan.Items?.[0];
if (!row || !row.oauth_secret_arn || !row.workspace_slug) {
return null;
}
const value = await sm.send(new GetSecretValueCommand({ SecretId: row.oauth_secret_arn as string }));
if (!value.SecretString) {
// Row points at an empty SM secret — broken state, but distinct from
// "no active workspace." Surface it so the operator gets a useful
// error instead of being told to run `setup` and creating a dup row.
throw new CliError(
`Workspace '${row.workspace_slug as string}' is registered but its OAuth secret `
+ `(${row.oauth_secret_arn as string}) has no value. Re-run \`bgagent linear setup\` `
+ 'for that workspace to repopulate it, or remove the registry row.',
);
}
let parsed: Partial<StoredLinearOauthToken>;
try {
parsed = JSON.parse(value.SecretString) as Partial<StoredLinearOauthToken>;
} catch (err) {
throw new CliError(
`Workspace '${row.workspace_slug as string}' OAuth secret is not valid JSON: `
+ `${err instanceof Error ? err.message : String(err)}. Re-run `
+ '`bgagent linear setup` for that workspace to fix it.',
);
}
if (!parsed.client_id || !parsed.client_secret) {
throw new CliError(
`Workspace '${row.workspace_slug as string}' OAuth secret is missing `
+ 'client_id or client_secret. Re-run `bgagent linear setup` for that workspace.',
);
}
return {
clientId: parsed.client_id,
clientSecret: parsed.client_secret,
sourceSlug: row.workspace_slug as string,
};
}
export function makeLinearCommand(): Command {
const linear = new Command('linear')
.description('Manage Linear integration');
linear.addCommand(
new Command('app-template')
.description('Print the field values to paste into Linear\'s OAuth app form')
.option('--bot-name <name>', 'GitHub username for actor=app (must end with [bot])')
.option('--developer-name <name>', 'Developer name shown on Linear\'s consent screen')
.option('--developer-url <url>', 'Developer URL shown on Linear\'s consent screen')
.option('--description <text>', 'App description shown on Linear\'s consent screen')
.option('--aws-callback-url <url>', 'AWS-hosted callback URL from create-oauth2-credential-provider')
.action((opts) => {
if (opts.botName && !/\[bot\]$/.test(opts.botName)) {
console.error(
'Error: --bot-name must end with the literal "[bot]" suffix '
+ `(Linear requires this for actor=app). Got: ${opts.botName}`,
);
process.exit(1);
}
console.log(renderLinearAppTemplate({
botName: opts.botName,
developerName: opts.developerName,
developerUrl: opts.developerUrl,
description: opts.description,
awsCallbackUrl: opts.awsCallbackUrl,
}));
}),
);
linear.addCommand(
new Command('webhook-info')
.description('Print the webhook URL + Linear settings for this stack')
.action(() => {
// Read-only convenience — surfaces the values an operator needs to
// create a webhook subscription in Linear (URL, resource types,
// followup command). Eliminates the "find the API URL in CFN
// outputs" detour that the setup guide used to embed.
const config = loadConfig();
if (!config.api_url) {
throw new CliError(
'No API URL configured. Run `bgagent configure` first to point at a deployed stack.',
);
}
const webhookUrl = `${config.api_url.replace(/\/+$/, '')}/linear/webhook`;
const bar = '═'.repeat(BANNER_WIDTH);
console.log(bar);
console.log('Linear webhook configuration');
console.log(bar);
console.log();
console.log('In Linear → Settings → API → Webhooks → + New webhook, paste:');
console.log();
console.log(` URL: ${webhookUrl}`);
console.log(' Resource types: Issues');
console.log(' Team: (whichever team owns the projects you map)');
console.log();
console.log('Save, then open the webhook detail page and copy the signing secret');
console.log('(starts with `lin_wh_`). Feed it to ABCA via:');
console.log();
console.log(' bgagent linear update-webhook-secret <slug>');
console.log();
console.log('Note: webhook subscriptions are workspace-scoped, with a fresh signing');
console.log('secret per subscription. Each Linear workspace you onboard needs its');
console.log('own webhook configured this way.');
console.log(bar);
}),
);
linear.addCommand(
new Command('link')
.description('Redeem an invite code from `bgagent linear invite-user` to link your Linear identity')
.argument('<code>', 'One-time invite code (e.g. link-3f8b4a2c)')
.option('--output <format>', 'Output format (text or json)', 'text')
.action(async (code: string, opts) => {
const client = new ApiClient();
// In text mode, do a dry-run preview FIRST so the user can
// confirm what they're linking before any write hits DDB. The
// safety rail that lets a teammate abort if the admin picked
// the wrong row.
//
// In `--output json` mode there's no interactive prompt, so the
// dry-run is wasted work — skip it and go straight to the real
// link call. The single response object is what callers script
// around.
if (opts.output !== 'json') {
const preview = await client.linearLink(code, { dryRun: true });
const name = preview.linear_user_name || preview.linear_user_id;
const email = preview.linear_user_email ? ` (${preview.linear_user_email})` : '';
const wsLabel = preview.linear_workspace_slug || preview.linear_workspace_id;
console.log('You are about to link the following Linear identity to YOUR ABCA account:');
console.log();
console.log(` Linear user: ${name}${email}`);
console.log(` Linear workspace: ${wsLabel}`);
console.log();
console.log('After linking, tasks triggered by this Linear user will be attributed to');
console.log('your platform user (concurrency caps, billing, `bgagent list`).');
console.log();
const confirm = (await promptLine('Continue? [Y/n]')).trim().toLowerCase();
if (confirm && confirm !== 'y' && confirm !== 'yes') {
console.log('Aborted. The invite code is still valid until it expires.');
return;
}
}
const result = await client.linearLink(code);
if (opts.output === 'json') {
console.log(formatJson(result));
} else {
console.log();
console.log('✅ Linear account linked.');
console.log(` Linked at: ${result.linked_at}`);
}
}),
);
linear.addCommand(
new Command('setup')
.description('Authorize a Linear workspace via OAuth (Phase 2.0b — direct flow, Secrets Manager storage)')
.argument('<slug>', 'Linear workspace urlKey (e.g. "acme" from linear.app/acme/...)')
.option('--region <region>', 'AWS region (defaults to configured region)')
.option('--stack-name <name>', 'CloudFormation stack name', 'backgroundagent-dev')
.option('--client-id <id>', 'Linear OAuth app Client ID (else prompted)')
.option('--client-secret <secret>', 'Linear OAuth app Client Secret (else prompted; prefer interactive)')
.option('--no-browser', 'Print the authorization URL instead of opening a browser (for SSH/headless)')
.option('--no-actor-app', 'Drop actor=app from the OAuth flow (diagnostic: isolates whether agent-install is blocking)')
.action(async (slug: string, opts) => {
if (!SLUG_RE.test(slug)) {
throw new CliError(
`Invalid workspace slug '${slug}'. Must be 4-50 chars matching [a-zA-Z0-9_-]. `
+ 'This is the Linear urlKey, e.g. \'acme\' from linear.app/acme/...',
);
}
const config = loadConfig();
const region = opts.region || config.region;
const stackName = opts.stackName;
// ─── Stack outputs ─────────────────────────────────────────────
const [
workspaceRegistryTable,
userMappingTable,
webhookSecretArn,
] = await Promise.all([
getStackOutput(region, stackName, 'LinearWorkspaceRegistryTableName'),
getStackOutput(region, stackName, 'LinearUserMappingTableName'),
getStackOutput(region, stackName, 'LinearWebhookSecretArn'),
]);
const missing: string[] = [];
if (!workspaceRegistryTable) missing.push('LinearWorkspaceRegistryTableName');
if (!userMappingTable) missing.push('LinearUserMappingTableName');
if (!webhookSecretArn) missing.push('LinearWebhookSecretArn');
if (missing.length > 0) {
throw new CliError(
`Stack '${stackName}' is missing outputs ${missing.join(', ')}. `
+ 'Re-deploy with the 2.0b CDK changes (mise //cdk:deploy).',
);
}
// ─── Resolve caller identity ──────────────────────────────────
const creds = loadCredentials();
if (!creds?.id_token) {
throw new CliError('Not authenticated — run `bgagent login` first.');
}
let cognitoSub: string;
try {
cognitoSub = extractCognitoSub();
} catch (err) {
throw new CliError(
`Could not read Cognito sub from cached id_token: ${err instanceof Error ? err.message : String(err)}. `
+ 'Run `bgagent login` to refresh credentials.',
);
}
// ─── Linear OAuth app credentials ──────────────────────────────
// Prompted up-front so the wizard doesn't get halfway through the
// OAuth dance before realising it can't continue.
console.log(`bgagent linear setup — workspace '${slug}'`);
console.log(` region: ${region}`);
console.log(
'\nLinear OAuth app credentials needed. If you have not created one, run `bgagent linear app-template`'
+ ' for the values to paste into Linear → Settings → API → New application.\n',
);
const clientId = (opts.clientId ?? await promptSecret('Linear Client ID: ')).trim();
if (!clientId) {
throw new CliError('Client ID is required.');
}
const clientSecret = (opts.clientSecret ?? await promptSecret('Linear Client Secret: ')).trim();
if (!clientSecret) {
throw new CliError('Client Secret is required.');
}
// ─── Step 1: Generate PKCE + open browser to Linear consent ────
const pkce = generatePkce();
const state = randomState();
// `opts.actorApp` is true by default; --no-actor-app sets it false.
// Commander populates `opts.actorApp = false` when --no-actor-app is passed.
const useActorApp = opts.actorApp !== false;
const authorizationUrl = buildAuthorizationUrl({
clientId,
redirectUri: CALLBACK_URL,
state,
codeChallenge: pkce.codeChallenge,
actorApp: useActorApp,
});
if (!useActorApp) {
console.log(' ⚠ --no-actor-app: dropping actor=app for diagnosis. Token will not be agent-scoped.');
}
// The localhost callback server starts BEFORE we open the browser
// so it's listening when Linear's redirect arrives.
const callbackPromise = awaitOauthCallback();
console.log();
if (opts.browser !== false) {
const opened = await openBrowser(authorizationUrl);
if (opened) {
console.log(' → Opened your browser to the Linear consent screen.');
console.log(' The browser will redirect to a localhost page after you Authorize — that\'s expected.');
} else {
console.log(' → Could not open browser automatically. Open this URL manually:');
console.log(` ${authorizationUrl}`);
}
} else {
console.log(' → --no-browser: open this URL manually:');
console.log(` ${authorizationUrl}`);
}
process.stdout.write(' → Waiting for browser callback...');
const callback = await callbackPromise;
console.log(' ✓');
// Phase 2.0b Option 2 expects Linear to redirect with `code` +
// `state`. If we got the AgentCore session_id shape, the user
// likely configured an `actor=app` flow against an AgentCore
// Identity provider — that path is parked, error out clearly.
if (callback.kind !== 'direct-oauth') {
throw new CliError(
'Localhost callback returned an AgentCore session_id, not a direct OAuth code. '
+ 'Phase 2.0b Option 2 only supports the direct redirect — verify Linear\'s '
+ 'redirect URI is set to http://localhost:8080/oauth/callback and re-run.',
);
}
if (callback.state !== state) {
throw new CliError(
`OAuth state mismatch (expected '${state}', got '${callback.state}'). `
+ 'Possible CSRF attack or stale tab — re-run setup.',
);
}
// ─── Step 2: Exchange code for access token ───────────────────
process.stdout.write(' → Exchanging code for access token...');
const tokenResponse = await exchangeAuthorizationCode({
code: callback.code,
codeVerifier: pkce.codeVerifier,
redirectUri: CALLBACK_URL,
clientId,
clientSecret,
});
console.log(' ✓');
// ─── Step 3: Fetch workspace identity ─────────────────────────
process.stdout.write(' → Querying Linear viewer + organization...');
const identity = await queryLinearIdentity(`Bearer ${tokenResponse.access_token}`);
if (!identity) {
throw new CliError(
'Linear viewer query rejected the access token. This is unexpected — token was just issued. '
+ 'Re-run `bgagent linear setup` if Linear\'s API is recovering from a transient outage.',
);
}
console.log(` ✓ (${identity.organization.name ?? identity.organization.urlKey ?? identity.organization.id})`);
if (identity.organization.urlKey && identity.organization.urlKey !== slug) {
console.log(
` ⚠ Slug '${slug}' does not match Linear's urlKey '${identity.organization.urlKey}'. `
+ 'Re-run with the correct slug to keep the registry key aligned with Linear.',
);
}
// ─── Step 4: Persist token to per-workspace Secrets Manager ───
process.stdout.write(' → Storing OAuth token...');
const sm = new SecretsManagerClient({ region });
const now = new Date().toISOString();
const stored: StoredLinearOauthToken = {
access_token: tokenResponse.access_token,
refresh_token: tokenResponse.refresh_token ?? '',
expires_at: computeExpiresAt(tokenResponse.expires_in),
scope: tokenResponse.scope,
// Co-located so Lambda-side refresh works without per-Lambda
// env vars — one secret holds everything needed to renew.
client_id: clientId,
client_secret: clientSecret,
workspace_id: identity.organization.id,
workspace_slug: slug,
installed_at: now,
updated_at: now,
installed_by_platform_user_id: cognitoSub,
};
if (!stored.refresh_token) {
throw new CliError(
'Linear did not return a refresh_token. The integration cannot self-renew tokens; '
+ 're-check that the Linear OAuth app permits refresh-token grants.',
);
}
const secretName = linearOauthSecretName(slug);
const oauthSecretArn = await upsertOauthSecret(sm, secretName, stored, slug);
console.log(` ✓ (${secretName})`);
// ─── Step 5: Persist registry + user-mapping rows ─────────────
const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({ region }));
// Best-effort: fetch team keys so the screenshot processor can
// prefix-route Linear issue lookups (e.g. ABCA-42 → workspace
// owning ABCA) instead of scanning every active workspace.
const teamKeys = await queryLinearTeamKeys(`Bearer ${tokenResponse.access_token}`);
await ddb.send(new PutCommand({
TableName: workspaceRegistryTable!,
Item: {
linear_workspace_id: identity.organization.id,
workspace_slug: slug,
oauth_secret_arn: oauthSecretArn,
installed_by_platform_user_id: cognitoSub,
installed_at: now,
updated_at: now,
status: 'active',
...(teamKeys.length > 0 ? { team_keys: teamKeys } : {}),
},
}));
console.log(
teamKeys.length > 0
? ` ✓ Recorded workspace in registry (team keys: ${teamKeys.join(', ')})`
: ' ✓ Recorded workspace in registry',
);
// We deliberately do NOT auto-link a user-mapping row here.
// With actor=app, Linear's `viewer` query returns the OAuth
// app's bot user (a synthetic `<uuid>@oauthapp.linear.app`
// identity), not the human admin who ran the wizard. Writing
// that mapping creates the wrong row: the bot never applies
// labels, the human applying labels is unmapped, and the
// processor drops their tasks with "no linked platform user".
// The admin self-link picker further down replaces that path.
// ─── Step 6: Webhook signing secret (per-workspace + stack-wide) ───
//
// Webhook subscriptions in Linear are workspace-scoped, and Linear
// generates a fresh signing secret per subscription. To verify
// events from N workspaces we need N signing secrets, looked up
// by orgId. We store the workspace's signing secret on its OAuth
// bundle (per-workspace path) AND mirror to the stack-wide secret
// (back-compat path) when (a) it's the first install (stack-wide
// is empty), or (b) the user explicitly asked to rotate.
//
// The webhook receiver tries per-workspace first and falls back
// to the stack-wide secret, so existing installs keep working
// without re-onboarding. Multi-workspace installs need each
// workspace to own its own per-workspace signing secret — only
// the FIRST install can populate the stack-wide one usefully.
// If stack-wide is already populated, this is either a re-run
// of setup on the SAME workspace or the FIRST workspace of a
// future multi-workspace install. Either way the stored value
// is this workspace's signing secret — lift it into the
// per-workspace bundle without prompting (auto-migration to
// the new shape). Rotation is not setup's job: use
// `bgagent linear update-webhook-secret <slug>` to rotate the
// signing secret without re-running OAuth.
const stackWideAlreadyConfigured = await isWebhookSecretConfigured(sm, webhookSecretArn!);
let webhookSigningSecret: string | undefined;
if (stackWideAlreadyConfigured) {
console.log(' ✓ Webhook signing secret already configured stack-wide (mirroring to per-workspace)');
try {
const value = await sm.send(new GetSecretValueCommand({ SecretId: webhookSecretArn! }));
if (value.SecretString && value.SecretString.startsWith('lin_wh_')) {
webhookSigningSecret = value.SecretString;
}
} catch (err) {
console.log(` ⚠ Could not read stack-wide secret to mirror: ${err instanceof Error ? err.message : String(err)}`);
}
} else {
const apiBaseUrl = config.api_url.replace(/\/+$/, '');
console.log();
console.log(' Webhook signing secret needed.');
console.log(' In Linear → Settings → API → Webhooks, create a webhook pointing at:');
console.log(` ${apiBaseUrl}/linear/webhook`);
console.log(' Subscribe to: Issues. Copy the signing secret from the webhook detail page.');
console.log();
const webhookSecret = await promptSecret('Webhook signing secret (lin_wh_…): ');
if (!webhookSecret) {
throw new CliError('Webhook signing secret is required.');
}
if (!webhookSecret.startsWith('lin_wh_')) {
throw new CliError(
'Webhook signing secrets start with \'lin_wh_\'. Got something different — re-check the Linear webhook detail page.',
);
}
// First install: stamp BOTH stack-wide (back-compat fallback
// for installs predating per-workspace signing) and the
// per-workspace OAuth bundle (the verifier's primary path).
await sm.send(new PutSecretValueCommand({
SecretId: webhookSecretArn!,
SecretString: webhookSecret,
}));
console.log(' ✓ Stored webhook signing secret (stack-wide back-compat)');
webhookSigningSecret = webhookSecret;
}
// Mirror into the per-workspace OAuth secret so the receiver can
// look it up by orgId. Re-upsert with the merged payload.
if (webhookSigningSecret) {
const merged: StoredLinearOauthToken = {
...stored,
webhook_signing_secret: webhookSigningSecret,
updated_at: new Date().toISOString(),
};
await upsertOauthSecret(sm, secretName, merged, slug);
console.log(' ✓ Mirrored signing secret to per-workspace OAuth bundle');
}
// ─── Step 7: Self-link picker ──────────────────────────────────
// With actor=app, Linear's `viewer` returns the bot user, not
// you. We can't auto-link from the OAuth dance — instead we
// show the workspace member list so you can pick yourself.
// One extra question, no separate command. Teammate linking
// is a different flow (`bgagent linear invite-user`).
console.log();
const linked = await runSelfLinkPicker({
ddb,
userMappingTable: userMappingTable!,
accessToken: tokenResponse.access_token,
workspaceId: identity.organization.id,
slug,
cognitoSub,
linkMethod: 'auto_setup_oauth',
});
// ─── Done ──────────────────────────────────────────────────────
console.log();
console.log('✅ Setup complete.');
console.log();
console.log('Next steps:');
if (!linked) {
console.log(` 1. Re-run \`bgagent linear setup ${slug}\` to retry the self-link picker,`);
console.log(' OR label a test issue and the resulting CloudWatch warning will tell you');
console.log(' your Linear UUID. (Required — without linking, your Linear-triggered tasks are dropped.)');
console.log(' 2. Onboard a Linear project to a GitHub repo:');
console.log(' bgagent linear onboard-project <linear-project-id> --repo owner/repo');
} else {
console.log(' 1. Onboard a Linear project to a GitHub repo:');
console.log(' bgagent linear onboard-project <linear-project-id> --repo owner/repo');
console.log(' 2. Add the trigger label to a Linear issue in a mapped project.');
console.log(' (To onboard teammates: `bgagent linear invite-user <slug>`.)');
}
}),
);
linear.addCommand(
new Command('add-workspace')
.description('Authorize an additional Linear workspace using the existing OAuth app + webhook secret')
.argument('<slug>', 'Linear workspace urlKey (e.g. "acme" from linear.app/acme/...)')
.option('--region <region>', 'AWS region (defaults to configured region)')
.option('--stack-name <name>', 'CloudFormation stack name', 'backgroundagent-dev')
.option('--no-browser', 'Print the authorization URL instead of opening a browser (for SSH/headless)')
.option('--no-actor-app', 'Drop actor=app from the OAuth flow (diagnostic)')
.action(async (slug: string, opts) => {
if (!SLUG_RE.test(slug)) {
throw new CliError(
`Invalid workspace slug '${slug}'. Must be 4-50 chars matching [a-zA-Z0-9_-]. `
+ 'This is the Linear urlKey, e.g. \'acme\' from linear.app/acme/...',
);
}
const config = loadConfig();
const region = opts.region || config.region;
const stackName = opts.stackName;
// ─── Stack outputs ─────────────────────────────────────────────
// Subset of `setup`'s outputs — webhook secret ARN is intentionally
// NOT required here: add-workspace assumes the initial setup wizard
// already installed it (one signing secret covers all workspaces
// sharing the same Linear OAuth app + webhook receiver URL).
const [
workspaceRegistryTable,
userMappingTable,
] = await Promise.all([
getStackOutput(region, stackName, 'LinearWorkspaceRegistryTableName'),
getStackOutput(region, stackName, 'LinearUserMappingTableName'),
]);
const missing: string[] = [];
if (!workspaceRegistryTable) missing.push('LinearWorkspaceRegistryTableName');
if (!userMappingTable) missing.push('LinearUserMappingTableName');
if (missing.length > 0) {
throw new CliError(
`Stack '${stackName}' is missing outputs ${missing.join(', ')}. `
+ 'Re-deploy with the 2.0b CDK changes (mise //cdk:deploy).',
);
}
// ─── Resolve caller identity ──────────────────────────────────
const creds = loadCredentials();
if (!creds?.id_token) {
throw new CliError('Not authenticated — run `bgagent login` first.');
}
let cognitoSub: string;
try {
cognitoSub = extractCognitoSub();
} catch (err) {
throw new CliError(
`Could not read Cognito sub from cached id_token: ${err instanceof Error ? err.message : String(err)}. `
+ 'Run `bgagent login` to refresh credentials.',
);
}
const sm = new SecretsManagerClient({ region });
const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({ region }));
// ─── Linear OAuth app credentials ──────────────────────────────
// Always prompt — never accept secrets via flags (shell history
// leak). The auto-detected client_id from an existing active
// workspace is offered as the default; user accepts with Enter
// (single OAuth app shared across workspaces) or types a new id
// (per-workspace OAuth app, e.g. when the existing app is
// private to its origin workspace).
console.log(`bgagent linear add-workspace — workspace '${slug}'`);
console.log(` region: ${region}`);
console.log();
process.stdout.write(' → Looking for an existing workspace to reuse OAuth credentials...');
const existing = await findReusableOauthAppCredentials(ddb, sm, workspaceRegistryTable!);
if (!existing) {
console.log(' ✗');
throw new CliError(
'No active Linear workspace found in the registry. '
+ 'Run `bgagent linear setup <slug>` first to install the OAuth app, '
+ 'then re-run `bgagent linear add-workspace` for additional workspaces.',
);
}
console.log(' ✓');
console.log();
console.log(' Linear OAuth credentials. Press Enter to reuse the existing app, or paste new values');
console.log(' (the existing app may be private to its origin workspace and not authorize cross-install).');
const clientId = await promptLine(' Linear Client ID', existing.clientId);
const sameAsExisting = clientId === existing.clientId;
const clientSecret = sameAsExisting
? existing.clientSecret
: (await promptSecret(' Linear Client Secret: ')).trim();
if (!clientId || !clientSecret) {
throw new CliError('Client ID and Client Secret are both required.');
}
console.log();
// ─── PKCE + browser consent ────────────────────────────────────
const pkce = generatePkce();
const state = randomState();
const useActorApp = opts.actorApp !== false;
const authorizationUrl = buildAuthorizationUrl({
clientId,
redirectUri: CALLBACK_URL,
state,
codeChallenge: pkce.codeChallenge,
actorApp: useActorApp,
});
if (!useActorApp) {
console.log(' ⚠ --no-actor-app: dropping actor=app for diagnosis. Token will not be agent-scoped.');
}
const callbackPromise = awaitOauthCallback();
console.log();
if (opts.browser !== false) {
const opened = await openBrowser(authorizationUrl);
if (opened) {
console.log(' → Opened your browser to the Linear consent screen.');
console.log(' Sign in to the workspace you want to add (use a workspace switcher if needed).');
} else {
console.log(' → Could not open browser automatically. Open this URL manually:');
console.log(` ${authorizationUrl}`);
}
} else {
console.log(' → --no-browser: open this URL manually:');
console.log(` ${authorizationUrl}`);
}
process.stdout.write(' → Waiting for browser callback...');
const callback = await callbackPromise;
console.log(' ✓');
if (callback.kind !== 'direct-oauth') {
throw new CliError(
'Localhost callback returned an AgentCore session_id, not a direct OAuth code. '
+ 'Verify Linear\'s redirect URI is set to http://localhost:8080/oauth/callback and re-run.',
);
}
if (callback.state !== state) {
throw new CliError(
`OAuth state mismatch (expected '${state}', got '${callback.state}'). `
+ 'Possible CSRF attack or stale tab — re-run add-workspace.',
);
}
// ─── Exchange code → fetch identity ────────────────────────────
process.stdout.write(' → Exchanging code for access token...');
const tokenResponse = await exchangeAuthorizationCode({
code: callback.code,
codeVerifier: pkce.codeVerifier,
redirectUri: CALLBACK_URL,
clientId,
clientSecret,
});
console.log(' ✓');
process.stdout.write(' → Querying Linear viewer + organization...');
const identity = await queryLinearIdentity(`Bearer ${tokenResponse.access_token}`);
if (!identity) {
throw new CliError(
'Linear viewer query rejected the access token. This is unexpected — token was just issued. '
+ 'Re-run `bgagent linear add-workspace` if Linear\'s API is recovering from a transient outage.',
);
}
console.log(` ✓ (${identity.organization.name ?? identity.organization.urlKey ?? identity.organization.id})`);
if (identity.organization.urlKey && identity.organization.urlKey !== slug) {
throw new CliError(
`Slug '${slug}' does not match Linear's urlKey '${identity.organization.urlKey}' for the authorized workspace. `
+ 'Re-run with the correct slug — using the wrong slug would shadow the secret name and produce a confusing registry row.',
);
}
// ─── Refuse re-install of an already-onboarded workspace ───────
// Different from `setup`, which is intentionally idempotent: the
// explicit add-workspace verb implies "new workspace", and silently
// overwriting a registry row could mask a wrong-account login.
const dupCheck = await ddb.send(new ScanCommand({
TableName: workspaceRegistryTable!,
FilterExpression: 'linear_workspace_id = :id',
ExpressionAttributeValues: { ':id': identity.organization.id },
Limit: 1,
}));
if (dupCheck.Items && dupCheck.Items.length > 0) {
throw new CliError(
`Workspace '${slug}' (${identity.organization.id}) is already in the registry. `
+ 'Use `bgagent linear setup` to re-authorize an existing workspace, or remove the registry row manually before retrying.',
);
}
// ─── Persist token to per-workspace SM ─────────────────────────
process.stdout.write(' → Storing OAuth token...');
const now = new Date().toISOString();
const stored: StoredLinearOauthToken = {
access_token: tokenResponse.access_token,
refresh_token: tokenResponse.refresh_token ?? '',
expires_at: computeExpiresAt(tokenResponse.expires_in),
scope: tokenResponse.scope,
client_id: clientId,
client_secret: clientSecret,
workspace_id: identity.organization.id,
workspace_slug: slug,
installed_at: now,
updated_at: now,
installed_by_platform_user_id: cognitoSub,
};
if (!stored.refresh_token) {
throw new CliError(
'Linear did not return a refresh_token. The integration cannot self-renew tokens; '
+ 're-check that the Linear OAuth app permits refresh-token grants.',
);
}
const secretName = linearOauthSecretName(slug);
const oauthSecretArn = await upsertOauthSecret(sm, secretName, stored, slug);
console.log(` ✓ (${secretName})`);
// ─── Persist registry + user-mapping rows ──────────────────────
// Fetch team keys for prefix-routing (see same call in `setup`).
const teamKeys = await queryLinearTeamKeys(`Bearer ${tokenResponse.access_token}`);
await ddb.send(new PutCommand({
TableName: workspaceRegistryTable!,
Item: {
linear_workspace_id: identity.organization.id,
workspace_slug: slug,
oauth_secret_arn: oauthSecretArn,
installed_by_platform_user_id: cognitoSub,