@andco/protocol 0.0.3 → 0.0.5

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 (113) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +51 -3
  3. package/dist/api-errors.d.ts +114 -0
  4. package/dist/api-errors.d.ts.map +1 -0
  5. package/dist/api-errors.js +116 -0
  6. package/dist/authorization-preparation.d.ts +52 -543
  7. package/dist/authorization-preparation.d.ts.map +1 -1
  8. package/dist/authorization-preparation.js +19 -42
  9. package/dist/authorization.d.ts +64 -22
  10. package/dist/authorization.d.ts.map +1 -1
  11. package/dist/authorization.js +136 -55
  12. package/dist/consent.d.ts +5 -8
  13. package/dist/consent.d.ts.map +1 -1
  14. package/dist/consent.js +5 -62
  15. package/dist/constants.d.ts +19 -3
  16. package/dist/constants.d.ts.map +1 -1
  17. package/dist/constants.js +19 -3
  18. package/dist/errors.d.ts +154 -58
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +174 -57
  21. package/dist/index.d.ts +4 -4
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +4 -4
  24. package/dist/intent-input.d.ts +1022 -288
  25. package/dist/intent-input.d.ts.map +1 -1
  26. package/dist/intent-input.js +284 -40
  27. package/dist/messages/error.d.ts +1 -2
  28. package/dist/messages/error.d.ts.map +1 -1
  29. package/dist/messages/error.js +5 -2
  30. package/dist/messages/index.d.ts +1 -1
  31. package/dist/native-copy.d.ts +23 -2
  32. package/dist/native-copy.d.ts.map +1 -1
  33. package/dist/native-copy.js +65 -117
  34. package/dist/native-intent.d.ts +126 -75
  35. package/dist/native-intent.d.ts.map +1 -1
  36. package/dist/native-intent.js +140 -48
  37. package/dist/rar/account-matchers.d.ts +579 -0
  38. package/dist/rar/account-matchers.d.ts.map +1 -0
  39. package/dist/rar/account-matchers.js +480 -0
  40. package/dist/rar/bank.d.ts +1549 -0
  41. package/dist/rar/bank.d.ts.map +1 -0
  42. package/dist/rar/bank.js +379 -0
  43. package/dist/rar/catalog.d.ts +1155 -0
  44. package/dist/rar/catalog.d.ts.map +1 -0
  45. package/dist/rar/catalog.js +175 -0
  46. package/dist/rar/detail.d.ts +39 -0
  47. package/dist/rar/detail.d.ts.map +1 -0
  48. package/dist/rar/detail.js +44 -0
  49. package/dist/rar/index.d.ts +9 -0
  50. package/dist/rar/index.d.ts.map +1 -0
  51. package/dist/rar/index.js +8 -0
  52. package/dist/rar/money.d.ts +58 -0
  53. package/dist/rar/money.d.ts.map +1 -0
  54. package/dist/rar/money.js +61 -0
  55. package/dist/rar/project-users.d.ts +43 -0
  56. package/dist/rar/project-users.d.ts.map +1 -0
  57. package/dist/rar/project-users.js +63 -0
  58. package/dist/rar/subject-data.d.ts +170 -0
  59. package/dist/rar/subject-data.d.ts.map +1 -0
  60. package/dist/rar/subject-data.js +127 -0
  61. package/dist/rar/subject.d.ts +166 -0
  62. package/dist/rar/subject.d.ts.map +1 -0
  63. package/dist/rar/subject.js +119 -0
  64. package/dist/scopes.d.ts +5 -30
  65. package/dist/scopes.d.ts.map +1 -1
  66. package/dist/scopes.js +0 -13
  67. package/dist/service-grants.d.ts +44 -0
  68. package/dist/service-grants.d.ts.map +1 -0
  69. package/dist/service-grants.js +45 -0
  70. package/dist/signing.d.ts +56 -0
  71. package/dist/signing.d.ts.map +1 -0
  72. package/dist/signing.js +233 -0
  73. package/dist/transport/financial-events.d.ts +90 -35
  74. package/dist/transport/financial-events.d.ts.map +1 -1
  75. package/dist/transport/financial-events.js +7 -1
  76. package/dist/transport/generated/oauth-api.d.ts +932 -441
  77. package/dist/transport/generated/oauth-api.d.ts.map +1 -1
  78. package/dist/transport/index.d.ts +0 -1
  79. package/dist/transport/index.d.ts.map +1 -1
  80. package/dist/transport/index.js +0 -1
  81. package/dist/transport/intents.d.ts +155 -23
  82. package/dist/transport/intents.d.ts.map +1 -1
  83. package/dist/transport/intents.js +192 -59
  84. package/dist/transport/rest.d.ts +19 -8
  85. package/dist/transport/rest.d.ts.map +1 -1
  86. package/dist/transport/rest.js +1 -1
  87. package/dist/urls.d.ts.map +1 -1
  88. package/dist/urls.js +1 -1
  89. package/dist/userinfo.d.ts +10 -1
  90. package/dist/userinfo.d.ts.map +1 -1
  91. package/dist/userinfo.js +10 -1
  92. package/dist/utils.d.ts +15 -0
  93. package/dist/utils.d.ts.map +1 -1
  94. package/dist/utils.js +31 -0
  95. package/dist/webhooks.d.ts +154 -0
  96. package/dist/webhooks.d.ts.map +1 -0
  97. package/dist/webhooks.js +249 -0
  98. package/package.json +21 -2
  99. package/dist/automatic-charge.d.ts +0 -314
  100. package/dist/automatic-charge.d.ts.map +0 -1
  101. package/dist/automatic-charge.js +0 -126
  102. package/dist/bank-account-authorization.d.ts +0 -6
  103. package/dist/bank-account-authorization.d.ts.map +0 -1
  104. package/dist/bank-account-authorization.js +0 -13
  105. package/dist/transport/webhooks.d.ts +0 -27
  106. package/dist/transport/webhooks.d.ts.map +0 -1
  107. package/dist/transport/webhooks.js +0 -68
  108. package/dist/webhook-input.d.ts +0 -22
  109. package/dist/webhook-input.d.ts.map +0 -1
  110. package/dist/webhook-input.js +0 -11
  111. package/dist/webhook-signature.d.ts +0 -54
  112. package/dist/webhook-signature.d.ts.map +0 -1
  113. package/dist/webhook-signature.js +0 -74
@@ -0,0 +1,154 @@
1
+ /** Header names of a signed Andco webhook delivery. */
2
+ export declare const ANDCO_WEBHOOK_HEADERS: {
3
+ readonly eventId: "andco-event-id";
4
+ readonly timestamp: "andco-timestamp";
5
+ readonly signature: "andco-signature";
6
+ };
7
+ /** The only signature algorithm Andco signs webhook deliveries with. */
8
+ export declare const ANDCO_WEBHOOK_ALGORITHM: "Ed25519";
9
+ /** How far a delivery timestamp may drift from the receiver's clock, in seconds. */
10
+ export declare const ANDCO_WEBHOOK_TOLERANCE_SECONDS = 300;
11
+ /** Andco's public webhook keys. Platform serves the same document at its own origin. */
12
+ export declare const ANDCO_WEBHOOK_JWKS_URL: "https://api.andco.com/.well-known/webhook-keys.json";
13
+ /**
14
+ * The exact string Andco signs for one delivery: `${eventId}.${timestamp}.${rawBody}`.
15
+ *
16
+ * Binding the event id and the timestamp into the signed bytes means a captured body can be
17
+ * replayed neither under a later timestamp nor as a different event.
18
+ *
19
+ * @example
20
+ * ANDCO_WEBHOOK_SIGNED_CONTENT("8f0c…", "1790000000", '{"id":"8f0c…"}');
21
+ * // => '8f0c….1790000000.{"id":"8f0c…"}'
22
+ */
23
+ export declare function ANDCO_WEBHOOK_SIGNED_CONTENT(eventId: string, timestamp: string, rawBody: string): string;
24
+ /**
25
+ * Formats the `andco-signature` header value.
26
+ *
27
+ * @example
28
+ * ANDCO_WEBHOOK_SIGNATURE_HEADER("whk_2026_10", "kV3…");
29
+ * // => "kid=whk_2026_10, alg=Ed25519, sig=kV3…"
30
+ */
31
+ export declare function ANDCO_WEBHOOK_SIGNATURE_HEADER(kid: string, signature: string): string;
32
+ /** Why a delivery was rejected. Compare against these members, and keep a default branch. */
33
+ export declare const ANDCO_WEBHOOK_ERROR_CODES: {
34
+ /** `andco-event-id`, `andco-timestamp` or `andco-signature` is missing. */
35
+ readonly MISSING_HEADERS: "webhook_missing_headers";
36
+ /** `andco-signature` is not `kid=…, alg=Ed25519, sig=…`. */
37
+ readonly MALFORMED_SIGNATURE: "webhook_malformed_signature";
38
+ /** The timestamp is not a number or lies outside the tolerance window. */
39
+ readonly STALE_TIMESTAMP: "webhook_stale_timestamp";
40
+ /** The JWKS has no Ed25519 key with this `kid`, even after a refresh. */
41
+ readonly UNKNOWN_KEY: "webhook_unknown_key";
42
+ /** The signature does not match the signed content. */
43
+ readonly INVALID_SIGNATURE: "webhook_invalid_signature";
44
+ /** The body is not an event, or its `id` differs from `andco-event-id`. */
45
+ readonly INVALID_PAYLOAD: "webhook_invalid_payload";
46
+ /** The JWKS could not be fetched or is not a JWKS. */
47
+ readonly JWKS_UNAVAILABLE: "webhook_jwks_unavailable";
48
+ };
49
+ export type AndcoWebhookErrorCode = (typeof ANDCO_WEBHOOK_ERROR_CODES)[keyof typeof ANDCO_WEBHOOK_ERROR_CODES];
50
+ /**
51
+ * A webhook delivery that must not be trusted. Answer it with a 4xx and do not act on its body;
52
+ * Andco retries deliveries that are not acknowledged with a 2xx.
53
+ *
54
+ * @example
55
+ * try {
56
+ * event = await verify(request);
57
+ * } catch (error) {
58
+ * if (error instanceof AndcoWebhookError) return new Response(error.code, { status: 400 });
59
+ * throw error;
60
+ * }
61
+ */
62
+ export declare class AndcoWebhookError extends Error {
63
+ readonly code: AndcoWebhookErrorCode;
64
+ readonly name = "AndcoWebhookError";
65
+ constructor(code: AndcoWebhookErrorCode, message?: string, options?: {
66
+ cause?: unknown;
67
+ });
68
+ }
69
+ /**
70
+ * One Andco event as delivered to a Project's webhook endpoint. Every event of every client of the
71
+ * Project arrives at the same endpoint: filter by `client_id`, `grant_id` or `type` yourself.
72
+ */
73
+ export type AndcoWebhookEvent = {
74
+ /** Stable event id, equal to `andco-event-id`. Deduplicate durable effects by it. */
75
+ id: string;
76
+ /** Event type, such as `deposit.completed` or `withdrawal.posted`. */
77
+ type: string;
78
+ version: 1;
79
+ /** ISO 8601 instant of the fact. */
80
+ occurred_at: string;
81
+ /** The OAuth client of the Project whose Grant covers this event. */
82
+ client_id: string;
83
+ /** The Grant that covers this event. */
84
+ grant_id: string;
85
+ /** Opaque position of the event in its subject's replay feed. */
86
+ cursor: string;
87
+ /** Event-specific facts. Money values are strings. */
88
+ payload: Record<string, unknown>;
89
+ };
90
+ /** A raw delivery, for runtimes that do not hand the handler a Fetch `Request`. */
91
+ export type AndcoWebhookDelivery = {
92
+ /** The exact request body, before any JSON parsing. Re-serialized JSON does not verify. */
93
+ body: string;
94
+ /** Request headers: a Fetch `Headers` or a Node-style record such as `IncomingMessage.headers`. */
95
+ headers: Headers | Record<string, string | string[] | undefined>;
96
+ };
97
+ export type AndcoWebhookVerifierOptions = {
98
+ /** Where to fetch Andco's public webhook keys. Defaults to {@link ANDCO_WEBHOOK_JWKS_URL}. */
99
+ jwksUrl?: string | URL;
100
+ /** Accepted clock drift, in seconds. Defaults to {@link ANDCO_WEBHOOK_TOLERANCE_SECONDS}. */
101
+ toleranceSeconds?: number;
102
+ /** Fetch used for the JWKS. Defaults to the global `fetch`. */
103
+ fetch?: typeof fetch;
104
+ /** Current Unix time in seconds, for tests. */
105
+ now?: () => number;
106
+ };
107
+ /** Verifies one delivery and returns its event, or throws {@link AndcoWebhookError}. */
108
+ export type AndcoWebhookVerify = (delivery: Request | AndcoWebhookDelivery) => Promise<AndcoWebhookEvent>;
109
+ /**
110
+ * Creates a verifier for Andco webhook deliveries.
111
+ *
112
+ * Andco signs `${eventId}.${timestamp}.${rawBody}` with an Ed25519 key it owns and names the key by
113
+ * `kid` in `andco-signature`. The verifier fetches Andco's public JWKS once, caches every key by
114
+ * `kid`, and refetches only when a delivery names a `kid` it has not seen, which is how Andco rotates
115
+ * keys without any change on the receiver. Verification uses Web Crypto only, so it runs on Node,
116
+ * Deno, Bun, Cloudflare Workers and edge runtimes alike.
117
+ *
118
+ * The returned function throws {@link AndcoWebhookError} when a header is missing, the timestamp is
119
+ * outside the tolerance window, the key is unknown, the signature does not match, or the body's `id`
120
+ * differs from `andco-event-id`. Create the verifier once per process so the key cache is shared.
121
+ *
122
+ * @example
123
+ * ```ts
124
+ * // app/api/andco/webhooks/route.ts
125
+ * import { andcoWebhooks } from "@andco/protocol/webhooks";
126
+ *
127
+ * const verify = andcoWebhooks.verifier();
128
+ *
129
+ * export async function POST(request: Request) {
130
+ * const event = await verify(request);
131
+ * if (event.type === "deposit.completed") await markPaid(event.payload["intent_id"] as string);
132
+ * return new Response(null, { status: 204 });
133
+ * }
134
+ * ```
135
+ *
136
+ * @example
137
+ * ```ts
138
+ * // Node http, local development against Platform
139
+ * const verify = andcoWebhooks.verifier({ jwksUrl: "https://bank.localhost/.well-known/webhook-keys.json" });
140
+ * const event = await verify({ body: rawBody, headers: request.headers });
141
+ * ```
142
+ */
143
+ declare function verifier(options?: AndcoWebhookVerifierOptions): AndcoWebhookVerify;
144
+ /**
145
+ * Receiving Andco webhooks. See {@link verifier}.
146
+ *
147
+ * @example
148
+ * const verify = andcoWebhooks.verifier();
149
+ */
150
+ export declare const andcoWebhooks: {
151
+ readonly verifier: typeof verifier;
152
+ };
153
+ export {};
154
+ //# sourceMappingURL=webhooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhooks.d.ts","sourceRoot":"","sources":["../src/webhooks.ts"],"names":[],"mappings":"AAEA,uDAAuD;AACvD,eAAO,MAAM,qBAAqB;;;;CAIxB,CAAC;AAEX,wEAAwE;AACxE,eAAO,MAAM,uBAAuB,EAAG,SAAkB,CAAC;AAE1D,oFAAoF;AACpF,eAAO,MAAM,+BAA+B,MAAM,CAAC;AAEnD,wFAAwF;AACxF,eAAO,MAAM,sBAAsB,uDAA+D,CAAC;AAEnG;;;;;;;;;GASG;AACH,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAExG;AAED;;;;;;GAMG;AACH,wBAAgB,8BAA8B,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAErF;AAED,6FAA6F;AAC7F,eAAO,MAAM,yBAAyB;IACpC,2EAA2E;;IAE3E,4DAA4D;;IAE5D,0EAA0E;;IAE1E,yEAAyE;;IAEzE,uDAAuD;;IAEvD,2EAA2E;;IAE3E,sDAAsD;;CAE9C,CAAC;AAEX,MAAM,MAAM,qBAAqB,GAAG,CAAC,OAAO,yBAAyB,CAAC,CAAC,MAAM,OAAO,yBAAyB,CAAC,CAAC;AAE/G;;;;;;;;;;;GAWG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;aAGxB,IAAI,EAAE,qBAAqB;IAF7C,SAAyB,IAAI,uBAAuB;gBAElC,IAAI,EAAE,qBAAqB,EAC3C,OAAO,GAAE,MAAa,EACtB,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE;CAIhC;AAED;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,qFAAqF;IACrF,EAAE,EAAE,MAAM,CAAC;IACX,sEAAsE;IACtE,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,CAAC,CAAC;IACX,oCAAoC;IACpC,WAAW,EAAE,MAAM,CAAC;IACpB,qEAAqE;IACrE,SAAS,EAAE,MAAM,CAAC;IAClB,wCAAwC;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,iEAAiE;IACjE,MAAM,EAAE,MAAM,CAAC;IACf,sDAAsD;IACtD,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC,CAAC;AAEF,mFAAmF;AACnF,MAAM,MAAM,oBAAoB,GAAG;IACjC,2FAA2F;IAC3F,IAAI,EAAE,MAAM,CAAC;IACb,mGAAmG;IACnG,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;CAClE,CAAC;AAEF,MAAM,MAAM,2BAA2B,GAAG;IACxC,8FAA8F;IAC9F,OAAO,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;IACvB,6FAA6F;IAC7F,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,+DAA+D;IAC/D,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,+CAA+C;IAC/C,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB,CAAC;AAEF,wFAAwF;AACxF,MAAM,MAAM,kBAAkB,GAAG,CAAC,QAAQ,EAAE,OAAO,GAAG,oBAAoB,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAC;AA+C1G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,iBAAS,QAAQ,CAAC,OAAO,GAAE,2BAAgC,GAAG,kBAAkB,CA6F/E;AAED;;;;;GAKG;AACH,eAAO,MAAM,aAAa;;CAAwB,CAAC"}
@@ -0,0 +1,249 @@
1
+ import { ANDCO_API_ORIGIN } from "./constants.js";
2
+ /** Header names of a signed Andco webhook delivery. */
3
+ export const ANDCO_WEBHOOK_HEADERS = {
4
+ eventId: "andco-event-id",
5
+ timestamp: "andco-timestamp",
6
+ signature: "andco-signature",
7
+ };
8
+ /** The only signature algorithm Andco signs webhook deliveries with. */
9
+ export const ANDCO_WEBHOOK_ALGORITHM = "Ed25519";
10
+ /** How far a delivery timestamp may drift from the receiver's clock, in seconds. */
11
+ export const ANDCO_WEBHOOK_TOLERANCE_SECONDS = 300;
12
+ /** Andco's public webhook keys. Platform serves the same document at its own origin. */
13
+ export const ANDCO_WEBHOOK_JWKS_URL = `${ANDCO_API_ORIGIN}/.well-known/webhook-keys.json`;
14
+ /**
15
+ * The exact string Andco signs for one delivery: `${eventId}.${timestamp}.${rawBody}`.
16
+ *
17
+ * Binding the event id and the timestamp into the signed bytes means a captured body can be
18
+ * replayed neither under a later timestamp nor as a different event.
19
+ *
20
+ * @example
21
+ * ANDCO_WEBHOOK_SIGNED_CONTENT("8f0c…", "1790000000", '{"id":"8f0c…"}');
22
+ * // => '8f0c….1790000000.{"id":"8f0c…"}'
23
+ */
24
+ export function ANDCO_WEBHOOK_SIGNED_CONTENT(eventId, timestamp, rawBody) {
25
+ return `${eventId}.${timestamp}.${rawBody}`;
26
+ }
27
+ /**
28
+ * Formats the `andco-signature` header value.
29
+ *
30
+ * @example
31
+ * ANDCO_WEBHOOK_SIGNATURE_HEADER("whk_2026_10", "kV3…");
32
+ * // => "kid=whk_2026_10, alg=Ed25519, sig=kV3…"
33
+ */
34
+ export function ANDCO_WEBHOOK_SIGNATURE_HEADER(kid, signature) {
35
+ return `kid=${kid}, alg=${ANDCO_WEBHOOK_ALGORITHM}, sig=${signature}`;
36
+ }
37
+ /** Why a delivery was rejected. Compare against these members, and keep a default branch. */
38
+ export const ANDCO_WEBHOOK_ERROR_CODES = {
39
+ /** `andco-event-id`, `andco-timestamp` or `andco-signature` is missing. */
40
+ MISSING_HEADERS: "webhook_missing_headers",
41
+ /** `andco-signature` is not `kid=…, alg=Ed25519, sig=…`. */
42
+ MALFORMED_SIGNATURE: "webhook_malformed_signature",
43
+ /** The timestamp is not a number or lies outside the tolerance window. */
44
+ STALE_TIMESTAMP: "webhook_stale_timestamp",
45
+ /** The JWKS has no Ed25519 key with this `kid`, even after a refresh. */
46
+ UNKNOWN_KEY: "webhook_unknown_key",
47
+ /** The signature does not match the signed content. */
48
+ INVALID_SIGNATURE: "webhook_invalid_signature",
49
+ /** The body is not an event, or its `id` differs from `andco-event-id`. */
50
+ INVALID_PAYLOAD: "webhook_invalid_payload",
51
+ /** The JWKS could not be fetched or is not a JWKS. */
52
+ JWKS_UNAVAILABLE: "webhook_jwks_unavailable",
53
+ };
54
+ /**
55
+ * A webhook delivery that must not be trusted. Answer it with a 4xx and do not act on its body;
56
+ * Andco retries deliveries that are not acknowledged with a 2xx.
57
+ *
58
+ * @example
59
+ * try {
60
+ * event = await verify(request);
61
+ * } catch (error) {
62
+ * if (error instanceof AndcoWebhookError) return new Response(error.code, { status: 400 });
63
+ * throw error;
64
+ * }
65
+ */
66
+ export class AndcoWebhookError extends Error {
67
+ code;
68
+ name = "AndcoWebhookError";
69
+ constructor(code, message = code, options) {
70
+ super(message, options);
71
+ this.code = code;
72
+ }
73
+ }
74
+ const SIGNATURE_HEADER = /^\s*kid=([A-Za-z0-9._:-]{1,128})\s*,\s*alg=([A-Za-z0-9]+)\s*,\s*sig=([A-Za-z0-9_-]+)\s*$/;
75
+ /** A new `kid` triggers at most one JWKS refresh per this interval, so forged kids cannot flood Andco. */
76
+ const UNKNOWN_KID_REFRESH_MS = 60_000;
77
+ function headerOf(headers, name) {
78
+ if (typeof headers.get === "function")
79
+ return headers.get(name) ?? undefined;
80
+ const record = headers;
81
+ const value = record[name] ?? Object.entries(record).find(([key]) => key.toLowerCase() === name)?.[1];
82
+ return Array.isArray(value) ? value[0] : value;
83
+ }
84
+ function decodeBase64Url(value) {
85
+ try {
86
+ const padded = value
87
+ .replace(/-/g, "+")
88
+ .replace(/_/g, "/")
89
+ .padEnd(Math.ceil(value.length / 4) * 4, "=");
90
+ const binary = atob(padded);
91
+ const bytes = new Uint8Array(binary.length);
92
+ for (let index = 0; index < binary.length; index += 1)
93
+ bytes[index] = binary.charCodeAt(index);
94
+ return bytes;
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ }
100
+ function isEvent(value) {
101
+ if (!value || typeof value !== "object" || Array.isArray(value))
102
+ return false;
103
+ const event = value;
104
+ return (typeof event["id"] === "string" &&
105
+ typeof event["type"] === "string" &&
106
+ event["version"] === 1 &&
107
+ typeof event["occurred_at"] === "string" &&
108
+ typeof event["client_id"] === "string" &&
109
+ typeof event["grant_id"] === "string" &&
110
+ typeof event["cursor"] === "string" &&
111
+ !!event["payload"] &&
112
+ typeof event["payload"] === "object" &&
113
+ !Array.isArray(event["payload"]));
114
+ }
115
+ /**
116
+ * Creates a verifier for Andco webhook deliveries.
117
+ *
118
+ * Andco signs `${eventId}.${timestamp}.${rawBody}` with an Ed25519 key it owns and names the key by
119
+ * `kid` in `andco-signature`. The verifier fetches Andco's public JWKS once, caches every key by
120
+ * `kid`, and refetches only when a delivery names a `kid` it has not seen, which is how Andco rotates
121
+ * keys without any change on the receiver. Verification uses Web Crypto only, so it runs on Node,
122
+ * Deno, Bun, Cloudflare Workers and edge runtimes alike.
123
+ *
124
+ * The returned function throws {@link AndcoWebhookError} when a header is missing, the timestamp is
125
+ * outside the tolerance window, the key is unknown, the signature does not match, or the body's `id`
126
+ * differs from `andco-event-id`. Create the verifier once per process so the key cache is shared.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * // app/api/andco/webhooks/route.ts
131
+ * import { andcoWebhooks } from "@andco/protocol/webhooks";
132
+ *
133
+ * const verify = andcoWebhooks.verifier();
134
+ *
135
+ * export async function POST(request: Request) {
136
+ * const event = await verify(request);
137
+ * if (event.type === "deposit.completed") await markPaid(event.payload["intent_id"] as string);
138
+ * return new Response(null, { status: 204 });
139
+ * }
140
+ * ```
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * // Node http, local development against Platform
145
+ * const verify = andcoWebhooks.verifier({ jwksUrl: "https://bank.localhost/.well-known/webhook-keys.json" });
146
+ * const event = await verify({ body: rawBody, headers: request.headers });
147
+ * ```
148
+ */
149
+ function verifier(options = {}) {
150
+ const jwksUrl = String(options.jwksUrl ?? ANDCO_WEBHOOK_JWKS_URL);
151
+ const tolerance = options.toleranceSeconds ?? ANDCO_WEBHOOK_TOLERANCE_SECONDS;
152
+ const now = options.now ?? (() => Math.floor(Date.now() / 1000));
153
+ const keys = new Map();
154
+ let loading;
155
+ let loadedAt = Number.NEGATIVE_INFINITY;
156
+ async function load() {
157
+ const fetchImpl = options.fetch ?? globalThis.fetch;
158
+ let response;
159
+ try {
160
+ response = await fetchImpl(jwksUrl, { headers: { Accept: "application/json" } });
161
+ }
162
+ catch (error) {
163
+ throw new AndcoWebhookError(ANDCO_WEBHOOK_ERROR_CODES.JWKS_UNAVAILABLE, `Could not fetch ${jwksUrl}`, {
164
+ cause: error,
165
+ });
166
+ }
167
+ const document = response.ok ? await response.json().catch(() => null) : null;
168
+ const entries = document?.keys;
169
+ if (!Array.isArray(entries)) {
170
+ throw new AndcoWebhookError(ANDCO_WEBHOOK_ERROR_CODES.JWKS_UNAVAILABLE, `${jwksUrl} answered ${response.status} without a JWKS`);
171
+ }
172
+ loadedAt = Date.now();
173
+ for (const entry of entries) {
174
+ if (entry?.kty !== "OKP" || entry.crv !== "Ed25519" || typeof entry.x !== "string")
175
+ continue;
176
+ if (typeof entry.kid !== "string" || keys.has(entry.kid))
177
+ continue;
178
+ const jwk = { kty: "OKP", crv: "Ed25519", x: entry.x };
179
+ const key = crypto.subtle.importKey("jwk", jwk, { name: "Ed25519" }, false, ["verify"]);
180
+ key.catch(() => keys.delete(entry.kid));
181
+ keys.set(entry.kid, key);
182
+ }
183
+ console.debug("[andcoWebhooks.verifier] loaded %s webhook keys from %s", keys.size, jwksUrl);
184
+ }
185
+ async function keyFor(kid) {
186
+ const cached = keys.get(kid);
187
+ if (cached)
188
+ return cached;
189
+ if (Date.now() - loadedAt >= UNKNOWN_KID_REFRESH_MS) {
190
+ loading ??= load().finally(() => {
191
+ loading = undefined;
192
+ });
193
+ }
194
+ await loading;
195
+ const loaded = keys.get(kid);
196
+ if (!loaded)
197
+ throw new AndcoWebhookError(ANDCO_WEBHOOK_ERROR_CODES.UNKNOWN_KEY, `Unknown webhook key ${kid}`);
198
+ return loaded;
199
+ }
200
+ return async function verify(delivery) {
201
+ let body;
202
+ let headers;
203
+ if (typeof Request !== "undefined" && delivery instanceof Request) {
204
+ body = await delivery.text();
205
+ headers = delivery.headers;
206
+ }
207
+ else {
208
+ ({ body, headers } = delivery);
209
+ }
210
+ const eventId = headerOf(headers, ANDCO_WEBHOOK_HEADERS.eventId);
211
+ const timestamp = headerOf(headers, ANDCO_WEBHOOK_HEADERS.timestamp);
212
+ const signature = headerOf(headers, ANDCO_WEBHOOK_HEADERS.signature);
213
+ if (!eventId || !timestamp || !signature)
214
+ throw new AndcoWebhookError(ANDCO_WEBHOOK_ERROR_CODES.MISSING_HEADERS);
215
+ const parts = SIGNATURE_HEADER.exec(signature);
216
+ if (!parts || parts[2] !== ANDCO_WEBHOOK_ALGORITHM)
217
+ throw new AndcoWebhookError(ANDCO_WEBHOOK_ERROR_CODES.MALFORMED_SIGNATURE);
218
+ const [, kid, , encoded] = parts;
219
+ const bytes = decodeBase64Url(encoded);
220
+ if (!bytes || bytes.length !== 64)
221
+ throw new AndcoWebhookError(ANDCO_WEBHOOK_ERROR_CODES.MALFORMED_SIGNATURE);
222
+ if (!/^\d{1,12}$/.test(timestamp) || Math.abs(now() - Number(timestamp)) > tolerance)
223
+ throw new AndcoWebhookError(ANDCO_WEBHOOK_ERROR_CODES.STALE_TIMESTAMP);
224
+ const key = await keyFor(kid);
225
+ const content = new TextEncoder().encode(ANDCO_WEBHOOK_SIGNED_CONTENT(eventId, timestamp, body));
226
+ const valid = await crypto.subtle.verify({ name: "Ed25519" }, key, bytes, content);
227
+ if (!valid) {
228
+ console.debug("[andcoWebhooks.verify] signature mismatch for event %s and key %s", eventId, kid);
229
+ throw new AndcoWebhookError(ANDCO_WEBHOOK_ERROR_CODES.INVALID_SIGNATURE);
230
+ }
231
+ let event;
232
+ try {
233
+ event = JSON.parse(body);
234
+ }
235
+ catch {
236
+ event = null;
237
+ }
238
+ if (!isEvent(event) || event.id !== eventId)
239
+ throw new AndcoWebhookError(ANDCO_WEBHOOK_ERROR_CODES.INVALID_PAYLOAD);
240
+ return event;
241
+ };
242
+ }
243
+ /**
244
+ * Receiving Andco webhooks. See {@link verifier}.
245
+ *
246
+ * @example
247
+ * const verify = andcoWebhooks.verifier();
248
+ */
249
+ export const andcoWebhooks = { verifier };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andco/protocol",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "andco": {
5
5
  "release": 1780358400
6
6
  },
@@ -35,6 +35,11 @@
35
35
  "types": "./dist/server.d.ts",
36
36
  "import": "./dist/server.js",
37
37
  "default": "./dist/server.js"
38
+ },
39
+ "./webhooks": {
40
+ "types": "./dist/webhooks.d.ts",
41
+ "import": "./dist/webhooks.js",
42
+ "default": "./dist/webhooks.js"
38
43
  }
39
44
  },
40
45
  "files": [
@@ -45,14 +50,28 @@
45
50
  "valibot": "^1.5.0"
46
51
  },
47
52
  "devDependencies": {
53
+ "ajv": "8.20.0",
48
54
  "openapi-typescript": "^7.13.0",
49
- "typescript": "^6.0.3"
55
+ "typescript": "^6.0.3",
56
+ "yaml": "2.9.1"
50
57
  },
51
58
  "license": "Apache-2.0",
52
59
  "description": "Shared protocol types, message schemas and transport contracts for the Andco SDK.",
60
+ "author": "Patricio Lopez Juri <patricio.lopez@haulmer.com>",
61
+ "repository": {
62
+ "type": "git",
63
+ "url": "git+https://github.com/haulmer/andco-sdk-js.git",
64
+ "directory": "packages/protocol"
65
+ },
66
+ "homepage": "https://github.com/haulmer/andco-sdk-js#readme",
67
+ "bugs": {
68
+ "url": "https://github.com/haulmer/andco-sdk-js/issues"
69
+ },
53
70
  "scripts": {
54
71
  "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
55
72
  "sync-release": "node scripts/sync-release.mjs",
73
+ "generate:containment-cases": "node scripts/generate-account-matcher-containment-cases.mjs",
74
+ "generate:conformance": "node scripts/generate-conformance-vectors.mjs --out ../../../andco-sdk-python/packages/andco-sdk/tests/conformance/andco-protocol.json --out ../../../andco-sdk-ruby/packages/andco-sdk/spec/conformance/andco-protocol.json --out ../../../andco-sdk-go/packages/andco-sdk/testdata/andco-protocol.json",
56
75
  "generate:openapi": "openapi-typescript openapi/oauth-api.yaml -o src/transport/generated/oauth-api.ts && biome format --write src/transport/generated/oauth-api.ts",
57
76
  "build": "pnpm run clean && pnpm run sync-release && tsc",
58
77
  "dev": "tsc --watch --preserveWatchOutput",