@andco/protocol 0.0.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.
Files changed (126) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +44 -0
  3. package/dist/authorization-preparation.d.ts +754 -0
  4. package/dist/authorization-preparation.d.ts.map +1 -0
  5. package/dist/authorization-preparation.js +187 -0
  6. package/dist/authorization.d.ts +99 -0
  7. package/dist/authorization.d.ts.map +1 -0
  8. package/dist/authorization.js +227 -0
  9. package/dist/automatic-charge.d.ts +314 -0
  10. package/dist/automatic-charge.d.ts.map +1 -0
  11. package/dist/automatic-charge.js +126 -0
  12. package/dist/bank-account-authorization.d.ts +6 -0
  13. package/dist/bank-account-authorization.d.ts.map +1 -0
  14. package/dist/bank-account-authorization.js +13 -0
  15. package/dist/callback-state.d.ts +10 -0
  16. package/dist/callback-state.d.ts.map +1 -0
  17. package/dist/callback-state.js +28 -0
  18. package/dist/consent.d.ts +48 -0
  19. package/dist/consent.d.ts.map +1 -0
  20. package/dist/consent.js +110 -0
  21. package/dist/constants.d.ts +17 -0
  22. package/dist/constants.d.ts.map +1 -0
  23. package/dist/constants.js +20 -0
  24. package/dist/errors.d.ts +70 -0
  25. package/dist/errors.d.ts.map +1 -0
  26. package/dist/errors.js +80 -0
  27. package/dist/index.d.ts +33 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +32 -0
  30. package/dist/intent-input.d.ts +637 -0
  31. package/dist/intent-input.d.ts.map +1 -0
  32. package/dist/intent-input.js +101 -0
  33. package/dist/messages/authorization-response.d.ts +12 -0
  34. package/dist/messages/authorization-response.d.ts.map +1 -0
  35. package/dist/messages/authorization-response.js +9 -0
  36. package/dist/messages/base.d.ts +31 -0
  37. package/dist/messages/base.d.ts.map +1 -0
  38. package/dist/messages/base.js +30 -0
  39. package/dist/messages/click.d.ts +11 -0
  40. package/dist/messages/click.d.ts.map +1 -0
  41. package/dist/messages/click.js +8 -0
  42. package/dist/messages/error.d.ts +13 -0
  43. package/dist/messages/error.d.ts.map +1 -0
  44. package/dist/messages/error.js +9 -0
  45. package/dist/messages/index.d.ts +75 -0
  46. package/dist/messages/index.d.ts.map +1 -0
  47. package/dist/messages/index.js +27 -0
  48. package/dist/messages/init.d.ts +9 -0
  49. package/dist/messages/init.d.ts.map +1 -0
  50. package/dist/messages/init.js +6 -0
  51. package/dist/messages/popup.d.ts +108 -0
  52. package/dist/messages/popup.d.ts.map +1 -0
  53. package/dist/messages/popup.js +62 -0
  54. package/dist/messages/ready.d.ts +9 -0
  55. package/dist/messages/ready.d.ts.map +1 -0
  56. package/dist/messages/ready.js +6 -0
  57. package/dist/messages/set-preferences.d.ts +16 -0
  58. package/dist/messages/set-preferences.d.ts.map +1 -0
  59. package/dist/messages/set-preferences.js +20 -0
  60. package/dist/miniapp-icon.d.ts +4 -0
  61. package/dist/miniapp-icon.d.ts.map +1 -0
  62. package/dist/miniapp-icon.js +68 -0
  63. package/dist/miniapp-manifest.d.ts +71 -0
  64. package/dist/miniapp-manifest.d.ts.map +1 -0
  65. package/dist/miniapp-manifest.js +46 -0
  66. package/dist/native-copy.d.ts +7 -0
  67. package/dist/native-copy.d.ts.map +1 -0
  68. package/dist/native-copy.js +436 -0
  69. package/dist/native-intent.d.ts +402 -0
  70. package/dist/native-intent.d.ts.map +1 -0
  71. package/dist/native-intent.js +410 -0
  72. package/dist/native.d.ts +55 -0
  73. package/dist/native.d.ts.map +1 -0
  74. package/dist/native.js +53 -0
  75. package/dist/oauth.d.ts +4 -0
  76. package/dist/oauth.d.ts.map +1 -0
  77. package/dist/oauth.js +3 -0
  78. package/dist/release.d.ts +3 -0
  79. package/dist/release.d.ts.map +1 -0
  80. package/dist/release.js +2 -0
  81. package/dist/scopes.d.ts +35 -0
  82. package/dist/scopes.d.ts.map +1 -0
  83. package/dist/scopes.js +15 -0
  84. package/dist/server.d.ts +9 -0
  85. package/dist/server.d.ts.map +1 -0
  86. package/dist/server.js +14 -0
  87. package/dist/transport/financial-events.d.ts +134 -0
  88. package/dist/transport/financial-events.d.ts.map +1 -0
  89. package/dist/transport/financial-events.js +120 -0
  90. package/dist/transport/generated/oauth-api.d.ts +1685 -0
  91. package/dist/transport/generated/oauth-api.d.ts.map +1 -0
  92. package/dist/transport/generated/oauth-api.js +5 -0
  93. package/dist/transport/index.d.ts +6 -0
  94. package/dist/transport/index.d.ts.map +1 -0
  95. package/dist/transport/index.js +5 -0
  96. package/dist/transport/intents.d.ts +81 -0
  97. package/dist/transport/intents.d.ts.map +1 -0
  98. package/dist/transport/intents.js +286 -0
  99. package/dist/transport/rest.d.ts +76 -0
  100. package/dist/transport/rest.d.ts.map +1 -0
  101. package/dist/transport/rest.js +48 -0
  102. package/dist/transport/runtime.d.ts +8 -0
  103. package/dist/transport/runtime.d.ts.map +1 -0
  104. package/dist/transport/runtime.js +16 -0
  105. package/dist/transport/webhooks.d.ts +27 -0
  106. package/dist/transport/webhooks.d.ts.map +1 -0
  107. package/dist/transport/webhooks.js +68 -0
  108. package/dist/urls.d.ts +71 -0
  109. package/dist/urls.d.ts.map +1 -0
  110. package/dist/urls.js +132 -0
  111. package/dist/userinfo.d.ts +11 -0
  112. package/dist/userinfo.d.ts.map +1 -0
  113. package/dist/userinfo.js +9 -0
  114. package/dist/utils.d.ts +20 -0
  115. package/dist/utils.d.ts.map +1 -0
  116. package/dist/utils.js +45 -0
  117. package/dist/webhook-input.d.ts +22 -0
  118. package/dist/webhook-input.d.ts.map +1 -0
  119. package/dist/webhook-input.js +11 -0
  120. package/dist/webhook-signature.d.ts +54 -0
  121. package/dist/webhook-signature.d.ts.map +1 -0
  122. package/dist/webhook-signature.js +74 -0
  123. package/dist/window-features.d.ts +28 -0
  124. package/dist/window-features.d.ts.map +1 -0
  125. package/dist/window-features.js +55 -0
  126. package/package.json +63 -0
@@ -0,0 +1,8 @@
1
+ /** Fetch implementation accepted by AndCo transport clients. */
2
+ export type AndCoFetch = typeof globalThis.fetch;
3
+ /**
4
+ * Resolves an injected Fetch implementation first and the runtime global lazily
5
+ * when a request is made.
6
+ */
7
+ export declare function createRuntimeFetch(injected?: AndCoFetch): AndCoFetch;
8
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/transport/runtime.ts"],"names":[],"mappings":"AAEA,gEAAgE;AAChE,MAAM,MAAM,UAAU,GAAG,OAAO,UAAU,CAAC,KAAK,CAAC;AAEjD;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,CAAC,EAAE,UAAU,GAAG,UAAU,CAYpE"}
@@ -0,0 +1,16 @@
1
+ import { ANDCO_ERROR_CODES, AndCoSDKError } from "../errors.js";
2
+ /**
3
+ * Resolves an injected Fetch implementation first and the runtime global lazily
4
+ * when a request is made.
5
+ */
6
+ export function createRuntimeFetch(injected) {
7
+ return ((input, init) => {
8
+ const fetcher = injected ?? globalThis.fetch;
9
+ if (typeof fetcher !== "function") {
10
+ return Promise.reject(new AndCoSDKError(ANDCO_ERROR_CODES.FETCH_UNAVAILABLE, {
11
+ missing: ["fetch"],
12
+ }));
13
+ }
14
+ return fetcher(input, init);
15
+ });
16
+ }
@@ -0,0 +1,27 @@
1
+ import { type AndCoWebhookSubscriptionCreate } from "../webhook-input.js";
2
+ import type { components } from "./generated/oauth-api.js";
3
+ import type { AndCoRestClient } from "./rest.js";
4
+ export type { AndCoWebhookSubscriptionCreate } from "../webhook-input.js";
5
+ export type AndCoWebhookSubscription = components["schemas"]["WebhookSubscription"];
6
+ export type AndCoWebhookDelivery = components["schemas"]["WebhookDelivery"];
7
+ export type AndCoWebhookAttempt = components["schemas"]["WebhookAttempt"];
8
+ export type AndCoWebhookDeliveryPage = components["schemas"]["WebhookDeliveryPage"];
9
+ export type AndCoWebhookAttemptPage = components["schemas"]["WebhookAttemptPage"];
10
+ type PageOptions = {
11
+ after?: string;
12
+ limit?: number;
13
+ };
14
+ /** Registers and inspects durable backend endpoints under the current exact Grant. */
15
+ export declare class AndCoWebhooksClient {
16
+ private readonly rest;
17
+ constructor(rest: AndCoRestClient);
18
+ create(input: AndCoWebhookSubscriptionCreate, options: {
19
+ idempotencyKey: string;
20
+ }): Promise<AndCoWebhookSubscription>;
21
+ get(subscriptionId: string): Promise<AndCoWebhookSubscription>;
22
+ getDeliveries(subscriptionId: string, options?: PageOptions): Promise<AndCoWebhookDeliveryPage>;
23
+ getAttempts(subscriptionId: string, deliveryId: string, options?: PageOptions): Promise<AndCoWebhookAttemptPage>;
24
+ /** Requeues a failed delivery; pending, in-flight, and acknowledged deliveries are unchanged. */
25
+ redrive(subscriptionId: string, deliveryId: string): Promise<AndCoWebhookDelivery>;
26
+ }
27
+ //# sourceMappingURL=webhooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhooks.d.ts","sourceRoot":"","sources":["../../src/transport/webhooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,8BAA8B,EAAgC,MAAM,qBAAqB,CAAC;AACxG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAE3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAEjD,YAAY,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AAC1E,MAAM,MAAM,wBAAwB,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,qBAAqB,CAAC,CAAC;AAEpF,MAAM,MAAM,oBAAoB,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,iBAAiB,CAAC,CAAC;AAC5E,MAAM,MAAM,mBAAmB,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,gBAAgB,CAAC,CAAC;AAC1E,MAAM,MAAM,wBAAwB,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,qBAAqB,CAAC,CAAC;AACpF,MAAM,MAAM,uBAAuB,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,oBAAoB,CAAC,CAAC;AAClF,KAAK,WAAW,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAStD,sFAAsF;AACtF,qBAAa,mBAAmB;IACX,OAAO,CAAC,QAAQ,CAAC,IAAI;gBAAJ,IAAI,EAAE,eAAe;IAC5C,MAAM,CACjB,KAAK,EAAE,8BAA8B,EACrC,OAAO,EAAE;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE,GAClC,OAAO,CAAC,wBAAwB,CAAC;IAWvB,GAAG,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,wBAAwB,CAAC;IAQ9D,aAAa,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,GAAE,WAAgB,GAAG,OAAO,CAAC,wBAAwB,CAAC;IASnG,WAAW,CACtB,cAAc,EAAE,MAAM,EACtB,UAAU,EAAE,MAAM,EAClB,OAAO,GAAE,WAAgB,GACxB,OAAO,CAAC,uBAAuB,CAAC;IAgBnC,iGAAiG;IACpF,OAAO,CAAC,cAAc,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;CAUhG"}
@@ -0,0 +1,68 @@
1
+ import { safeParseWebhookSubscription } from "../webhook-input.js";
2
+ import { AndCoIntentError, ASSERT_INTENT_ID } from "./intents.js";
3
+ function validatePage(options) {
4
+ if ((options.after !== undefined && options.after.length > 128) ||
5
+ (options.limit !== undefined && (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 100)))
6
+ throw new TypeError("Invalid webhook page options");
7
+ }
8
+ /** Registers and inspects durable backend endpoints under the current exact Grant. */
9
+ export class AndCoWebhooksClient {
10
+ rest;
11
+ constructor(rest) {
12
+ this.rest = rest;
13
+ }
14
+ async create(input, options) {
15
+ const parsed = safeParseWebhookSubscription(input);
16
+ if (!parsed.success || !/^[A-Za-z0-9._:-]{1,128}$/.test(options.idempotencyKey))
17
+ throw new TypeError("Invalid webhook registration");
18
+ const { data, error, response } = await this.rest.POST("/event-subscriptions", {
19
+ body: parsed.output,
20
+ params: { header: { "Idempotency-Key": options.idempotencyKey } },
21
+ });
22
+ if (error || !data)
23
+ throw new AndCoIntentError(error?.error ?? "invalid_webhook_response", response.status);
24
+ return data;
25
+ }
26
+ async get(subscriptionId) {
27
+ ASSERT_INTENT_ID(subscriptionId);
28
+ const { data, error, response } = await this.rest.GET("/event-subscriptions/{subscription_id}", {
29
+ params: { path: { subscription_id: subscriptionId } },
30
+ });
31
+ if (error || !data)
32
+ throw new AndCoIntentError(error?.error ?? "invalid_webhook_response", response.status);
33
+ return data;
34
+ }
35
+ async getDeliveries(subscriptionId, options = {}) {
36
+ ASSERT_INTENT_ID(subscriptionId);
37
+ validatePage(options);
38
+ const { data, error, response } = await this.rest.GET("/event-subscriptions/{subscription_id}/deliveries", {
39
+ params: { path: { subscription_id: subscriptionId }, query: { after: options.after, limit: options.limit } },
40
+ });
41
+ if (error || !data)
42
+ throw new AndCoIntentError(error?.error ?? "invalid_webhook_response", response.status);
43
+ return data;
44
+ }
45
+ async getAttempts(subscriptionId, deliveryId, options = {}) {
46
+ ASSERT_INTENT_ID(subscriptionId);
47
+ ASSERT_INTENT_ID(deliveryId);
48
+ validatePage(options);
49
+ const { data, error, response } = await this.rest.GET("/event-subscriptions/{subscription_id}/deliveries/{delivery_id}/attempts", {
50
+ params: {
51
+ path: { subscription_id: subscriptionId, delivery_id: deliveryId },
52
+ query: { after: options.after, limit: options.limit },
53
+ },
54
+ });
55
+ if (error || !data)
56
+ throw new AndCoIntentError(error?.error ?? "invalid_webhook_response", response.status);
57
+ return data;
58
+ }
59
+ /** Requeues a failed delivery; pending, in-flight, and acknowledged deliveries are unchanged. */
60
+ async redrive(subscriptionId, deliveryId) {
61
+ ASSERT_INTENT_ID(subscriptionId);
62
+ ASSERT_INTENT_ID(deliveryId);
63
+ const { data, error, response } = await this.rest.POST("/event-subscriptions/{subscription_id}/deliveries/{delivery_id}/redrive", { params: { path: { subscription_id: subscriptionId, delivery_id: deliveryId } } });
64
+ if (error || !data)
65
+ throw new AndCoIntentError(error?.error ?? "invalid_webhook_response", response.status);
66
+ return data;
67
+ }
68
+ }
package/dist/urls.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ /** Returns whether a hostname identifies the local machine for development URLs. */
2
+ export declare function IS_LOOPBACK_HOST(hostname: string): boolean;
3
+ declare const BETTER_URL_FIELDS: readonly ["hash", "host", "hostname", "password", "pathname", "port", "protocol", "search", "username"];
4
+ type BetterURLFieldName = (typeof BETTER_URL_FIELDS)[number];
5
+ /** Extracts `[key]` segment names from a URL template string literal. */
6
+ export type ExtractURLSegments<S extends string> = S extends `${string}[${infer K}]${infer Rest}` ? K | ExtractURLSegments<Rest> : never;
7
+ type BetterURLReplace<TUrl extends string | URL> = TUrl extends string ? [ExtractURLSegments<TUrl>] extends [never] ? Record<string, string | number> : Partial<Record<ExtractURLSegments<TUrl>, string | number>> : Record<string, string | number>;
8
+ export type BetterURLOverwrite<TUrl extends string | URL = string | URL> = Partial<Pick<URL, BetterURLFieldName>> & {
9
+ /** Set/delete querystring entries. `null` deletes the key, `undefined` is skipped, anything else is set. */
10
+ params?: Record<string | number, any>;
11
+ /** Substitutes `[key]` placeholders in the pathname (values are URL-encoded). */
12
+ replace?: BetterURLReplace<TUrl>;
13
+ };
14
+ export interface BetterURLFormatOptions {
15
+ protocol?: boolean;
16
+ hostname?: boolean;
17
+ port?: boolean;
18
+ pathname?: boolean;
19
+ search?: boolean;
20
+ hash?: boolean;
21
+ }
22
+ /**
23
+ * A `URL` with batch mutation and selective formatting on top. Carries no safety guarantees of its
24
+ * own — use {@link SafeURL} when the value must meet AndCo's transport contract.
25
+ *
26
+ * @example
27
+ * // Fill a path placeholder and set query params in one shot -> "https://example.com/o/andco?ref=demo"
28
+ * new BetterURL("/o/[organization_slug]", "https://example.com", {
29
+ * replace: { organization_slug: "andco" },
30
+ * params: { ref: "demo" },
31
+ * });
32
+ */
33
+ export declare class BetterURL<const TUrl extends string | URL = string | URL> extends URL {
34
+ constructor(url: TUrl, base?: string | URL, overwrite?: BetterURLOverwrite<TUrl>);
35
+ /**
36
+ * Returns whether this URL targets a loopback host.
37
+ *
38
+ * @example
39
+ * new BetterURL("http://localhost:3000").isLoopback; // true
40
+ */
41
+ get isLoopback(): boolean;
42
+ /** Applies `overwrite` mutations to this URL in place and returns it. */
43
+ assign(overwrite: BetterURLOverwrite<TUrl>): this;
44
+ /** Serializes the selected components only. With no options, returns `href`. */
45
+ format(opts?: BetterURLFormatOptions): string;
46
+ /** Parses the fragment as query-string-style params. Recomputed on every access; mutating it does not write back to `hash`. */
47
+ get hashParams(): URLSearchParams;
48
+ }
49
+ /**
50
+ * A {@link BetterURL} that is HTTPS (or plaintext HTTP on a loopback development host), and carries no
51
+ * credentials or fragment. These checks run once, at construction: mutating `protocol`, `username`,
52
+ * `password`, or `hash` afterward is not re-validated, so treat a SafeURL as safe only until mutated.
53
+ *
54
+ * Because a fragment fails construction, `.hashParams` is always empty on a valid SafeURL.
55
+ *
56
+ * @example
57
+ * const callback = new SafeURL("https://app.example/oauth/callback");
58
+ */
59
+ export declare class SafeURL<const TUrl extends string | URL = string | URL> extends BetterURL<TUrl> {
60
+ constructor(url: TUrl, base?: string | URL, overwrite?: BetterURLOverwrite<TUrl>);
61
+ }
62
+ /** Creates the AndCo Console URL for registering an OAuth project. */
63
+ export declare function ANDCO_PROJECT_URL({ redirectUris, clientName, clientType, framework, scopes, }: {
64
+ redirectUris: string[];
65
+ clientName: string;
66
+ clientType?: "confidential" | "public";
67
+ framework: "nodejs" | "react" | "react-native" | "nextjs" | "vue" | "angular" | "svelte" | "ruby" | "python";
68
+ scopes: string[];
69
+ }, baseURL?: string | URL): URL;
70
+ export {};
71
+ //# sourceMappingURL=urls.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"urls.d.ts","sourceRoot":"","sources":["../src/urls.ts"],"names":[],"mappings":"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"}
package/dist/urls.js ADDED
@@ -0,0 +1,132 @@
1
+ /** Returns whether a hostname identifies the local machine for development URLs. */
2
+ export function IS_LOOPBACK_HOST(hostname) {
3
+ const normalized = hostname.toLowerCase();
4
+ if (normalized === "localhost" || normalized.endsWith(".localhost"))
5
+ return true;
6
+ if (normalized === "[::1]" || normalized === "::1")
7
+ return true;
8
+ return /^127(?:\.\d{1,3}){3}$/.test(normalized);
9
+ }
10
+ const BETTER_URL_FIELDS = [
11
+ "hash",
12
+ "host",
13
+ "hostname",
14
+ "password",
15
+ "pathname",
16
+ "port",
17
+ "protocol",
18
+ "search",
19
+ "username",
20
+ ];
21
+ /**
22
+ * A `URL` with batch mutation and selective formatting on top. Carries no safety guarantees of its
23
+ * own — use {@link SafeURL} when the value must meet AndCo's transport contract.
24
+ *
25
+ * @example
26
+ * // Fill a path placeholder and set query params in one shot -> "https://example.com/o/andco?ref=demo"
27
+ * new BetterURL("/o/[organization_slug]", "https://example.com", {
28
+ * replace: { organization_slug: "andco" },
29
+ * params: { ref: "demo" },
30
+ * });
31
+ */
32
+ export class BetterURL extends URL {
33
+ constructor(url, base, overwrite) {
34
+ try {
35
+ super(url, base);
36
+ }
37
+ catch (error) {
38
+ throw new Error(`${error instanceof Error ? error.message : String(error)} — new BetterURL('${url}', '${base}')`);
39
+ }
40
+ if (overwrite)
41
+ this.assign(overwrite);
42
+ }
43
+ /**
44
+ * Returns whether this URL targets a loopback host.
45
+ *
46
+ * @example
47
+ * new BetterURL("http://localhost:3000").isLoopback; // true
48
+ */
49
+ get isLoopback() {
50
+ return IS_LOOPBACK_HOST(this.hostname);
51
+ }
52
+ /** Applies `overwrite` mutations to this URL in place and returns it. */
53
+ assign(overwrite) {
54
+ if (overwrite.replace) {
55
+ let { pathname } = this;
56
+ for (const [key, value] of Object.entries(overwrite.replace)) {
57
+ pathname = pathname.replaceAll(`[${key}]`, encodeURIComponent(String(value)));
58
+ }
59
+ this.pathname = pathname;
60
+ }
61
+ for (const field of BETTER_URL_FIELDS) {
62
+ const value = overwrite[field];
63
+ if (value !== undefined)
64
+ this[field] = value;
65
+ }
66
+ if (overwrite.params) {
67
+ for (const [key, value] of Object.entries(overwrite.params)) {
68
+ if (value === undefined) {
69
+ // skip
70
+ }
71
+ else if (value === null) {
72
+ this.searchParams.delete(key);
73
+ }
74
+ else {
75
+ this.searchParams.set(key, value);
76
+ }
77
+ }
78
+ }
79
+ return this;
80
+ }
81
+ /** Serializes the selected components only. With no options, returns `href`. */
82
+ format(opts) {
83
+ if (!opts)
84
+ return this.href;
85
+ let str = "";
86
+ if (opts.protocol)
87
+ str += `${this.protocol}//`;
88
+ if (opts.hostname)
89
+ str += this.hostname;
90
+ if (opts.port && this.port)
91
+ str += `:${this.port}`;
92
+ if (opts.pathname)
93
+ str += this.pathname;
94
+ if (opts.search)
95
+ str += this.search;
96
+ if (opts.hash)
97
+ str += this.hash;
98
+ return str;
99
+ }
100
+ /** Parses the fragment as query-string-style params. Recomputed on every access; mutating it does not write back to `hash`. */
101
+ get hashParams() {
102
+ return new URLSearchParams(this.hash.slice(1));
103
+ }
104
+ }
105
+ /**
106
+ * A {@link BetterURL} that is HTTPS (or plaintext HTTP on a loopback development host), and carries no
107
+ * credentials or fragment. These checks run once, at construction: mutating `protocol`, `username`,
108
+ * `password`, or `hash` afterward is not re-validated, so treat a SafeURL as safe only until mutated.
109
+ *
110
+ * Because a fragment fails construction, `.hashParams` is always empty on a valid SafeURL.
111
+ *
112
+ * @example
113
+ * const callback = new SafeURL("https://app.example/oauth/callback");
114
+ */
115
+ export class SafeURL extends BetterURL {
116
+ constructor(url, base, overwrite) {
117
+ super(url, base, overwrite);
118
+ const secureTransport = this.protocol === "https:" || (this.protocol === "http:" && IS_LOOPBACK_HOST(this.hostname));
119
+ if (!secureTransport || this.username || this.password || this.hash) {
120
+ throw new TypeError("AndCo URLs require HTTPS, except for loopback development hosts, and cannot contain credentials or a fragment");
121
+ }
122
+ }
123
+ }
124
+ /** Creates the AndCo Console URL for registering an OAuth project. */
125
+ export function ANDCO_PROJECT_URL({ redirectUris, clientName, clientType = "confidential", framework, scopes, }, baseURL = "https://www.andco.cl") {
126
+ const search = new URLSearchParams({ client_name: clientName, client_type: clientType, framework });
127
+ for (const redirectUri of redirectUris)
128
+ search.append("redirect_uris", redirectUri);
129
+ for (const scope of scopes)
130
+ search.append("scopes", scope);
131
+ return new URL(`/o/_/p/credentials/new?${search.toString()}`, baseURL);
132
+ }
@@ -0,0 +1,11 @@
1
+ import * as v from "valibot";
2
+ /** Scope-filtered claims returned by Andco's UserInfo endpoint. */
3
+ export declare const AndCoUserInfoSchema: v.LooseObjectSchema<{
4
+ readonly sub: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 256, undefined>]>;
5
+ readonly email: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.EmailAction<string, undefined>, v.MaxLengthAction<string, 320, undefined>]>, undefined>;
6
+ readonly email_verified: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
7
+ readonly name: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MaxLengthAction<string, 1024, undefined>]>, undefined>;
8
+ readonly picture: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>, v.MaxLengthAction<string, 2048, undefined>]>, undefined>;
9
+ }, undefined>;
10
+ export type AndCoOAuthUser = v.InferOutput<typeof AndCoUserInfoSchema>;
11
+ //# sourceMappingURL=userinfo.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"userinfo.d.ts","sourceRoot":"","sources":["../src/userinfo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAE7B,mEAAmE;AACnE,eAAO,MAAM,mBAAmB;;;;;;aAM9B,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,mBAAmB,CAAC,CAAC"}
@@ -0,0 +1,9 @@
1
+ import * as v from "valibot";
2
+ /** Scope-filtered claims returned by Andco's UserInfo endpoint. */
3
+ export const AndCoUserInfoSchema = /* @__PURE__ */ v.looseObject({
4
+ sub: v.pipe(v.string(), v.minLength(1), v.maxLength(256)),
5
+ email: v.optional(v.pipe(v.string(), v.email(), v.maxLength(320))),
6
+ email_verified: v.optional(v.boolean()),
7
+ name: v.optional(v.pipe(v.string(), v.maxLength(1_024))),
8
+ picture: v.optional(v.pipe(v.string(), v.url(), v.maxLength(2_048))),
9
+ });
@@ -0,0 +1,20 @@
1
+ /** Cryptographically secure random source accepted by SDK helpers. */
2
+ export type AndCoRandomSource = Pick<Crypto, "getRandomValues"> & Partial<Pick<Crypto, "randomUUID">>;
3
+ export declare function BASE64_ENCODE(value: string): string;
4
+ export declare function BASE64_DECODE(value: string): string;
5
+ /**
6
+ * Creates a UUID v4 from a Web Crypto random source.
7
+ *
8
+ * `crypto.randomUUID()` is used when available. Runtimes that only expose
9
+ * `getRandomValues()` use the equivalent RFC 4122 byte layout.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { RANDOM_UUID, type AndCoRandomSource } from "@andco/protocol";
14
+ *
15
+ * declare const runtimeCrypto: AndCoRandomSource;
16
+ * const transactionId = RANDOM_UUID(runtimeCrypto);
17
+ * ```
18
+ */
19
+ export declare function RANDOM_UUID(source?: AndCoRandomSource | undefined): string;
20
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAEA,sEAAsE;AACtE,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAAC,MAAM,EAAE,iBAAiB,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC;AAEtG,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOnD;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAMnD;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,MAAM,GAAE,iBAAiB,GAAG,SAA6B,GAAG,MAAM,CAc7F"}
package/dist/utils.js ADDED
@@ -0,0 +1,45 @@
1
+ import { ANDCO_ERROR_CODES, AndCoSDKError } from "./errors.js";
2
+ export function BASE64_ENCODE(value) {
3
+ const bytes = new TextEncoder().encode(value);
4
+ let binary = "";
5
+ for (const byte of bytes) {
6
+ binary += String.fromCharCode(byte);
7
+ }
8
+ return btoa(binary).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
9
+ }
10
+ export function BASE64_DECODE(value) {
11
+ const encoded = value.replace(/-/g, "+").replace(/_/g, "/");
12
+ const padded = encoded.padEnd(Math.ceil(encoded.length / 4) * 4, "=");
13
+ const binary = atob(padded);
14
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
15
+ return new TextDecoder().decode(bytes);
16
+ }
17
+ /**
18
+ * Creates a UUID v4 from a Web Crypto random source.
19
+ *
20
+ * `crypto.randomUUID()` is used when available. Runtimes that only expose
21
+ * `getRandomValues()` use the equivalent RFC 4122 byte layout.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { RANDOM_UUID, type AndCoRandomSource } from "@andco/protocol";
26
+ *
27
+ * declare const runtimeCrypto: AndCoRandomSource;
28
+ * const transactionId = RANDOM_UUID(runtimeCrypto);
29
+ * ```
30
+ */
31
+ export function RANDOM_UUID(source = globalThis.crypto) {
32
+ if (source && typeof source.randomUUID === "function") {
33
+ return source.randomUUID();
34
+ }
35
+ else if (!source || typeof source.getRandomValues !== "function") {
36
+ throw new AndCoSDKError(ANDCO_ERROR_CODES.WEB_CRYPTO_UNAVAILABLE, {
37
+ missing: ["crypto.getRandomValues"],
38
+ });
39
+ }
40
+ const bytes = source.getRandomValues(new Uint8Array(16));
41
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
42
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
43
+ const value = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
44
+ return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
45
+ }
@@ -0,0 +1,22 @@
1
+ import * as v from "valibot";
2
+ /** Backend registration is limited to one explicit subject under the current Grant. */
3
+ export declare const WebhookSubscriptionCreateSchema: v.StrictObjectSchema<{
4
+ readonly subject: v.StrictObjectSchema<{
5
+ readonly kind: v.PicklistSchema<["intent", "account"], undefined>;
6
+ readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UuidAction<string, undefined>]>;
7
+ }, undefined>;
8
+ readonly url: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>, v.MaxLengthAction<string, 2048, undefined>]>;
9
+ readonly event_types: v.SchemaWithPipe<readonly [v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>, v.MaxLengthAction<string, 128, undefined>]>, undefined>, v.MinLengthAction<string[], 1, undefined>, v.MaxLengthAction<string[], 32, undefined>, v.CheckAction<string[], undefined>]>;
10
+ readonly signing_secret: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
11
+ }, undefined>;
12
+ export type AndCoWebhookSubscriptionCreate = v.InferOutput<typeof WebhookSubscriptionCreateSchema>;
13
+ export declare function safeParseWebhookSubscription(input: unknown): v.SafeParseResult<v.StrictObjectSchema<{
14
+ readonly subject: v.StrictObjectSchema<{
15
+ readonly kind: v.PicklistSchema<["intent", "account"], undefined>;
16
+ readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UuidAction<string, undefined>]>;
17
+ }, undefined>;
18
+ readonly url: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>, v.MaxLengthAction<string, 2048, undefined>]>;
19
+ readonly event_types: v.SchemaWithPipe<readonly [v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>, v.MaxLengthAction<string, 128, undefined>]>, undefined>, v.MinLengthAction<string[], 1, undefined>, v.MaxLengthAction<string[], 32, undefined>, v.CheckAction<string[], undefined>]>;
20
+ readonly signing_secret: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
21
+ }, undefined>>;
22
+ //# sourceMappingURL=webhook-input.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook-input.d.ts","sourceRoot":"","sources":["../src/webhook-input.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAE7B,uFAAuF;AACvF,eAAO,MAAM,+BAA+B;;;;;;;;aAU1C,CAAC;AACH,MAAM,MAAM,8BAA8B,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,+BAA+B,CAAC,CAAC;AACnG,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,OAAO;;;;;;;;eAE1D"}
@@ -0,0 +1,11 @@
1
+ import * as v from "valibot";
2
+ /** Backend registration is limited to one explicit subject under the current Grant. */
3
+ export const WebhookSubscriptionCreateSchema = /* @__PURE__ */ v.strictObject({
4
+ subject: v.strictObject({ kind: v.picklist(["intent", "account"]), id: v.pipe(v.string(), v.uuid()) }),
5
+ url: v.pipe(v.string(), v.url(), v.maxLength(2048)),
6
+ event_types: v.pipe(v.array(v.pipe(v.string(), v.regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/), v.maxLength(128))), v.minLength(1), v.maxLength(32), v.check((types) => new Set(types).size === types.length)),
7
+ signing_secret: v.pipe(v.string(), v.regex(/^[A-Za-z0-9_-]{43}$/)),
8
+ });
9
+ export function safeParseWebhookSubscription(input) {
10
+ return v.safeParse(WebhookSubscriptionCreateSchema, input);
11
+ }
@@ -0,0 +1,54 @@
1
+ /** Header names Andco signs a webhook delivery with. */
2
+ export declare const ANDCO_WEBHOOK_HEADERS: {
3
+ readonly signature: "andco-signature";
4
+ readonly eventId: "andco-event-id";
5
+ readonly timestamp: "andco-timestamp";
6
+ };
7
+ /** Default tolerance for the delivery timestamp, in seconds. */
8
+ export declare const ANDCO_WEBHOOK_TOLERANCE_SECONDS = 300;
9
+ /** Everything a verification needs, however the runtime spells its headers. */
10
+ export type AndCoWebhookVerifyInput = {
11
+ /** The exact bytes of the request body, before any JSON parsing. */
12
+ body: string;
13
+ /** `Andco-Signature`, including its `v1=` prefix. */
14
+ signature: string | null | undefined;
15
+ /** `Andco-Event-Id`. */
16
+ eventId: string | null | undefined;
17
+ /** `Andco-Timestamp`, in seconds. */
18
+ timestamp: string | null | undefined;
19
+ /** The subscription's signing secret. */
20
+ secret: string | Uint8Array;
21
+ /** How far the delivery timestamp may drift. Defaults to five minutes. */
22
+ toleranceSeconds?: number;
23
+ /** Current time in seconds, for tests. */
24
+ now?: number;
25
+ };
26
+ /**
27
+ * Whether a webhook delivery really came from Andco.
28
+ *
29
+ * The signature covers `{timestamp}.{eventId}.{body}`, so it binds the payload to one delivery and
30
+ * one moment: replaying an old body under a new timestamp does not verify, and neither does
31
+ * reusing a valid signature for a different event.
32
+ *
33
+ * Two details are easy to get wrong when this is written by hand, and both are handled here: the
34
+ * comparison is constant-time, so a wrong signature leaks nothing through how long the check takes,
35
+ * and a delivery outside the tolerance window is rejected even when its signature is valid.
36
+ *
37
+ * The body must be the raw bytes. A framework that parses JSON before your handler runs has already
38
+ * destroyed the thing being signed — re-serializing it produces different bytes and the check fails.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * const raw = await request.text();
43
+ * const trusted = await andCoWebhookVerify({
44
+ * body: raw,
45
+ * signature: request.headers.get(ANDCO_WEBHOOK_HEADERS.signature),
46
+ * eventId: request.headers.get(ANDCO_WEBHOOK_HEADERS.eventId),
47
+ * timestamp: request.headers.get(ANDCO_WEBHOOK_HEADERS.timestamp),
48
+ * secret: process.env.ANDCO_WEBHOOK_SECRET!,
49
+ * });
50
+ * if (!trusted) return new Response(null, { status: 400 });
51
+ * ```
52
+ */
53
+ export declare function andCoWebhookVerify(input: AndCoWebhookVerifyInput): Promise<boolean>;
54
+ //# sourceMappingURL=webhook-signature.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook-signature.d.ts","sourceRoot":"","sources":["../src/webhook-signature.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,eAAO,MAAM,qBAAqB;;;;CAIxB,CAAC;AAEX,gEAAgE;AAChE,eAAO,MAAM,+BAA+B,MAAM,CAAC;AAInD,+EAA+E;AAC/E,MAAM,MAAM,uBAAuB,GAAG;IACpC,oEAAoE;IACpE,IAAI,EAAE,MAAM,CAAC;IACb,qDAAqD;IACrD,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACrC,wBAAwB;IACxB,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACnC,qCAAqC;IACrC,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACrC,yCAAyC;IACzC,MAAM,EAAE,MAAM,GAAG,UAAU,CAAC;IAC5B,0EAA0E;IAC1E,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,0CAA0C;IAC1C,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAsB,kBAAkB,CAAC,KAAK,EAAE,uBAAuB,GAAG,OAAO,CAAC,OAAO,CAAC,CA0BzF"}
@@ -0,0 +1,74 @@
1
+ /** Header names Andco signs a webhook delivery with. */
2
+ export const ANDCO_WEBHOOK_HEADERS = {
3
+ signature: "andco-signature",
4
+ eventId: "andco-event-id",
5
+ timestamp: "andco-timestamp",
6
+ };
7
+ /** Default tolerance for the delivery timestamp, in seconds. */
8
+ export const ANDCO_WEBHOOK_TOLERANCE_SECONDS = 300;
9
+ const SIGNATURE_PREFIX = "v1=";
10
+ /**
11
+ * Whether a webhook delivery really came from Andco.
12
+ *
13
+ * The signature covers `{timestamp}.{eventId}.{body}`, so it binds the payload to one delivery and
14
+ * one moment: replaying an old body under a new timestamp does not verify, and neither does
15
+ * reusing a valid signature for a different event.
16
+ *
17
+ * Two details are easy to get wrong when this is written by hand, and both are handled here: the
18
+ * comparison is constant-time, so a wrong signature leaks nothing through how long the check takes,
19
+ * and a delivery outside the tolerance window is rejected even when its signature is valid.
20
+ *
21
+ * The body must be the raw bytes. A framework that parses JSON before your handler runs has already
22
+ * destroyed the thing being signed — re-serializing it produces different bytes and the check fails.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const raw = await request.text();
27
+ * const trusted = await andCoWebhookVerify({
28
+ * body: raw,
29
+ * signature: request.headers.get(ANDCO_WEBHOOK_HEADERS.signature),
30
+ * eventId: request.headers.get(ANDCO_WEBHOOK_HEADERS.eventId),
31
+ * timestamp: request.headers.get(ANDCO_WEBHOOK_HEADERS.timestamp),
32
+ * secret: process.env.ANDCO_WEBHOOK_SECRET!,
33
+ * });
34
+ * if (!trusted) return new Response(null, { status: 400 });
35
+ * ```
36
+ */
37
+ export async function andCoWebhookVerify(input) {
38
+ const { body, signature, eventId, timestamp, secret } = input;
39
+ if (!signature || !eventId || !timestamp)
40
+ return false;
41
+ if (!signature.startsWith(SIGNATURE_PREFIX))
42
+ return false;
43
+ const seconds = Number(timestamp);
44
+ if (!Number.isFinite(seconds))
45
+ return false;
46
+ const now = input.now ?? Math.floor(Date.now() / 1_000);
47
+ const tolerance = input.toleranceSeconds ?? ANDCO_WEBHOOK_TOLERANCE_SECONDS;
48
+ if (Math.abs(now - seconds) > tolerance)
49
+ return false;
50
+ const provided = decodeHex(signature.slice(SIGNATURE_PREFIX.length));
51
+ if (!provided)
52
+ return false;
53
+ const key = await crypto.subtle.importKey("raw", typeof secret === "string" ? new TextEncoder().encode(secret) : secret, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
54
+ const expected = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${timestamp}.${eventId}.${body}`)));
55
+ return timingSafeEqual(provided, expected);
56
+ }
57
+ function decodeHex(value) {
58
+ if (value.length === 0 || value.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(value))
59
+ return null;
60
+ const bytes = new Uint8Array(value.length / 2);
61
+ for (let index = 0; index < bytes.length; index += 1) {
62
+ bytes[index] = Number.parseInt(value.slice(index * 2, index * 2 + 2), 16);
63
+ }
64
+ return bytes;
65
+ }
66
+ /** Compares in time that does not depend on where the first difference is. */
67
+ function timingSafeEqual(a, b) {
68
+ if (a.length !== b.length)
69
+ return false;
70
+ let difference = 0;
71
+ for (let index = 0; index < a.length; index += 1)
72
+ difference |= a[index] ^ b[index];
73
+ return difference === 0;
74
+ }
@@ -0,0 +1,28 @@
1
+ /** Browser popup geometry shared by every Andco surface that opens one. */
2
+ export type AndcoPopupPosition = "center" | "top-left" | "top-right" | "bottom-left" | "bottom-right";
3
+ export type AndcoPopupGeometry = {
4
+ width?: number | string;
5
+ height?: number | string;
6
+ position?: AndcoPopupPosition;
7
+ /** Extra boolean features, such as `popup`. */
8
+ [feature: string]: unknown;
9
+ };
10
+ /**
11
+ * Builds a `window.open` features string.
12
+ *
13
+ * Part of the Protocol Contract rather than the SDK because both sides open the same popups: the
14
+ * Platform's own bridge positions a window exactly as an integrator's does, and two implementations
15
+ * would place them differently.
16
+ */
17
+ export declare function windowFeaturesFrom({ position, ...options }: AndcoPopupGeometry): string;
18
+ /** Whether this runtime has a DOM. A pure predicate both sides use before touching `window`. */
19
+ export declare function isBrowser(): boolean;
20
+ /**
21
+ * Prefix of the `window.name` an Andco popup carries, followed by its Presentation ID.
22
+ *
23
+ * Part of the Protocol Contract because both sides read it: whoever opens the popup writes the
24
+ * name, and the callback document uses it to recognise that the result is its to relay. Two
25
+ * spellings mean a popup that authorizes successfully and then never reports back.
26
+ */
27
+ export declare const ANDCO_POPUP_NAME_PREFIX = "andco-popup-";
28
+ //# sourceMappingURL=window-features.d.ts.map