@baukit/suite-client 0.0.0-stage → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +73 -2
  3. package/dist/api.d.ts +103 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +67 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/authorize.d.ts +48 -0
  8. package/dist/authorize.d.ts.map +1 -0
  9. package/dist/authorize.js +123 -0
  10. package/dist/authorize.js.map +1 -0
  11. package/dist/cjs/package.json +1 -0
  12. package/dist/cjs/peers.d.ts +14 -0
  13. package/dist/cjs/peers.d.ts.map +1 -0
  14. package/dist/cjs/peers.js +63 -0
  15. package/dist/cjs/peers.js.map +1 -0
  16. package/dist/connected.d.ts +29 -0
  17. package/dist/connected.d.ts.map +1 -0
  18. package/dist/connected.js +51 -0
  19. package/dist/connected.js.map +1 -0
  20. package/dist/index.d.ts +9 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +9 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/linked.d.ts +28 -0
  25. package/dist/linked.d.ts.map +1 -0
  26. package/dist/linked.js +50 -0
  27. package/dist/linked.js.map +1 -0
  28. package/dist/messages.d.ts +455 -0
  29. package/dist/messages.d.ts.map +1 -0
  30. package/dist/messages.js +279 -0
  31. package/dist/messages.js.map +1 -0
  32. package/dist/navigation.d.ts +24 -0
  33. package/dist/navigation.d.ts.map +1 -0
  34. package/dist/navigation.js +80 -0
  35. package/dist/navigation.js.map +1 -0
  36. package/dist/peers.d.ts +14 -0
  37. package/dist/peers.d.ts.map +1 -0
  38. package/dist/peers.js +59 -0
  39. package/dist/peers.js.map +1 -0
  40. package/dist/session.d.ts +26 -0
  41. package/dist/session.d.ts.map +1 -0
  42. package/dist/session.js +88 -0
  43. package/dist/session.js.map +1 -0
  44. package/dist/urls.d.ts +17 -0
  45. package/dist/urls.d.ts.map +1 -0
  46. package/dist/urls.js +46 -0
  47. package/dist/urls.js.map +1 -0
  48. package/package.json +61 -4
  49. package/src/api.ts +139 -0
  50. package/src/authorize.ts +141 -0
  51. package/src/client.test.ts +575 -0
  52. package/src/connected.ts +54 -0
  53. package/src/index.ts +8 -0
  54. package/src/linked.ts +56 -0
  55. package/src/messages.ts +365 -0
  56. package/src/navigation.test.ts +99 -0
  57. package/src/navigation.ts +94 -0
  58. package/src/peers.test.ts +85 -0
  59. package/src/peers.ts +77 -0
  60. package/src/session.ts +88 -0
  61. package/src/urls.ts +58 -0
package/src/peers.ts ADDED
@@ -0,0 +1,77 @@
1
+ /** Embedded peer metadata. Products own the peers file. */
2
+ export interface PeerMetadata {
3
+ readonly id: string;
4
+ readonly scheme: string;
5
+ readonly displayName: string;
6
+ readonly emits: readonly string[];
7
+ readonly accepts: readonly string[];
8
+ readonly rewardModes: readonly ('native' | 'source_xp' | 'off')[];
9
+ }
10
+
11
+ const MAX_APP_ID_LENGTH = 64;
12
+ const PEER_FIELDS = ['id', 'scheme', 'displayName', 'emits', 'accepts', 'rewardModes'];
13
+
14
+ function requireFields(value: unknown, fields: readonly string[]): Record<string, unknown> {
15
+ if (
16
+ value === null ||
17
+ typeof value !== 'object' ||
18
+ Array.isArray(value) ||
19
+ Object.keys(value).length !== fields.length ||
20
+ !fields.every((field) => Object.hasOwn(value, field))
21
+ ) {
22
+ throw new TypeError('Invalid suite peers file fields');
23
+ }
24
+ return value as Record<string, unknown>;
25
+ }
26
+
27
+ function stringArray(value: unknown): value is string[] {
28
+ return Array.isArray(value) && value.every((item: unknown) => typeof item === 'string');
29
+ }
30
+
31
+ function parsePeer(value: unknown): PeerMetadata {
32
+ const peer = requireFields(value, PEER_FIELDS);
33
+ const { id, scheme, displayName, emits, accepts, rewardModes } = peer;
34
+ if (
35
+ typeof id !== 'string' ||
36
+ id.length > MAX_APP_ID_LENGTH ||
37
+ !/^[a-z]/u.test(id) ||
38
+ /[^a-z0-9_]/u.test(id) ||
39
+ typeof scheme !== 'string' ||
40
+ !/^[a-z]/u.test(scheme) ||
41
+ /[^a-z0-9+.-]/u.test(scheme) ||
42
+ typeof displayName !== 'string' ||
43
+ !stringArray(emits) ||
44
+ !stringArray(accepts) ||
45
+ !stringArray(rewardModes)
46
+ ) {
47
+ throw new TypeError('Invalid suite peer metadata');
48
+ }
49
+ const modes = rewardModes.map((mode) => {
50
+ if (mode !== 'native' && mode !== 'source_xp' && mode !== 'off') {
51
+ throw new TypeError('Invalid suite peer reward mode');
52
+ }
53
+ return mode;
54
+ });
55
+ return { id, scheme, displayName, emits: [...emits], accepts: [...accepts], rewardModes: modes };
56
+ }
57
+
58
+ /** Validates a parsed schema-version-1 peers file with the Rust registry rules. */
59
+ export function parsePeersFile(json: unknown): PeerMetadata[] {
60
+ const file = requireFields(json, ['schemaVersion', 'peers']);
61
+ if (file['schemaVersion'] !== 1 || !Array.isArray(file['peers'])) {
62
+ throw new TypeError('Invalid suite peers file schema');
63
+ }
64
+ const peers = file['peers'].map(parsePeer);
65
+ const ids = new Set(peers.map((peer) => peer.id));
66
+ if (ids.size !== peers.length) {
67
+ throw new TypeError('Duplicate suite peer id');
68
+ }
69
+ return peers;
70
+ }
71
+
72
+ /** Returns the other apps' query schemes, without duplicates, in lexical order. */
73
+ export function peerLinkQuerySchemes(peers: readonly PeerMetadata[], ownAppId: string): string[] {
74
+ return [
75
+ ...new Set(peers.filter((peer) => peer.id !== ownAppId).map((peer) => peer.scheme)),
76
+ ].sort();
77
+ }
package/src/session.ts ADDED
@@ -0,0 +1,88 @@
1
+ import {
2
+ OAuthSessionCoordinator,
3
+ type OAuthSessionCoordinatorOptions,
4
+ type OAuthSessionOutcome,
5
+ } from '@baukit/integrations-client';
6
+ import { SuiteClient, SuiteFlowError, type SuiteLink } from './api.js';
7
+ import { suiteReturnUrl, suiteReturnValidator, type SuiteReturnPolicy } from './urls.js';
8
+
9
+ export type SuiteConnectionResult =
10
+ | { readonly type: 'connected'; readonly requestId: string; readonly link: SuiteLink }
11
+ | { readonly type: 'denied' }
12
+ | { readonly type: 'cancelled' };
13
+ export interface SuiteSessionOptions extends SuiteReturnPolicy {
14
+ readonly client: SuiteClient;
15
+ readonly coordinator: Omit<OAuthSessionCoordinatorOptions, 'validateReturnUrl' | 'timeoutMs'>;
16
+ }
17
+ /** One instance per signed-in session. Share it between native and redirect handlers. */
18
+ export class SuiteSession {
19
+ readonly #coordinator: OAuthSessionCoordinator;
20
+ #nativeConnection: Promise<SuiteConnectionResult> | undefined;
21
+ #redirect: { readonly url: string; readonly result: Promise<SuiteConnectionResult> } | undefined;
22
+ #nativeReturn: string | undefined;
23
+ public constructor(private readonly options: SuiteSessionOptions) {
24
+ const native = options.coordinator.native;
25
+ this.#coordinator = new OAuthSessionCoordinator({
26
+ ...options.coordinator,
27
+ ...(native === undefined
28
+ ? {}
29
+ : {
30
+ native: {
31
+ run: async (input) => {
32
+ const result = await native.run(input);
33
+ if (result.type === 'success') this.#nativeReturn = result.returnUrl;
34
+ return result;
35
+ },
36
+ cancel: () => {
37
+ native.cancel();
38
+ },
39
+ },
40
+ }),
41
+ timeoutMs: 600_000,
42
+ validateReturnUrl: suiteReturnValidator(options),
43
+ });
44
+ }
45
+ public connect(peerApp: string): Promise<SuiteConnectionResult> {
46
+ if (this.#nativeConnection !== undefined) return this.#nativeConnection;
47
+ this.#redirect = undefined;
48
+ this.#nativeReturn = undefined;
49
+ const operation = this.#coordinator
50
+ .authorize({
51
+ platform: this.options.platform,
52
+ returnUrl: suiteReturnUrl(this.options),
53
+ createAuthorizationUrl: async ({ returnUrl, stateNonce }) =>
54
+ (await this.options.client.start({ peerApp, returnUrl, stateNonce })).authorizeUrl,
55
+ })
56
+ .then((outcome) => this.complete(outcome));
57
+ if (this.options.platform === 'web') return operation;
58
+ const result = operation.finally(() => {
59
+ if (this.#nativeReturn !== undefined) this.#redirect = { url: this.#nativeReturn, result };
60
+ if (this.#nativeConnection === result) this.#nativeConnection = undefined;
61
+ });
62
+ this.#nativeConnection = result;
63
+ return result;
64
+ }
65
+ public handleRedirect(url: string): Promise<SuiteConnectionResult> {
66
+ if (this.#nativeConnection !== undefined) return this.#nativeConnection;
67
+ if (this.#redirect?.url === url) return this.#redirect.result;
68
+ const result = this.#coordinator.handleRedirect(url).then((outcome) => this.complete(outcome));
69
+ this.#redirect = { url, result };
70
+ return result;
71
+ }
72
+ private async complete(outcome: OAuthSessionOutcome): Promise<SuiteConnectionResult> {
73
+ if (outcome.type === 'cancelled') return { type: 'cancelled' };
74
+ if (outcome.type !== 'success') throw new SuiteFlowError('suite_code_invalid');
75
+ const params = outcome.callbackParams;
76
+ if (params['status'] === 'denied') return { type: 'denied' };
77
+ if (params['status'] === 'failed')
78
+ throw new SuiteFlowError(params['code'] ?? 'suite_code_invalid');
79
+ const requestId = params['request'];
80
+ const code = params['code'];
81
+ if (!requestId || !code || params['status']) throw new SuiteFlowError('suite_code_invalid');
82
+ return {
83
+ type: 'connected',
84
+ requestId,
85
+ link: await this.options.client.complete(requestId, code),
86
+ };
87
+ }
88
+ }
package/src/urls.ts ADDED
@@ -0,0 +1,58 @@
1
+ import { createReturnUrlValidator } from '@baukit/integrations-client';
2
+
3
+ export interface SuiteReturnPolicy {
4
+ readonly platform: 'web' | 'native';
5
+ readonly origin: string;
6
+ }
7
+ export function suiteReturnUrl(policy: SuiteReturnPolicy): string {
8
+ return policy.platform === 'web' ? `${policy.origin}/suite/linked` : `${policy.origin}/linked`;
9
+ }
10
+ export function suiteReturnValidator(policy: SuiteReturnPolicy): (url: string) => boolean {
11
+ return createReturnUrlValidator({
12
+ origin: policy.origin,
13
+ paths: [policy.platform === 'web' ? '/suite/linked' : '/linked'],
14
+ });
15
+ }
16
+ /** Allows only the two suite pages. Other native intents belong to the product. */
17
+ export function createSuiteNativeIntentValidator(scheme: string): (value: string) => boolean {
18
+ if (!/^[a-z][a-z0-9+.-]*$/.test(scheme)) throw new TypeError('Invalid app scheme.');
19
+ const routes = new Set([
20
+ `${scheme}://suite/authorize`,
21
+ `${scheme}://suite/linked`,
22
+ `${scheme}:///suite/authorize`,
23
+ `${scheme}:///suite/linked`,
24
+ '/suite/authorize',
25
+ '/suite/linked',
26
+ ]);
27
+ return (value) => routes.has(value.split(/[?#]/, 1)[0] ?? '');
28
+ }
29
+ export async function openSuitePeer(
30
+ peer: { readonly scheme: string; readonly webUrl: string },
31
+ options: {
32
+ readonly platform: 'web' | 'native';
33
+ readonly openUrl: (url: string) => Promise<void>;
34
+ readonly allowLoopback?: boolean;
35
+ },
36
+ ): Promise<void> {
37
+ const web = new URL(peer.webUrl);
38
+ const loopback =
39
+ options.allowLoopback === true && ['localhost', '127.0.0.1', '[::1]'].includes(web.hostname);
40
+ if (
41
+ !/^[a-z][a-z0-9+.-]*$/.test(peer.scheme) ||
42
+ web.username !== '' ||
43
+ web.password !== '' ||
44
+ (web.protocol !== 'https:' && !(web.protocol === 'http:' && loopback))
45
+ ) {
46
+ throw new TypeError('Invalid peer URL.');
47
+ }
48
+ if (options.platform === 'native') {
49
+ try {
50
+ await options.openUrl(`${peer.scheme}://`);
51
+ return;
52
+ } catch {
53
+ await options.openUrl(peer.webUrl);
54
+ return;
55
+ }
56
+ }
57
+ await options.openUrl(peer.webUrl);
58
+ }