@openchamber/web 1.21.1 → 1.22.1
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.
- package/dist/assets/{CodeMirrorCommentWidgets-BGj8TJxW.js → CodeMirrorCommentWidgets-BO_2OW4E.js} +1 -1
- package/dist/assets/DiffView-CNnDxRmO.js +4 -0
- package/dist/assets/DirtyBranchSwitchDialog-jADfXQnR.js +1 -0
- package/dist/assets/FilesView-8wdiG2mj.js +17 -0
- package/dist/assets/GitView-Cv2xH-S6.js +6 -0
- package/dist/assets/{JsonTreeView-CggOsLot.js → JsonTreeView-DUiIpERC.js} +1 -1
- package/dist/assets/LinearIssuesView-CoZ7pQN5.js +1 -0
- package/dist/assets/MarkdownImageGallery-DffjmciG.js +1 -0
- package/dist/assets/MarkdownRendererImpl-DxqdYDAx.js +12 -0
- package/dist/assets/OnboardingScreen-CTZe6HZn.js +1 -0
- package/dist/assets/{PatchDiff-DJYMUiXA.js → PatchDiff-BymkP9JA.js} +1 -1
- package/dist/assets/{PierreDiffViewer-CY2bx_SB.js → PierreDiffViewer-BvwtCxW4.js} +3 -3
- package/dist/assets/{PlanView-PkiOY_9H.js → PlanView-C1qvAm7m.js} +3 -3
- package/dist/assets/SettingsView-xGONHFGS.js +28 -0
- package/dist/assets/{SettingsWindow-oyOm2fHR.js → SettingsWindow-COzgfFxM.js} +1 -1
- package/dist/assets/{ToolOutputDialog-lKyeQTPL.js → ToolOutputDialog-Dlhh_-oe.js} +6 -6
- package/dist/assets/ToolPartDiffPreview-b9joNtXH.js +8 -0
- package/dist/assets/{VirtualizedFileDiff-BP7ebDFF.js → VirtualizedFileDiff-vqW3KKo5.js} +1 -1
- package/dist/assets/WalkthroughView-D-HFgdmM.js +4 -0
- package/dist/assets/{computeVirtualFileMetrics-CZ0xPeaT.js → computeVirtualFileMetrics-DUnyszhW.js} +1 -1
- package/dist/assets/{contextPanelEmbeddedChat-C9abMBTb.js → contextPanelEmbeddedChat-CV-DwAiX.js} +1 -1
- package/dist/assets/{de-CEoCz3j6.js → de-Cv_4FoXm.js} +6 -5
- package/dist/assets/es-BIWNEbnS.js +16 -0
- package/dist/assets/{fr-CS7Csln9.js → fr-SD3OfMHJ.js} +6 -5
- package/dist/assets/index-CHUT_bDS.css +1 -0
- package/dist/assets/index-DDInLQDd.js +40 -0
- package/dist/assets/{index-CaPAjwXQ.js → index-DLiD86ge.js} +1 -1
- package/dist/assets/{isDiffPlainText-ZBvDxhVB.js → isDiffPlainText-TNageFjy.js} +1 -1
- package/dist/assets/{isFilePlainText-DiLRrkJr.js → isFilePlainText-JPmZOYSp.js} +1 -1
- package/dist/assets/{ja-vnwqLcx6.js → ja-D7I9HofF.js} +7 -6
- package/dist/assets/{ko-CXuSfZv5.js → ko-BsVJM_PQ.js} +7 -6
- package/dist/assets/{main-D5RWr6sJ.js → main-DCB4JgVe.js} +2 -2
- package/dist/assets/main-De8Z5w49.js +928 -0
- package/dist/assets/markdownCore-BoQVG5-a.js +3 -0
- package/dist/assets/{miniChat-CqR3icsk.js → miniChat-BtV7N5OF.js} +2 -2
- package/dist/assets/{mobile-RN_UTTlB.js → mobile-DZV_sfX7.js} +2 -2
- package/dist/assets/{patchFileDiff-CjRR5ESs.js → patchFileDiff-Chmiz6hq.js} +4 -4
- package/dist/assets/{pl-BJxry0Mi.js → pl-XR9Bs8Be.js} +6 -5
- package/dist/assets/pt-BR-Due4be8g.js +16 -0
- package/dist/assets/{renderElectronMiniChatApp-1wC94fQK.js → renderElectronMiniChatApp-8tXADjfl.js} +2 -2
- package/dist/assets/renderMobileApp-Cji7Hma5.js +25 -0
- package/dist/assets/runtimeEndpointReset-gWt3Lb5D.js +16 -0
- package/dist/assets/scheduledTasksApi-9e-UX6im.js +1 -0
- package/dist/assets/{shikiHighlight-fGmFkxAM.js → shikiHighlight-CRpCl7UT.js} +1 -1
- package/dist/assets/tr-DBJcAv4y.js +7 -0
- package/dist/assets/uk-COYh2BaN.js +16 -0
- package/dist/assets/{useAppFontEffects-KP8_yiGW.js → useAppFontEffects-CCgvcQ6u.js} +178 -170
- package/dist/assets/useInlineCommentController-BkfXnjNZ.js +2 -0
- package/dist/assets/useRootScrollLock-KzOUytpn.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-DrTPkHl4.js → vendor-codemirror-language-data-BxpoC5Fp.js} +2 -2
- package/dist/assets/vendor-zod-DVWEh-IS.js +39 -0
- package/dist/assets/{web-components-DOXvU-tB.js → web-components-B6QgbmTo.js} +4 -4
- package/dist/assets/zh-CN-Cjk6lzhc.js +16 -0
- package/dist/assets/{zh-TW-Dv8yyhN1.js → zh-TW-Dk0dOg03.js} +6 -5
- package/dist/index.html +5 -5
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +2 -2
- package/server/index.js +35 -4
- package/server/lib/agent-tool/runtime.js +2 -19
- package/server/lib/dev-tunnel/DOCUMENTATION.md +13 -4
- package/server/lib/dev-tunnel/runtime.js +4 -4
- package/server/lib/dev-tunnel/tunnel.test.js +20 -0
- package/server/lib/dictation/DOCUMENTATION.md +19 -6
- package/server/lib/dictation/local/model-catalog.js +220 -0
- package/server/lib/dictation/local/model-catalog.test.js +42 -0
- package/server/lib/dictation/local/sherpa-tts.js +41 -20
- package/server/lib/dictation/local/worker-process.js +2 -0
- package/server/lib/dictation/runtime.js +4 -0
- package/server/lib/dictation/service.js +27 -4
- package/server/lib/fs/DOCUMENTATION.md +4 -0
- package/server/lib/fs/routes.js +129 -0
- package/server/lib/fs/routes.test.js +219 -0
- package/server/lib/git/DOCUMENTATION.md +3 -1
- package/server/lib/git/routes.js +16 -0
- package/server/lib/git/service.js +97 -17
- package/server/lib/git/service.test.js +153 -0
- package/server/lib/linear/DOCUMENTATION.md +97 -0
- package/server/lib/linear/OAUTH-BROKER-HANDOFF.md +91 -0
- package/server/lib/linear/auth.js +436 -0
- package/server/lib/linear/auth.test.js +242 -0
- package/server/lib/linear/client.js +191 -0
- package/server/lib/linear/index.js +61 -0
- package/server/lib/linear/issues.js +499 -0
- package/server/lib/linear/issues.test.js +512 -0
- package/server/lib/linear/mapping.js +188 -0
- package/server/lib/linear/mapping.test.js +147 -0
- package/server/lib/linear/oauth.js +345 -0
- package/server/lib/linear/oauth.test.js +166 -0
- package/server/lib/linear/parse.js +23 -0
- package/server/lib/linear/routes.js +432 -0
- package/server/lib/linear/routes.test.js +661 -0
- package/server/lib/linear/status-runtime.js +64 -0
- package/server/lib/linear/status-runtime.test.js +167 -0
- package/server/lib/linear/status.js +280 -0
- package/server/lib/linear/status.test.js +271 -0
- package/server/lib/linear/teams.js +72 -0
- package/server/lib/linear/teams.test.js +94 -0
- package/server/lib/mcp-reconnect/DOCUMENTATION.md +55 -0
- package/server/lib/mcp-reconnect/runtime.js +122 -0
- package/server/lib/mcp-reconnect/runtime.test.js +140 -0
- package/server/lib/message-queue/DOCUMENTATION.md +148 -0
- package/server/lib/message-queue/runtime.js +818 -0
- package/server/lib/message-queue/runtime.test.js +426 -0
- package/server/lib/openchamber-sessions/routes.js +102 -0
- package/server/lib/openchamber-sessions/routes.test.js +88 -0
- package/server/lib/opencode/DOCUMENTATION.md +5 -1
- package/server/lib/opencode/core-routes.js +1 -0
- package/server/lib/opencode/feature-routes-runtime.js +5 -0
- package/server/lib/opencode/managed-plugin-config.js +35 -0
- package/server/lib/opencode/settings-runtime.js +2 -2
- package/server/lib/opencode/settings-runtime.test.js +29 -0
- package/server/lib/opencode/shutdown-runtime.js +2 -0
- package/server/lib/opencode/static-routes-runtime.js +3 -3
- package/server/lib/projects/project-config.js +33 -5
- package/server/lib/projects/project-config.test.js +85 -0
- package/server/lib/quota/DOCUMENTATION.md +2 -1
- package/server/lib/quota/credentials/providers.js +4 -0
- package/server/lib/quota/credentials/store.js +1 -1
- package/server/lib/quota/credentials/store.test.js +4 -4
- package/server/lib/quota/providers/exe-dev.js +75 -0
- package/server/lib/quota/providers/exe-dev.test.js +47 -0
- package/server/lib/quota/providers/index.js +7 -0
- package/server/lib/quota/providers/opencode-go.js +1 -0
- package/server/lib/quota/providers/opencode-go.test.js +5 -1
- package/server/lib/quota/routes.js +2 -0
- package/server/lib/relay/DOCUMENTATION.md +1 -1
- package/server/lib/relay/tunnel-host.js +3 -1
- package/server/lib/relay/tunnel-host.test.js +9 -1
- package/server/lib/scheduled-tasks/DOCUMENTATION.md +7 -0
- package/server/lib/security/request-security.js +21 -6
- package/server/lib/security/request-security.test.js +42 -8
- package/server/lib/session-assist/runtime.js +1 -0
- package/server/lib/session-goal/create.js +3 -1
- package/server/lib/session-goal/runtime.js +1 -0
- package/server/lib/small-model/DOCUMENTATION.md +4 -0
- package/server/lib/small-model/call.js +8 -2
- package/server/lib/small-model/call.test.js +23 -0
- package/server/lib/small-model/index.js +2 -1
- package/server/lib/small-model/routes.js +2 -1
- package/server/lib/system-prompt/runtime.js +2 -21
- package/server/lib/terminal/runtime.js +30 -7
- package/server/lib/tts/DOCUMENTATION.md +1 -0
- package/server/lib/tts/language-detect.js +210 -0
- package/server/lib/tts/language-detect.test.js +76 -0
- package/server/lib/tts/routes.js +23 -1
- package/server/lib/tts/routes.test.js +26 -0
- package/server/lib/ui-auth/ui-auth.js +4 -1
- package/server/lib/ui-auth/ui-auth.test.js +16 -0
- package/server/lib/walkthrough/index.js +1 -0
- package/dist/assets/CommitSection-DwGiXyjf.js +0 -1
- package/dist/assets/DiffView-Db6bjVv1.js +0 -4
- package/dist/assets/FilesView-DQOa7Lgz.js +0 -17
- package/dist/assets/GitView-CHzJxTi0.js +0 -6
- package/dist/assets/MarkdownImageGallery-DoZpaHev.js +0 -1
- package/dist/assets/MarkdownRendererImpl-B5Y5xCOz.js +0 -12
- package/dist/assets/OnboardingScreen-C98d69Fp.js +0 -1
- package/dist/assets/SettingsView-D-K3ELCM.js +0 -28
- package/dist/assets/ToolPartDiffPreview-C7kBQNAA.js +0 -8
- package/dist/assets/WalkthroughView-MuJodAHD.js +0 -4
- package/dist/assets/es-DwyXCqaL.js +0 -15
- package/dist/assets/index-CUKcHnUA.css +0 -1
- package/dist/assets/index-DIvDEKE-.js +0 -7
- package/dist/assets/main-DLlfDjQ_.js +0 -926
- package/dist/assets/markdownCore-CcTcLsQF.js +0 -3
- package/dist/assets/pt-BR-DxLmkhdv.js +0 -15
- package/dist/assets/renderMobileApp-ltva2Plg.js +0 -25
- package/dist/assets/runtimeEndpointReset-D6SmNZaP.js +0 -15
- package/dist/assets/scheduledTasksApi-mjMDet_H.js +0 -1
- package/dist/assets/tr-5Mk_hQ2Q.js +0 -6
- package/dist/assets/uk-ClgQjmlw.js +0 -15
- package/dist/assets/useInlineCommentController-HIjtuhxD.js +0 -2
- package/dist/assets/useRootScrollLock-BSiQ5F75.js +0 -1
- package/dist/assets/vendor-zod-BLfBSgBh.js +0 -39
- package/dist/assets/zh-CN-Ba6y8H-i.js +0 -15
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import { activateLinearAuth, getLinearAuth, setLinearAuth } from './auth.js';
|
|
6
|
+
import {
|
|
7
|
+
getLinearMappingFilePath,
|
|
8
|
+
mergeLinearMappingView,
|
|
9
|
+
readStoredLinearMapping,
|
|
10
|
+
resolveMappedProjectPath,
|
|
11
|
+
setStoredLinearMapping,
|
|
12
|
+
} from './mapping.js';
|
|
13
|
+
|
|
14
|
+
const makeTempDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-linear-mapping-'));
|
|
15
|
+
|
|
16
|
+
describe('Linear project mapping storage', () => {
|
|
17
|
+
let dataDir;
|
|
18
|
+
let previousDataDir;
|
|
19
|
+
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
previousDataDir = process.env.OPENCHAMBER_DATA_DIR;
|
|
22
|
+
dataDir = makeTempDir();
|
|
23
|
+
process.env.OPENCHAMBER_DATA_DIR = dataDir;
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
afterEach(() => {
|
|
27
|
+
if (previousDataDir === undefined) {
|
|
28
|
+
delete process.env.OPENCHAMBER_DATA_DIR;
|
|
29
|
+
} else {
|
|
30
|
+
process.env.OPENCHAMBER_DATA_DIR = previousDataDir;
|
|
31
|
+
}
|
|
32
|
+
fs.rmSync(dataDir, { recursive: true, force: true });
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('treats a missing file as empty mapping, not a failure', () => {
|
|
36
|
+
expect(fs.existsSync(getLinearMappingFilePath())).toBe(false);
|
|
37
|
+
expect(readStoredLinearMapping()).toEqual({
|
|
38
|
+
defaultProjectPath: null,
|
|
39
|
+
teamProjectPaths: {},
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('round-trips a default project and per-team paths', () => {
|
|
44
|
+
const written = setStoredLinearMapping({
|
|
45
|
+
defaultProjectPath: '/Users/ada/openchamber',
|
|
46
|
+
teamProjectPaths: {
|
|
47
|
+
'team-eng': '/Users/ada/eng',
|
|
48
|
+
'team-empty': ' ',
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
expect(written).toEqual({
|
|
52
|
+
defaultProjectPath: '/Users/ada/openchamber',
|
|
53
|
+
teamProjectPaths: { 'team-eng': '/Users/ada/eng' },
|
|
54
|
+
});
|
|
55
|
+
expect(readStoredLinearMapping()).toEqual(written);
|
|
56
|
+
expect(fs.statSync(getLinearMappingFilePath()).mode & 0o777).toBe(0o600);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('replaces the previous mapping on write', () => {
|
|
60
|
+
setStoredLinearMapping({
|
|
61
|
+
defaultProjectPath: '/old',
|
|
62
|
+
teamProjectPaths: { 'team-eng': '/eng' },
|
|
63
|
+
});
|
|
64
|
+
const next = setStoredLinearMapping({
|
|
65
|
+
defaultProjectPath: null,
|
|
66
|
+
teamProjectPaths: {},
|
|
67
|
+
});
|
|
68
|
+
expect(next).toEqual({ defaultProjectPath: null, teamProjectPaths: {} });
|
|
69
|
+
expect(readStoredLinearMapping()).toEqual(next);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('keeps tokens when a mapping write is rejected', () => {
|
|
73
|
+
setLinearAuth({
|
|
74
|
+
accessToken: 'access-keep',
|
|
75
|
+
refreshToken: 'refresh-keep',
|
|
76
|
+
expiresAt: Date.now() + 60_000,
|
|
77
|
+
});
|
|
78
|
+
setStoredLinearMapping({
|
|
79
|
+
defaultProjectPath: '/keep',
|
|
80
|
+
teamProjectPaths: { 'team-eng': '/eng' },
|
|
81
|
+
});
|
|
82
|
+
expect(() => setStoredLinearMapping(null)).toThrow(/object/);
|
|
83
|
+
expect(readStoredLinearMapping()).toEqual({
|
|
84
|
+
defaultProjectPath: '/keep',
|
|
85
|
+
teamProjectPaths: { 'team-eng': '/eng' },
|
|
86
|
+
});
|
|
87
|
+
expect(getLinearAuth().accessToken).toBe('access-keep');
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('rejects a malformed mapping file instead of treating it as empty', () => {
|
|
91
|
+
fs.writeFileSync(getLinearMappingFilePath(), '{not-json', 'utf8');
|
|
92
|
+
expect(() => readStoredLinearMapping()).toThrow(/malformed/);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('merges live teams onto stored paths and resolves team then default', () => {
|
|
96
|
+
const stored = {
|
|
97
|
+
defaultProjectPath: '/default',
|
|
98
|
+
teamProjectPaths: { 'team-eng': '/eng' },
|
|
99
|
+
};
|
|
100
|
+
const view = mergeLinearMappingView(stored, [
|
|
101
|
+
{ id: 'team-eng', key: 'ENG', name: 'Engineering' },
|
|
102
|
+
{ id: 'team-des', key: 'DES', name: 'Design' },
|
|
103
|
+
]);
|
|
104
|
+
expect(view).toEqual({
|
|
105
|
+
defaultProjectPath: '/default',
|
|
106
|
+
teams: [
|
|
107
|
+
{ id: 'team-eng', key: 'ENG', name: 'Engineering', projectPath: '/eng' },
|
|
108
|
+
{ id: 'team-des', key: 'DES', name: 'Design', projectPath: null },
|
|
109
|
+
],
|
|
110
|
+
});
|
|
111
|
+
expect(resolveMappedProjectPath(view, { id: 'team-eng', key: 'ENG' })).toBe('/eng');
|
|
112
|
+
expect(resolveMappedProjectPath(view, { id: 'team-des', key: 'DES' })).toBe('/default');
|
|
113
|
+
expect(resolveMappedProjectPath(view, null)).toBe('/default');
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('keeps mapping slices isolated per workspace', () => {
|
|
117
|
+
setLinearAuth({
|
|
118
|
+
accessToken: 'access-a',
|
|
119
|
+
user: { id: 'user-a', name: 'Ada' },
|
|
120
|
+
organization: { id: 'org-a', name: 'Alpha', urlKey: 'alpha' },
|
|
121
|
+
});
|
|
122
|
+
setStoredLinearMapping({
|
|
123
|
+
defaultProjectPath: '/alpha',
|
|
124
|
+
teamProjectPaths: { 'team-a': '/alpha-eng' },
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
setLinearAuth({
|
|
128
|
+
accessToken: 'access-b',
|
|
129
|
+
user: { id: 'user-b', name: 'Ben' },
|
|
130
|
+
organization: { id: 'org-b', name: 'Beta', urlKey: 'beta' },
|
|
131
|
+
});
|
|
132
|
+
setStoredLinearMapping({
|
|
133
|
+
defaultProjectPath: '/beta',
|
|
134
|
+
teamProjectPaths: {},
|
|
135
|
+
});
|
|
136
|
+
expect(readStoredLinearMapping()).toEqual({
|
|
137
|
+
defaultProjectPath: '/beta',
|
|
138
|
+
teamProjectPaths: {},
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
expect(activateLinearAuth('org-a')).toBe(true);
|
|
142
|
+
expect(readStoredLinearMapping()).toEqual({
|
|
143
|
+
defaultProjectPath: '/alpha',
|
|
144
|
+
teamProjectPaths: { 'team-a': '/alpha-eng' },
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
});
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import {
|
|
3
|
+
getLinearClientId,
|
|
4
|
+
getLinearClientSecret,
|
|
5
|
+
getLinearBrokerUrl,
|
|
6
|
+
getLinearRedirectUri,
|
|
7
|
+
getLinearScopes,
|
|
8
|
+
} from './auth.js';
|
|
9
|
+
import { isPlainObject, isString, readFiniteNumber, readTrimmedString } from './parse.js';
|
|
10
|
+
|
|
11
|
+
export const LINEAR_AUTHORIZE_URL = 'https://linear.app/oauth/authorize';
|
|
12
|
+
export const LINEAR_TOKEN_URL = 'https://api.linear.app/oauth/token';
|
|
13
|
+
export const LINEAR_REVOKE_URL = 'https://api.linear.app/oauth/revoke';
|
|
14
|
+
export const PENDING_AUTHORIZATION_TTL_MS = 10 * 60_000;
|
|
15
|
+
|
|
16
|
+
const pendingByState = new Map();
|
|
17
|
+
const brokerPollsByState = new Map();
|
|
18
|
+
|
|
19
|
+
export class LinearOAuthError extends Error {
|
|
20
|
+
constructor(message, code = 'LINEAR_OAUTH_FAILED') {
|
|
21
|
+
super(message);
|
|
22
|
+
this.name = 'LinearOAuthError';
|
|
23
|
+
this.code = code;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function createPkcePair() {
|
|
28
|
+
const verifier = crypto.randomBytes(32).toString('base64url');
|
|
29
|
+
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
|
|
30
|
+
return { verifier, challenge };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function pruneExpiredPending(now = Date.now()) {
|
|
34
|
+
for (const [state, entry] of pendingByState.entries()) {
|
|
35
|
+
if (!entry || entry.expiresAt <= now) {
|
|
36
|
+
pendingByState.delete(state);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function normalizeScope(scope) {
|
|
42
|
+
if (isString(scope)) {
|
|
43
|
+
return scope.trim();
|
|
44
|
+
}
|
|
45
|
+
if (Array.isArray(scope)) {
|
|
46
|
+
return scope.filter((item) => isString(item) && item.trim()).join(',');
|
|
47
|
+
}
|
|
48
|
+
return '';
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function readExpiresAt(expiresIn, now = Date.now()) {
|
|
52
|
+
const seconds = readFiniteNumber(expiresIn);
|
|
53
|
+
if (seconds == null || seconds <= 0) {
|
|
54
|
+
return now + 24 * 60 * 60 * 1000;
|
|
55
|
+
}
|
|
56
|
+
return now + Math.floor(seconds) * 1000;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function parseTokenPayload(payload) {
|
|
60
|
+
if (!isPlainObject(payload)) {
|
|
61
|
+
throw new LinearOAuthError('Linear token response was empty');
|
|
62
|
+
}
|
|
63
|
+
if (readTrimmedString(payload.error)) {
|
|
64
|
+
throw new LinearOAuthError(
|
|
65
|
+
readTrimmedString(payload.error_description) || readTrimmedString(payload.error),
|
|
66
|
+
readTrimmedString(payload.error).toUpperCase(),
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
const accessToken = readTrimmedString(payload.access_token);
|
|
70
|
+
if (!accessToken) {
|
|
71
|
+
throw new LinearOAuthError('Linear token response was missing access_token');
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
accessToken,
|
|
75
|
+
refreshToken: readTrimmedString(payload.refresh_token) || null,
|
|
76
|
+
tokenType: readTrimmedString(payload.token_type) || 'bearer',
|
|
77
|
+
expiresAt: readExpiresAt(payload.expires_in),
|
|
78
|
+
scope: normalizeScope(payload.scope),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function postForm(url, body) {
|
|
83
|
+
const response = await fetch(url, {
|
|
84
|
+
method: 'POST',
|
|
85
|
+
headers: {
|
|
86
|
+
Accept: 'application/json',
|
|
87
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
88
|
+
},
|
|
89
|
+
body: new URLSearchParams(body).toString(),
|
|
90
|
+
});
|
|
91
|
+
const payload = await response.json().catch(() => null);
|
|
92
|
+
if (!response.ok) {
|
|
93
|
+
const description = isPlainObject(payload)
|
|
94
|
+
? (readTrimmedString(payload.error_description) || readTrimmedString(payload.error))
|
|
95
|
+
: '';
|
|
96
|
+
const error = new LinearOAuthError(
|
|
97
|
+
description || `Linear token request failed (${response.status})`,
|
|
98
|
+
readTrimmedString(payload?.error).toUpperCase() || 'LINEAR_OAUTH_FAILED',
|
|
99
|
+
);
|
|
100
|
+
error.status = response.status;
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
return parseTokenPayload(payload);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function readJsonResponse(response, fallbackMessage) {
|
|
107
|
+
const payload = await response.json().catch(() => null);
|
|
108
|
+
if (!response.ok) {
|
|
109
|
+
const message = isPlainObject(payload) && readTrimmedString(payload.error)
|
|
110
|
+
? readTrimmedString(payload.error)
|
|
111
|
+
: `${fallbackMessage} (${response.status})`;
|
|
112
|
+
const error = new LinearOAuthError(message, 'LINEAR_BROKER_FAILED');
|
|
113
|
+
error.status = response.status;
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
if (!isPlainObject(payload)) {
|
|
117
|
+
throw new LinearOAuthError(`${fallbackMessage}: invalid response`, 'LINEAR_BROKER_FAILED');
|
|
118
|
+
}
|
|
119
|
+
return payload;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function brokerCallbackUrl(brokerUrl) {
|
|
123
|
+
return `${brokerUrl.replace(/\/+$/, '')}/callback`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function registerBrokerTransaction({ brokerUrl, state, claimSecret }) {
|
|
127
|
+
const response = await fetch(`${brokerUrl}/start`, {
|
|
128
|
+
method: 'POST',
|
|
129
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
|
130
|
+
body: JSON.stringify({ state, claimSecret }),
|
|
131
|
+
});
|
|
132
|
+
const payload = await readJsonResponse(response, 'Could not start Linear authorization broker');
|
|
133
|
+
const redirectUri = readTrimmedString(payload.redirectUri);
|
|
134
|
+
if (!redirectUri || redirectUri !== brokerCallbackUrl(brokerUrl)) {
|
|
135
|
+
throw new LinearOAuthError('Linear authorization broker returned an unexpected callback URL', 'LINEAR_BROKER_FAILED');
|
|
136
|
+
}
|
|
137
|
+
return redirectUri;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function startAuthorization({ origin } = {}) {
|
|
141
|
+
const clientId = getLinearClientId();
|
|
142
|
+
if (!clientId) {
|
|
143
|
+
throw new LinearOAuthError(
|
|
144
|
+
'Linear OAuth client not configured. Set OPENCHAMBER_LINEAR_CLIENT_ID.',
|
|
145
|
+
'LINEAR_CLIENT_ID_MISSING',
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
pruneExpiredPending();
|
|
150
|
+
const { verifier, challenge } = createPkcePair();
|
|
151
|
+
const state = crypto.randomBytes(32).toString('base64url');
|
|
152
|
+
const brokerUrl = getLinearBrokerUrl();
|
|
153
|
+
const configuredRedirectUri = getLinearRedirectUri();
|
|
154
|
+
const usesBroker = configuredRedirectUri === brokerCallbackUrl(brokerUrl);
|
|
155
|
+
const claimSecret = usesBroker ? crypto.randomBytes(32).toString('base64url') : null;
|
|
156
|
+
const redirectUri = usesBroker
|
|
157
|
+
? await registerBrokerTransaction({ brokerUrl, state, claimSecret })
|
|
158
|
+
: configuredRedirectUri;
|
|
159
|
+
const scope = getLinearScopes();
|
|
160
|
+
pendingByState.set(state, {
|
|
161
|
+
codeVerifier: verifier,
|
|
162
|
+
redirectUri,
|
|
163
|
+
origin: origin === 'desktop' ? 'desktop' : 'web',
|
|
164
|
+
broker: usesBroker ? { url: brokerUrl, claimSecret } : null,
|
|
165
|
+
expiresAt: Date.now() + PENDING_AUTHORIZATION_TTL_MS,
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
const url = new URL(LINEAR_AUTHORIZE_URL);
|
|
169
|
+
url.searchParams.set('response_type', 'code');
|
|
170
|
+
url.searchParams.set('client_id', clientId);
|
|
171
|
+
url.searchParams.set('redirect_uri', redirectUri);
|
|
172
|
+
url.searchParams.set('scope', scope);
|
|
173
|
+
url.searchParams.set('state', state);
|
|
174
|
+
url.searchParams.set('code_challenge', challenge);
|
|
175
|
+
url.searchParams.set('code_challenge_method', 'S256');
|
|
176
|
+
url.searchParams.set('actor', 'user');
|
|
177
|
+
url.searchParams.set('prompt', 'consent');
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
authorizationUrl: url.toString(),
|
|
181
|
+
expiresIn: Math.floor(PENDING_AUTHORIZATION_TTL_MS / 1000),
|
|
182
|
+
scope,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function pollBrokerState(state, pending) {
|
|
187
|
+
const response = await fetch(`${pending.broker.url}/poll`, {
|
|
188
|
+
method: 'POST',
|
|
189
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
|
190
|
+
body: JSON.stringify({ state, claimSecret: pending.broker.claimSecret }),
|
|
191
|
+
});
|
|
192
|
+
if (response.status === 202) {
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
const payload = await readJsonResponse(response, 'Could not read Linear authorization result');
|
|
196
|
+
const status = readTrimmedString(payload.status);
|
|
197
|
+
if (status === 'complete') {
|
|
198
|
+
const result = await consumeAuthorizationCallback({ code: payload.code, state });
|
|
199
|
+
return {
|
|
200
|
+
...result,
|
|
201
|
+
brokerReceipt: { state, ...pending.broker },
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
if (status === 'failed') {
|
|
205
|
+
return consumeAuthorizationCallback({
|
|
206
|
+
state,
|
|
207
|
+
error: payload.error,
|
|
208
|
+
errorDescription: payload.errorDescription,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
throw new LinearOAuthError('Linear authorization broker returned an unexpected result', 'LINEAR_BROKER_FAILED');
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export async function completeAuthorizationBroker(receipt) {
|
|
215
|
+
if (!receipt?.url || !receipt?.state || !receipt?.claimSecret) return false;
|
|
216
|
+
const response = await fetch(`${receipt.url}/complete`, {
|
|
217
|
+
method: 'POST',
|
|
218
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
|
219
|
+
body: JSON.stringify({ state: receipt.state, claimSecret: receipt.claimSecret }),
|
|
220
|
+
});
|
|
221
|
+
if (!response.ok) {
|
|
222
|
+
throw new LinearOAuthError(`Could not acknowledge Linear authorization result (${response.status})`, 'LINEAR_BROKER_FAILED');
|
|
223
|
+
}
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export async function pollAuthorizationBroker() {
|
|
228
|
+
pruneExpiredPending();
|
|
229
|
+
for (const [state, pending] of pendingByState.entries()) {
|
|
230
|
+
if (!pending?.broker) continue;
|
|
231
|
+
let poll = brokerPollsByState.get(state);
|
|
232
|
+
if (!poll) {
|
|
233
|
+
poll = pollBrokerState(state, pending).finally(() => brokerPollsByState.delete(state));
|
|
234
|
+
brokerPollsByState.set(state, poll);
|
|
235
|
+
}
|
|
236
|
+
const result = await poll;
|
|
237
|
+
if (result) return result;
|
|
238
|
+
}
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function failAuthorization(message, code, origin) {
|
|
243
|
+
const error = new LinearOAuthError(message, code);
|
|
244
|
+
if (origin) {
|
|
245
|
+
error.origin = origin;
|
|
246
|
+
}
|
|
247
|
+
return error;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export async function consumeAuthorizationCallback({ code, state, error, errorDescription }) {
|
|
251
|
+
pruneExpiredPending();
|
|
252
|
+
const pending = readTrimmedString(state) ? pendingByState.get(state) : null;
|
|
253
|
+
|
|
254
|
+
if (readTrimmedString(error)) {
|
|
255
|
+
if (readTrimmedString(state)) pendingByState.delete(state);
|
|
256
|
+
throw failAuthorization(
|
|
257
|
+
readTrimmedString(errorDescription) || readTrimmedString(error),
|
|
258
|
+
readTrimmedString(error).toUpperCase(),
|
|
259
|
+
pending?.origin,
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
if (!readTrimmedString(code)) {
|
|
263
|
+
if (readTrimmedString(state)) pendingByState.delete(state);
|
|
264
|
+
throw failAuthorization(
|
|
265
|
+
'Linear did not return an authorization code.',
|
|
266
|
+
'MISSING_CODE',
|
|
267
|
+
pending?.origin,
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
if (!pending?.codeVerifier) {
|
|
271
|
+
throw failAuthorization(
|
|
272
|
+
'This authorization session has expired or is unknown to the running app. Return to OpenChamber and click Connect again.',
|
|
273
|
+
'UNKNOWN_STATE',
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const body = {
|
|
278
|
+
grant_type: 'authorization_code',
|
|
279
|
+
code: code.trim(),
|
|
280
|
+
redirect_uri: pending.redirectUri,
|
|
281
|
+
client_id: getLinearClientId(),
|
|
282
|
+
code_verifier: pending.codeVerifier,
|
|
283
|
+
};
|
|
284
|
+
const clientSecret = getLinearClientSecret();
|
|
285
|
+
if (clientSecret) {
|
|
286
|
+
body.client_secret = clientSecret;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
try {
|
|
290
|
+
const tokens = await postForm(LINEAR_TOKEN_URL, body);
|
|
291
|
+
pendingByState.delete(state);
|
|
292
|
+
return {
|
|
293
|
+
...tokens,
|
|
294
|
+
origin: pending.origin,
|
|
295
|
+
};
|
|
296
|
+
} catch (caught) {
|
|
297
|
+
if (caught instanceof Error) {
|
|
298
|
+
caught.origin = pending.origin;
|
|
299
|
+
}
|
|
300
|
+
throw caught;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export async function refreshAccessToken(refreshToken) {
|
|
305
|
+
const token = readTrimmedString(refreshToken);
|
|
306
|
+
if (!token) {
|
|
307
|
+
throw new LinearOAuthError('refresh_token is required', 'MISSING_REFRESH_TOKEN');
|
|
308
|
+
}
|
|
309
|
+
const body = {
|
|
310
|
+
grant_type: 'refresh_token',
|
|
311
|
+
refresh_token: token,
|
|
312
|
+
client_id: getLinearClientId(),
|
|
313
|
+
};
|
|
314
|
+
const clientSecret = getLinearClientSecret();
|
|
315
|
+
if (clientSecret) {
|
|
316
|
+
body.client_secret = clientSecret;
|
|
317
|
+
}
|
|
318
|
+
return postForm(LINEAR_TOKEN_URL, body);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
export async function revokeToken(token, tokenTypeHint) {
|
|
322
|
+
const value = readTrimmedString(token);
|
|
323
|
+
if (!value) {
|
|
324
|
+
return false;
|
|
325
|
+
}
|
|
326
|
+
const body = { token: value };
|
|
327
|
+
if (tokenTypeHint === 'access_token' || tokenTypeHint === 'refresh_token') {
|
|
328
|
+
body.token_type_hint = tokenTypeHint;
|
|
329
|
+
}
|
|
330
|
+
try {
|
|
331
|
+
const response = await fetch(LINEAR_REVOKE_URL, {
|
|
332
|
+
method: 'POST',
|
|
333
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
334
|
+
body: new URLSearchParams(body).toString(),
|
|
335
|
+
});
|
|
336
|
+
return response.status === 200;
|
|
337
|
+
} catch {
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export function clearPendingAuthorizationsForTests() {
|
|
343
|
+
pendingByState.clear();
|
|
344
|
+
brokerPollsByState.clear();
|
|
345
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import {
|
|
6
|
+
startAuthorization,
|
|
7
|
+
consumeAuthorizationCallback,
|
|
8
|
+
pollAuthorizationBroker,
|
|
9
|
+
completeAuthorizationBroker,
|
|
10
|
+
refreshAccessToken,
|
|
11
|
+
clearPendingAuthorizationsForTests,
|
|
12
|
+
} from './oauth.js';
|
|
13
|
+
|
|
14
|
+
const makeTempDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-linear-oauth-'));
|
|
15
|
+
|
|
16
|
+
describe('Linear OAuth PKCE', () => {
|
|
17
|
+
let dataDir;
|
|
18
|
+
let previousDataDir;
|
|
19
|
+
let previousPort;
|
|
20
|
+
let previousRedirect;
|
|
21
|
+
|
|
22
|
+
beforeEach(() => {
|
|
23
|
+
previousDataDir = process.env.OPENCHAMBER_DATA_DIR;
|
|
24
|
+
previousPort = process.env.OPENCHAMBER_PORT;
|
|
25
|
+
previousRedirect = process.env.OPENCHAMBER_LINEAR_REDIRECT_URI;
|
|
26
|
+
dataDir = makeTempDir();
|
|
27
|
+
process.env.OPENCHAMBER_DATA_DIR = dataDir;
|
|
28
|
+
process.env.OPENCHAMBER_PORT = '3001';
|
|
29
|
+
delete process.env.OPENCHAMBER_LINEAR_CLIENT_ID;
|
|
30
|
+
process.env.OPENCHAMBER_LINEAR_REDIRECT_URI = 'http://127.0.0.1:3001/linear/oauth/callback';
|
|
31
|
+
clearPendingAuthorizationsForTests();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
afterEach(() => {
|
|
35
|
+
vi.unstubAllGlobals();
|
|
36
|
+
clearPendingAuthorizationsForTests();
|
|
37
|
+
restoreEnv('OPENCHAMBER_DATA_DIR', previousDataDir);
|
|
38
|
+
restoreEnv('OPENCHAMBER_PORT', previousPort);
|
|
39
|
+
restoreEnv('OPENCHAMBER_LINEAR_REDIRECT_URI', previousRedirect);
|
|
40
|
+
fs.rmSync(dataDir, { recursive: true, force: true });
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('creates an S256 authorize URL and stores a pending verifier', async () => {
|
|
44
|
+
const started = await startAuthorization({ origin: 'desktop' });
|
|
45
|
+
const url = new URL(started.authorizationUrl);
|
|
46
|
+
expect(url.origin + url.pathname).toBe('https://linear.app/oauth/authorize');
|
|
47
|
+
expect(url.searchParams.get('client_id')).toBe('91bbe26a69a2c8568d3683f1e01e776c');
|
|
48
|
+
expect(url.searchParams.get('redirect_uri')).toBe('http://127.0.0.1:3001/linear/oauth/callback');
|
|
49
|
+
expect(url.searchParams.get('code_challenge_method')).toBe('S256');
|
|
50
|
+
expect(url.searchParams.get('code_challenge')).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
|
51
|
+
expect(url.searchParams.get('actor')).toBe('user');
|
|
52
|
+
expect(url.searchParams.get('prompt')).toBe('consent');
|
|
53
|
+
expect(started.scope).toBe('read,write,comments:create');
|
|
54
|
+
expect(started.expiresIn).toBe(600);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('refuses a callback whose state was never started', async () => {
|
|
58
|
+
const tokenFetch = vi.fn();
|
|
59
|
+
vi.stubGlobal('fetch', tokenFetch);
|
|
60
|
+
await expect(consumeAuthorizationCallback({
|
|
61
|
+
code: 'attacker-code',
|
|
62
|
+
state: 'forged',
|
|
63
|
+
})).rejects.toMatchObject({ code: 'UNKNOWN_STATE' });
|
|
64
|
+
expect(tokenFetch).not.toHaveBeenCalled();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('exchanges a matching code with the original PKCE verifier', async () => {
|
|
68
|
+
const started = await startAuthorization({ origin: 'web' });
|
|
69
|
+
const state = new URL(started.authorizationUrl).searchParams.get('state');
|
|
70
|
+
const tokenFetch = vi.fn(async () => new Response(JSON.stringify({
|
|
71
|
+
access_token: 'access-1',
|
|
72
|
+
refresh_token: 'refresh-1',
|
|
73
|
+
token_type: 'Bearer',
|
|
74
|
+
expires_in: 86399,
|
|
75
|
+
scope: 'read,write,comments:create',
|
|
76
|
+
}), { status: 200 }));
|
|
77
|
+
vi.stubGlobal('fetch', tokenFetch);
|
|
78
|
+
|
|
79
|
+
const result = await consumeAuthorizationCallback({ code: 'auth-code', state });
|
|
80
|
+
expect(result.accessToken).toBe('access-1');
|
|
81
|
+
expect(result.refreshToken).toBe('refresh-1');
|
|
82
|
+
expect(result.origin).toBe('web');
|
|
83
|
+
|
|
84
|
+
expect(tokenFetch).toHaveBeenCalledTimes(1);
|
|
85
|
+
const [url, init] = tokenFetch.mock.calls[0];
|
|
86
|
+
expect(String(url)).toBe('https://api.linear.app/oauth/token');
|
|
87
|
+
expect(init.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
|
|
88
|
+
const body = new URLSearchParams(init.body);
|
|
89
|
+
expect(body.get('grant_type')).toBe('authorization_code');
|
|
90
|
+
expect(body.get('code')).toBe('auth-code');
|
|
91
|
+
expect(body.get('code_verifier')).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
|
92
|
+
expect(body.get('client_secret')).toBeNull();
|
|
93
|
+
|
|
94
|
+
await expect(consumeAuthorizationCallback({ code: 'auth-code', state })).rejects.toMatchObject({
|
|
95
|
+
code: 'UNKNOWN_STATE',
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('persists a rotated refresh token from Linear', async () => {
|
|
100
|
+
const tokenFetch = vi.fn(async () => new Response(JSON.stringify({
|
|
101
|
+
access_token: 'access-2',
|
|
102
|
+
refresh_token: 'refresh-2',
|
|
103
|
+
token_type: 'Bearer',
|
|
104
|
+
expires_in: 86399,
|
|
105
|
+
}), { status: 200 }));
|
|
106
|
+
vi.stubGlobal('fetch', tokenFetch);
|
|
107
|
+
const tokens = await refreshAccessToken('refresh-1');
|
|
108
|
+
expect(tokens.accessToken).toBe('access-2');
|
|
109
|
+
expect(tokens.refreshToken).toBe('refresh-2');
|
|
110
|
+
const body = new URLSearchParams(tokenFetch.mock.calls[0][1].body);
|
|
111
|
+
expect(body.get('grant_type')).toBe('refresh_token');
|
|
112
|
+
expect(body.get('refresh_token')).toBe('refresh-1');
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('claims a broker callback and exchanges it locally with PKCE', async () => {
|
|
116
|
+
delete process.env.OPENCHAMBER_LINEAR_REDIRECT_URI;
|
|
117
|
+
const brokerAndTokenFetch = vi.fn(async (url, init) => {
|
|
118
|
+
const target = String(url);
|
|
119
|
+
if (target.endsWith('/start')) {
|
|
120
|
+
const body = JSON.parse(init.body);
|
|
121
|
+
expect(body.state).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
|
122
|
+
expect(body.claimSecret).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
|
123
|
+
return new Response(JSON.stringify({
|
|
124
|
+
redirectUri: 'https://api.openchamber.dev/v1/oauth/linear/callback',
|
|
125
|
+
expiresIn: 600,
|
|
126
|
+
}), { status: 200 });
|
|
127
|
+
}
|
|
128
|
+
if (target.endsWith('/poll')) {
|
|
129
|
+
return new Response(JSON.stringify({ status: 'complete', code: 'broker-code' }), { status: 200 });
|
|
130
|
+
}
|
|
131
|
+
if (target.endsWith('/complete')) {
|
|
132
|
+
return new Response(JSON.stringify({ ok: true }), { status: 200 });
|
|
133
|
+
}
|
|
134
|
+
if (target === 'https://api.linear.app/oauth/token') {
|
|
135
|
+
const body = new URLSearchParams(init.body);
|
|
136
|
+
expect(body.get('code')).toBe('broker-code');
|
|
137
|
+
expect(body.get('redirect_uri')).toBe('https://api.openchamber.dev/v1/oauth/linear/callback');
|
|
138
|
+
expect(body.get('code_verifier')).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
|
139
|
+
return new Response(JSON.stringify({
|
|
140
|
+
access_token: 'broker-access',
|
|
141
|
+
refresh_token: 'broker-refresh',
|
|
142
|
+
expires_in: 86399,
|
|
143
|
+
}), { status: 200 });
|
|
144
|
+
}
|
|
145
|
+
throw new Error(`unexpected fetch: ${target}`);
|
|
146
|
+
});
|
|
147
|
+
vi.stubGlobal('fetch', brokerAndTokenFetch);
|
|
148
|
+
|
|
149
|
+
const started = await startAuthorization({ origin: 'desktop' });
|
|
150
|
+
const authorizationUrl = new URL(started.authorizationUrl);
|
|
151
|
+
expect(authorizationUrl.searchParams.get('redirect_uri')).toBe('https://api.openchamber.dev/v1/oauth/linear/callback');
|
|
152
|
+
|
|
153
|
+
const result = await pollAuthorizationBroker();
|
|
154
|
+
expect(result).toMatchObject({ accessToken: 'broker-access', origin: 'desktop' });
|
|
155
|
+
await expect(completeAuthorizationBroker(result.brokerReceipt)).resolves.toBe(true);
|
|
156
|
+
expect(brokerAndTokenFetch).toHaveBeenCalledTimes(4);
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
function restoreEnv(name, previous) {
|
|
161
|
+
if (previous === undefined) {
|
|
162
|
+
delete process.env[name];
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
process.env[name] = previous;
|
|
166
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export function isString(value) {
|
|
2
|
+
return Object.prototype.toString.call(value) === '[object String]';
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function isPlainObject(value) {
|
|
6
|
+
if (value == null || Array.isArray(value)) {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
return Object.getPrototypeOf(value) === Object.prototype;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function readTrimmedString(value) {
|
|
13
|
+
return isString(value) && value.trim() ? value.trim() : '';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function readFiniteNumber(value) {
|
|
17
|
+
return Number.isFinite(value) ? value : null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function readEnv(name) {
|
|
21
|
+
const raw = process.env[name];
|
|
22
|
+
return raw ? raw.trim() : '';
|
|
23
|
+
}
|