@andco/protocol 0.0.11 → 0.0.12

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 (120) hide show
  1. package/dist/api-errors.d.ts +5 -128
  2. package/dist/api-errors.d.ts.map +1 -1
  3. package/dist/api-errors.js +5 -131
  4. package/dist/authorization-preparation.d.ts +3 -3
  5. package/dist/authorization-preparation.d.ts.map +1 -1
  6. package/dist/authorization-preparation.js +4 -0
  7. package/dist/authorization.js +2 -2
  8. package/dist/errors.d.ts +52 -16
  9. package/dist/errors.d.ts.map +1 -1
  10. package/dist/errors.js +52 -12
  11. package/dist/index.d.ts +1 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +1 -0
  14. package/dist/intent-input.d.ts +1791 -725
  15. package/dist/intent-input.d.ts.map +1 -1
  16. package/dist/intent-input.js +325 -157
  17. package/dist/issues.d.ts +61 -0
  18. package/dist/issues.d.ts.map +1 -0
  19. package/dist/issues.js +61 -0
  20. package/dist/messages/index.d.ts +2 -2
  21. package/dist/messages/index.d.ts.map +1 -1
  22. package/dist/messages/index.js +10 -3
  23. package/dist/messages/set-preferences.d.ts +13 -1
  24. package/dist/messages/set-preferences.d.ts.map +1 -1
  25. package/dist/messages/set-preferences.js +31 -9
  26. package/dist/miniapp-manifest.d.ts +2 -2
  27. package/dist/miniapp-manifest.d.ts.map +1 -1
  28. package/dist/miniapp-manifest.js +1 -1
  29. package/dist/native-intent.d.ts +48 -28
  30. package/dist/native-intent.d.ts.map +1 -1
  31. package/dist/native-intent.js +76 -24
  32. package/dist/pagination.d.ts +37 -31
  33. package/dist/pagination.d.ts.map +1 -1
  34. package/dist/pagination.js +72 -24
  35. package/dist/rar/account-matchers.d.ts +47 -240
  36. package/dist/rar/account-matchers.d.ts.map +1 -1
  37. package/dist/rar/account-matchers.js +52 -131
  38. package/dist/rar/bank.d.ts +280 -392
  39. package/dist/rar/bank.d.ts.map +1 -1
  40. package/dist/rar/bank.js +68 -137
  41. package/dist/rar/catalog.d.ts +305 -288
  42. package/dist/rar/catalog.d.ts.map +1 -1
  43. package/dist/rar/catalog.js +69 -29
  44. package/dist/rar/detail.d.ts +15 -32
  45. package/dist/rar/detail.d.ts.map +1 -1
  46. package/dist/rar/detail.js +14 -34
  47. package/dist/rar/index.d.ts +2 -1
  48. package/dist/rar/index.d.ts.map +1 -1
  49. package/dist/rar/index.js +2 -1
  50. package/dist/rar/json-schemas.generated.d.ts +4 -0
  51. package/dist/rar/json-schemas.generated.d.ts.map +1 -0
  52. package/dist/rar/json-schemas.generated.js +3570 -0
  53. package/dist/rar/money.d.ts +5 -5
  54. package/dist/rar/money.d.ts.map +1 -1
  55. package/dist/rar/money.js +5 -5
  56. package/dist/rar/project-users.d.ts +40 -14
  57. package/dist/rar/project-users.d.ts.map +1 -1
  58. package/dist/rar/project-users.js +20 -23
  59. package/dist/rar/subject-data.d.ts +96 -48
  60. package/dist/rar/subject-data.d.ts.map +1 -1
  61. package/dist/rar/subject-data.js +61 -34
  62. package/dist/rar/subject.d.ts +18 -85
  63. package/dist/rar/subject.d.ts.map +1 -1
  64. package/dist/rar/subject.js +23 -51
  65. package/dist/rest/accounts.d.ts +347 -0
  66. package/dist/rest/accounts.d.ts.map +1 -0
  67. package/dist/rest/accounts.js +108 -0
  68. package/dist/rest/addresses.d.ts +581 -0
  69. package/dist/rest/addresses.d.ts.map +1 -0
  70. package/dist/rest/addresses.js +190 -0
  71. package/dist/rest/api-error.d.ts +104 -0
  72. package/dist/rest/api-error.d.ts.map +1 -0
  73. package/dist/rest/api-error.js +103 -0
  74. package/dist/rest/authorization.d.ts +123 -0
  75. package/dist/rest/authorization.d.ts.map +1 -0
  76. package/dist/rest/authorization.js +62 -0
  77. package/dist/rest/catalog.d.ts +199 -0
  78. package/dist/rest/catalog.d.ts.map +1 -0
  79. package/dist/rest/catalog.js +63 -0
  80. package/dist/rest/common.d.ts +637 -0
  81. package/dist/rest/common.d.ts.map +1 -0
  82. package/dist/rest/common.js +172 -0
  83. package/dist/rest/contract.d.ts +3480 -0
  84. package/dist/rest/contract.d.ts.map +1 -0
  85. package/dist/rest/contract.js +120 -0
  86. package/dist/rest/events.d.ts +145 -0
  87. package/dist/rest/events.d.ts.map +1 -0
  88. package/dist/rest/events.js +42 -0
  89. package/dist/rest/http.d.ts +49 -0
  90. package/dist/rest/http.d.ts.map +1 -0
  91. package/dist/rest/http.js +25 -0
  92. package/dist/rest/identity.d.ts +627 -0
  93. package/dist/rest/identity.d.ts.map +1 -0
  94. package/dist/rest/identity.js +128 -0
  95. package/dist/rest/index.d.ts +14 -0
  96. package/dist/rest/index.d.ts.map +1 -0
  97. package/dist/rest/index.js +13 -0
  98. package/dist/rest/intents.d.ts +4556 -0
  99. package/dist/rest/intents.d.ts.map +1 -0
  100. package/dist/rest/intents.js +551 -0
  101. package/dist/rest/signatures.d.ts +110 -0
  102. package/dist/rest/signatures.d.ts.map +1 -0
  103. package/dist/rest/signatures.js +113 -0
  104. package/dist/rest/subjects.d.ts +14 -0
  105. package/dist/rest/subjects.d.ts.map +1 -0
  106. package/dist/rest/subjects.js +22 -0
  107. package/dist/service-grants.d.ts +2 -2
  108. package/dist/service-grants.d.ts.map +1 -1
  109. package/dist/service-grants.js +1 -1
  110. package/dist/transport/generated/oauth-api.d.ts +5547 -1448
  111. package/dist/transport/generated/oauth-api.d.ts.map +1 -1
  112. package/dist/transport/intents.d.ts +9 -134
  113. package/dist/transport/intents.d.ts.map +1 -1
  114. package/dist/transport/intents.js +21 -405
  115. package/dist/transport/rest.d.ts +15 -5
  116. package/dist/transport/rest.d.ts.map +1 -1
  117. package/dist/userinfo.d.ts +22 -9
  118. package/dist/userinfo.d.ts.map +1 -1
  119. package/dist/userinfo.js +17 -12
  120. package/package.json +13 -2
@@ -1,9 +1,4 @@
1
- import { ErrorExtendable } from "../errors.js";
2
- import { type Pagination } from "../pagination.js";
3
- import { type AndCoRandomSource } from "../utils.js";
4
- import { type AndCoDepositEvent, type AndCoEventPage, type AndCoEventSubscriptionOptions, type AndCoIntentDepositEvent, type AndCoIntentTransferEvent, type AndCoWithdrawalEvent } from "./financial-events.js";
5
1
  import type { components, operations } from "./generated/oauth-api.js";
6
- import type { AndCoRestClient } from "./rest.js";
7
2
  /**
8
3
  * One Andco account of the Grant's subject, by Account Key or by identifier: a transfer's source,
9
4
  * a deposit's destination and the account a closure closes.
@@ -78,139 +73,19 @@ export type AndCoSignedAccountClosureClaims = components["schemas"]["SignedAccou
78
73
  export type AndCoAccountClosureIntent = components["schemas"]["AccountClosureIntent"];
79
74
  /** Any currently supported intent. */
80
75
  export type AndCoIntent = AndCoDepositIntent | AndCoTransferIntent | AndCoAccountOpeningIntent | AndCoAccountClosureIntent;
81
- /** Existing intent ID or a deferred factory that creates one after User activation. */
82
- export type AndCoIntentId = string | (() => Promise<string>);
83
- /** Options for idempotent intent creation. */
84
- export type AndCoIntentCreateOptions = {
85
- /** Stable transport key. The SDK generates a random key when omitted. */
86
- idempotencyKey?: string;
87
- };
88
- /** Error returned by the OAuth intent API. */
89
- export declare class AndCoIntentError extends ErrorExtendable {
90
- readonly code: string;
91
- readonly status: number;
92
- readonly details?: Readonly<Record<string, unknown>> | undefined;
93
- constructor(code: string, status: number, details?: Readonly<Record<string, unknown>> | undefined);
94
- }
95
- /** Creates and reads intents under the current exact OAuth Grant. */
96
- export declare class AndCoIntentsClient {
97
- private readonly rest;
98
- private readonly crypto?;
99
- constructor(rest: AndCoRestClient, crypto?: AndCoRandomSource | undefined);
100
- /** Replays authorized Intent facts after an opaque subject-bound checkpoint. */
101
- getEvents(intentId: string, pagination?: Pagination, signal?: AbortSignal): Promise<AndCoEventPage>;
102
- /** Observes durable deposit facts; callback success acknowledges each checkpoint. */
103
- onIntentDepositEvent(options: AndCoEventSubscriptionOptions & {
104
- intentId: string;
105
- }, handler: (event: AndCoIntentDepositEvent, cursor: string) => void | Promise<void>): import("./financial-events.js").AndCoEventSubscription;
106
- /** Replays bank facts with explicit account movement read authorization. */
107
- getAccountEvents(accountId: string, pagination?: Pagination, signal?: AbortSignal): Promise<AndCoEventPage>;
108
- /** Observes actual account credits and reversals, even when no Intent exists. */
109
- onDepositEvent(options: AndCoEventSubscriptionOptions & {
110
- accountId: string;
111
- }, handler: (event: AndCoDepositEvent, cursor: string) => void | Promise<void>): import("./financial-events.js").AndCoEventSubscription;
112
- /** Observes actual outgoing account transactions; needs `bank_transaction` read over the account. */
113
- onWithdrawalEvent(options: AndCoEventSubscriptionOptions & {
114
- accountId: string;
115
- }, handler: (event: AndCoWithdrawalEvent, cursor: string) => void | Promise<void>): import("./financial-events.js").AndCoEventSubscription;
116
- /**
117
- * Observes this application's transfer lifecycle, including late execution results.
118
- *
119
- * Only Intent events arrive here. The entries a transfer leaves in the accounts it touches are
120
- * account events, and they keep their direction-shaped names: read them with
121
- * {@link AndCoIntentsClient.onWithdrawalEvent} and {@link AndCoIntentsClient.onDepositEvent}.
122
- */
123
- onIntentTransferEvent(options: AndCoEventSubscriptionOptions & {
124
- intentId: string;
125
- }, handler: (event: AndCoIntentTransferEvent, cursor: string) => void | Promise<void>): import("./financial-events.js").AndCoEventSubscription;
126
- /** Creates a deposit; the exact Grant determines its destination account. */
127
- createDeposit(input: AndCoDepositIntentCreate, options?: AndCoIntentCreateOptions): Promise<AndCoDepositIntent>;
128
- /**
129
- * Creates a transfer over `application/json`; omitted idempotency keys are generated cryptographically.
130
- *
131
- * The Intent is born waiting for an Approval. A null `source` or `destination` is the screen: a
132
- * person chooses the account the money leaves from and completes where it goes. Approving it
133
- * without a person means signing it, which is the `application/jwt` half of the same creation.
134
- *
135
- * @example
136
- * const intent = await intents.createTransfer({
137
- * type: "transfer",
138
- * expires_in: "30 minutes",
139
- * source: { type: "account_key", accountKey: "caja-chica-santiago" },
140
- * destination: { type: "account_key", accountKey: "proveedores" },
141
- * amount: { currency: "CLP", value: "1500000" },
142
- * });
143
- */
144
- createTransfer(input: AndCoTransferIntentCreate, options?: AndCoIntentCreateOptions): Promise<AndCoTransferIntent>;
145
- /**
146
- * Sends one already-signed transfer over `application/jwt`, the other half of the same creation.
147
- *
148
- * The body is the compact JWS itself, and every value the transfer uses comes from its verified
149
- * claims — nothing is read from the envelope carrying them, so there is nothing else to pass.
150
- * No `Idempotency-Key` header goes with it: the key is the `jti` inside the signature, and the
151
- * server refuses a second candidate with `400 idempotency_key_not_allowed`.
152
- *
153
- * Signing is not this method's job. It takes an instruction somebody already signed with a
154
- * Signing Key this OAuth Client registered, and puts it on the wire.
155
- *
156
- * @example
157
- * const intent = await intents.createSignedTransfer(await signTransfer(claims));
158
- */
159
- createSignedTransfer(instruction: AndCoSignedInstruction): Promise<AndCoTransferIntent>;
160
- private create;
161
- /** Reads the authoritative masked state of one intent under the same Grant. */
162
- get(intentId: string): Promise<AndCoIntent>;
163
- /** Closes this application's no-target collection with its explicit `close` Grant action. Safe to retry. */
164
- closeDeposit(intentId: string): Promise<AndCoDepositCloseResult>;
165
- /**
166
- * Approves an Intent with the Grant behind this client's token, which must hold `approve` on the
167
- * family that releases the Intent type (`bank_transfer` for a transfer) for the same subject and
168
- * within its maximum; above it the server answers `amount_out_of_grant` and the Intent stays
169
- * pending for another approver.
170
- *
171
- * Acceptance is not completion: whether the money moved arrives as `transfer.succeeded` or
172
- * `transfer.failed`.
173
- *
174
- * @example
175
- * const intent = await intents.approve(intentId);
176
- */
177
- approve(intentId: string): Promise<AndCoIntent>;
178
- /**
179
- * Rejects an Intent as an approver, naming why. The Grant behind this client's token must hold
180
- * `reject` on the family that releases the Intent type. Recorded as a Rejection, apart from the
181
- * creator's Cancellation.
182
- *
183
- * @example
184
- * const intent = await intents.reject(intentId, "duplicated_invoice");
185
- */
186
- reject(intentId: string, reason: string): Promise<AndCoIntent>;
187
- /**
188
- * Withdraws an Intent this client created, naming why. Only the creator cancels; an approver
189
- * declining it uses {@link AndCoIntentsClient.reject}.
190
- *
191
- * Answers {@link ANDCO_INTENT_ERROR_CODES.INTENT_EXPIRED} when the Intent's deadline to be
192
- * approved and executed has already passed.
193
- */
194
- cancel(intentId: string, reason: string): Promise<AndCoIntent>;
195
- }
196
- /** Validates the Andco-owned interaction URL returned for an Intent. */
197
- export declare function ANDCO_INTENT_AUTHORIZATION_URL(intent: AndCoIntent, interactionOrigin: string | URL): URL;
198
76
  /**
199
- * Rejects anything that is not a compact JWS before it reaches the network.
77
+ * Validates the Andco-owned interaction URL returned for an Intent.
200
78
  *
201
- * This checks the envelope's shape and nothing else. Whether the signature verifies, whether the
202
- * key is registered and whether the claims are a transfer are all the server's answers to give.
79
+ * @throws {AndcoError} `invalid_response` when it is not an https URL on the interaction origin.
203
80
  */
204
- export declare function ASSERT_SIGNED_INSTRUCTION(instruction: string): void;
81
+ export declare function ANDCO_INTENT_AUTHORIZATION_URL(intent: AndCoIntent, interactionOrigin: string | URL): URL;
205
82
  /**
206
- * Syntax of an Intent identifier: a real UUID, version and variant included.
83
+ * Whether a value has the shape of a UUID: any 8-4-4-4-12 hex, with no version or variant check.
84
+ * It is the check the REST contract applies to every identifier, so a caller is refused before
85
+ * the network exactly when the API would refuse it.
207
86
  *
208
- * This is the strict end of the identifier check. Anything laxer -- accepting any UUID-shaped
209
- * string regardless of version or variant nibble -- lets a caller through that this transport
210
- * would reject before it touches the network; other layers derive their own check from this one
211
- * instead of retyping a looser pattern.
87
+ * @example
88
+ * IS_UUID_SHAPED("11111111-1111-4111-8111-111111111111"); // true
212
89
  */
213
- export declare const INTENT_ID_SYNTAX = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$";
214
- /** Rejects identifiers that cannot address an Intent. */
215
- export declare function ASSERT_INTENT_ID(intentId: string): void;
90
+ export declare function IS_UUID_SHAPED(value: string): boolean;
216
91
  //# sourceMappingURL=intents.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"intents.d.ts","sourceRoot":"","sources":["../../src/transport/intents.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,M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AACxG,iGAAiG;AACjG,MAAM,MAAM,yBAAyB,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,sBAAsB,CAAC,CAAC;AACtF,sCAAsC;AACtC,MAAM,MAAM,WAAW,GACnB,kBAAkB,GAClB,mBAAmB,GACnB,yBAAyB,GACzB,yBAAyB,CAAC;AAE9B;;;;GAIG;AACH,wBAAgB,8BAA8B,CAAC,MAAM,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,GAAG,GAAG,GAAG,GAAG,CAcxG;AAID;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAErD"}
@@ -1,420 +1,36 @@
1
- import { ANDCO_INTENT_PROPOSAL_MEDIA_TYPE, ANDCO_SIGNED_INSTRUCTION_MEDIA_TYPE } from "../constants.js";
2
- import { ErrorExtendable } from "../errors.js";
3
- import { safeParseIntentCancellation, safeParseIntentCreate, safeParseIntentRejection, unsupportedIntentShape, } from "../intent-input.js";
4
- import { paginationParameters } from "../pagination.js";
5
- import { ACCOUNT_KEY_SYNTAX } from "../rar/account-matchers.js";
6
- import { MONEY_OR_ZERO_PATTERN, MONEY_PATTERN } from "../rar/money.js";
1
+ import * as v from "valibot";
2
+ import { ANDCO_ERROR_CODES, AndcoError } from "../errors.js";
7
3
  import { SafeURL } from "../urls.js";
8
- import { RANDOM_UUID } from "../utils.js";
9
- import { subscribeFinancialEvents, } from "./financial-events.js";
10
- const MONEY_SYNTAX = /* @__PURE__ */ new RegExp(MONEY_PATTERN);
11
- const MONEY_OR_ZERO_SYNTAX = /* @__PURE__ */ new RegExp(MONEY_OR_ZERO_PATTERN);
12
- const ACCOUNT_KEY_PATTERN = /* @__PURE__ */ new RegExp(ACCOUNT_KEY_SYNTAX);
13
- /** Error returned by the OAuth intent API. */
14
- export class AndCoIntentError extends ErrorExtendable {
15
- code;
16
- status;
17
- details;
18
- constructor(code, status, details) {
19
- super(code);
20
- this.code = code;
21
- this.status = status;
22
- this.details = details;
23
- }
24
- }
25
- /** Creates and reads intents under the current exact OAuth Grant. */
26
- export class AndCoIntentsClient {
27
- rest;
28
- crypto;
29
- constructor(rest, crypto) {
30
- this.rest = rest;
31
- this.crypto = crypto;
32
- }
33
- /** Replays authorized Intent facts after an opaque subject-bound checkpoint. */
34
- async getEvents(intentId, pagination = {}, signal) {
35
- ASSERT_INTENT_ID(intentId);
36
- const { data, error, response } = await this.rest.GET("/intents/{intent_id}/events", {
37
- params: { path: { intent_id: intentId }, query: paginationParameters(pagination) },
38
- signal,
39
- });
40
- if (error || !data)
41
- throw INTENT_ERROR_FROM(error, response.status);
42
- return data;
43
- }
44
- /** Observes durable deposit facts; callback success acknowledges each checkpoint. */
45
- onIntentDepositEvent(options, handler) {
46
- ASSERT_INTENT_ID(options.intentId);
47
- return subscribeFinancialEvents((after, signal) => this.getEvents(options.intentId, { after }, signal), (event) => {
48
- const payload = event["payload"];
49
- const valid = payload?.["intent_id"] === options.intentId.toLowerCase() &&
50
- ((event["type"] === "deposit.target_updated" && VALID_EVENT_AMOUNT(payload["target"])) ||
51
- (event["type"] === "deposit.expired" &&
52
- payload["status"] === "expired" &&
53
- typeof payload["expires_at"] === "string") ||
54
- (event["type"] === "deposit.unassigned" &&
55
- typeof payload["movement_id"] === "string" &&
56
- typeof payload["transaction_id"] === "string" &&
57
- VALID_EVENT_AMOUNT(payload["amount"]) &&
58
- VALID_EVENT_AMOUNT(payload["total"], true)) ||
59
- (event["type"] === "deposit.assigned" &&
60
- typeof payload["movement_id"] === "string" &&
61
- VALID_EVENT_AMOUNT(payload["amount"]) &&
62
- VALID_EVENT_AMOUNT(payload["total"], true) &&
63
- typeof payload["late"] === "boolean") ||
64
- (event["type"] === "deposit.closed" &&
65
- payload["status"] === "closed" &&
66
- VALID_EVENT_AMOUNT(payload["total"], true) &&
67
- typeof payload["closed_at"] === "string") ||
68
- (event["type"] === "deposit.completed" &&
69
- payload["status"] === "completed" &&
70
- VALID_EVENT_AMOUNT(payload["total"], true) &&
71
- VALID_EVENT_AMOUNT(payload["target"]) &&
72
- typeof payload["completed_at"] === "string"));
73
- if (!valid)
74
- throw new AndCoIntentError("invalid_event_response", 502);
75
- return event;
76
- }, handler, options);
77
- }
78
- /** Replays bank facts with explicit account movement read authorization. */
79
- async getAccountEvents(accountId, pagination = {}, signal) {
80
- ASSERT_INTENT_ID(accountId);
81
- const { data, error, response } = await this.rest.GET("/accounts/{bank_account_id}/events", {
82
- params: { path: { bank_account_id: accountId }, query: paginationParameters(pagination) },
83
- signal,
84
- });
85
- if (error || !data)
86
- throw INTENT_ERROR_FROM(error, response.status);
87
- return data;
88
- }
89
- /** Observes actual account credits and reversals, even when no Intent exists. */
90
- onDepositEvent(options, handler) {
91
- ASSERT_INTENT_ID(options.accountId);
92
- return subscribeFinancialEvents((after, signal) => this.getAccountEvents(options.accountId, { after }, signal), (event) => {
93
- const payload = event["payload"];
94
- if ((event["type"] === "withdrawal.posted" || event["type"] === "withdrawal.reversed") &&
95
- VALID_EVENT_ACCOUNT(payload?.["account"], options.accountId))
96
- return null;
97
- if (!payload ||
98
- !VALID_EVENT_ACCOUNT(payload["account"], options.accountId) ||
99
- !((event["type"] === "deposit.received" && payload["outcome"] === "credited") ||
100
- (event["type"] === "deposit.reversed" &&
101
- payload["outcome"] === "reversed" &&
102
- typeof payload["observed_at"] === "string")) ||
103
- typeof payload["movement_id"] !== "string" ||
104
- typeof payload["transaction_id"] !== "string" ||
105
- !VALID_EVENT_AMOUNT(payload["amount"]) ||
106
- typeof payload["received_at"] !== "string" ||
107
- !(payload["note"] === null || typeof payload["note"] === "string")) {
108
- throw new AndCoIntentError("invalid_event_response", 502);
109
- }
110
- return event;
111
- }, handler, options);
112
- }
113
- /** Observes actual outgoing account transactions; needs `bank_transaction` read over the account. */
114
- onWithdrawalEvent(options, handler) {
115
- ASSERT_INTENT_ID(options.accountId);
116
- return subscribeFinancialEvents((after, signal) => this.getAccountEvents(options.accountId, { after }, signal), (event) => {
117
- const p = event["payload"];
118
- if ((event["type"] === "deposit.received" || event["type"] === "deposit.reversed") &&
119
- VALID_EVENT_ACCOUNT(p?.["account"], options.accountId))
120
- return null;
121
- if (!VALID_EVENT_ACCOUNT(p?.["account"], options.accountId) ||
122
- !((event["type"] === "withdrawal.posted" && p["outcome"] === "posted") ||
123
- (event["type"] === "withdrawal.reversed" &&
124
- p["outcome"] === "reversed" &&
125
- typeof p["observed_at"] === "string")) ||
126
- typeof p["movement_id"] !== "string" ||
127
- typeof p["transaction_id"] !== "string" ||
128
- !VALID_EVENT_AMOUNT(p["amount"]) ||
129
- typeof p["posted_at"] !== "string" ||
130
- !(p["note"] === null || typeof p["note"] === "string"))
131
- throw new AndCoIntentError("invalid_event_response", 502);
132
- return event;
133
- }, handler, options);
134
- }
135
- /**
136
- * Observes this application's transfer lifecycle, including late execution results.
137
- *
138
- * Only Intent events arrive here. The entries a transfer leaves in the accounts it touches are
139
- * account events, and they keep their direction-shaped names: read them with
140
- * {@link AndCoIntentsClient.onWithdrawalEvent} and {@link AndCoIntentsClient.onDepositEvent}.
141
- */
142
- onIntentTransferEvent(options, handler) {
143
- ASSERT_INTENT_ID(options.intentId);
144
- return subscribeFinancialEvents((after, signal) => this.getEvents(options.intentId, { after }, signal), (event) => {
145
- const p = event["payload"];
146
- if (p?.["intent_id"] !== options.intentId.toLowerCase() ||
147
- !/^transfer\.(expired|confirmed|succeeded|failed|cancelled|rejected)$/.test(event["type"]))
148
- throw new AndCoIntentError("invalid_event_response", 502);
149
- if (event["type"] === "transfer.expired") {
150
- if (p["status"] !== "expired" || typeof p["expires_at"] !== "string")
151
- throw new AndCoIntentError("invalid_event_response", 502);
152
- }
153
- else {
154
- const operation = p["operation"];
155
- if (typeof p["status"] !== "string" ||
156
- typeof p["observed_at"] !== "string" ||
157
- !(p["detail"] === null || typeof p["detail"] === "string") ||
158
- !(p["transaction_id"] === null || typeof p["transaction_id"] === "string") ||
159
- !((operation === null && event["type"] !== "transfer.confirmed") || VALID_CONFIRMED_TRANSFER(operation)))
160
- throw new AndCoIntentError("invalid_event_response", 502);
161
- }
162
- return event;
163
- }, handler, options);
164
- }
165
- /** Creates a deposit; the exact Grant determines its destination account. */
166
- async createDeposit(input, options = {}) {
167
- const intent = await this.create(input, options);
168
- if (intent["type"] !== "deposit")
169
- throw new AndCoIntentError("invalid_intent_response", 500);
170
- return intent;
171
- }
172
- /**
173
- * Creates a transfer over `application/json`; omitted idempotency keys are generated cryptographically.
174
- *
175
- * The Intent is born waiting for an Approval. A null `source` or `destination` is the screen: a
176
- * person chooses the account the money leaves from and completes where it goes. Approving it
177
- * without a person means signing it, which is the `application/jwt` half of the same creation.
178
- *
179
- * @example
180
- * const intent = await intents.createTransfer({
181
- * type: "transfer",
182
- * expires_in: "30 minutes",
183
- * source: { type: "account_key", accountKey: "caja-chica-santiago" },
184
- * destination: { type: "account_key", accountKey: "proveedores" },
185
- * amount: { currency: "CLP", value: "1500000" },
186
- * });
187
- */
188
- async createTransfer(input, options = {}) {
189
- const intent = await this.create(input, options);
190
- if (intent["type"] !== "transfer")
191
- throw new AndCoIntentError("invalid_intent_response", 500);
192
- return intent;
193
- }
194
- /**
195
- * Sends one already-signed transfer over `application/jwt`, the other half of the same creation.
196
- *
197
- * The body is the compact JWS itself, and every value the transfer uses comes from its verified
198
- * claims — nothing is read from the envelope carrying them, so there is nothing else to pass.
199
- * No `Idempotency-Key` header goes with it: the key is the `jti` inside the signature, and the
200
- * server refuses a second candidate with `400 idempotency_key_not_allowed`.
201
- *
202
- * Signing is not this method's job. It takes an instruction somebody already signed with a
203
- * Signing Key this OAuth Client registered, and puts it on the wire.
204
- *
205
- * @example
206
- * const intent = await intents.createSignedTransfer(await signTransfer(claims));
207
- */
208
- async createSignedTransfer(instruction) {
209
- ASSERT_SIGNED_INSTRUCTION(instruction);
210
- const { data, error, response } = await this.rest.POST("/intents", {
211
- body: instruction,
212
- headers: { "Content-Type": ANDCO_SIGNED_INSTRUCTION_MEDIA_TYPE },
213
- // A compact JWS is already serialized; the default serializer would JSON-quote it.
214
- bodySerializer: (body) => body,
215
- });
216
- if (error || !data)
217
- throw INTENT_ERROR_FROM(error, response.status);
218
- if (data["type"] !== "transfer")
219
- throw new AndCoIntentError("invalid_intent_response", 500);
220
- return data;
221
- }
222
- async create(input, options) {
223
- const unsupported = unsupportedIntentShape(input);
224
- if (unsupported)
225
- throw new AndCoIntentError("not_implemented", 501, { code: unsupported });
226
- const parsed = safeParseIntentCreate(input);
227
- if (!parsed.success) {
228
- throw new AndCoIntentError("invalid_request", 400, {
229
- issues: parsed.issues.map((issue) => ({ message: issue.message, path: issue.path?.map((entry) => entry.key) })),
230
- });
231
- }
232
- const idempotencyKey = options.idempotencyKey ?? RANDOM_UUID(this.crypto);
233
- if (!/^[A-Za-z0-9._:-]{1,128}$/.test(idempotencyKey)) {
234
- throw new TypeError("Invalid Idempotency-Key");
235
- }
236
- // The endpoint answers to two content types, so which of the two representations this is has to
237
- // be said rather than left to a transport default.
238
- const { data, error, response } = await this.rest.POST("/intents", {
239
- body: input,
240
- headers: { "Content-Type": ANDCO_INTENT_PROPOSAL_MEDIA_TYPE },
241
- params: { header: { "Idempotency-Key": idempotencyKey } },
242
- });
243
- if (error || !data)
244
- throw INTENT_ERROR_FROM(error, response.status);
245
- return data;
246
- }
247
- /** Reads the authoritative masked state of one intent under the same Grant. */
248
- async get(intentId) {
249
- ASSERT_INTENT_ID(intentId);
250
- const { data, error, response } = await this.rest.GET("/intents/{intent_id}", {
251
- params: { path: { intent_id: intentId } },
252
- });
253
- if (error || !data)
254
- throw INTENT_ERROR_FROM(error, response.status);
255
- return data;
256
- }
257
- /** Closes this application's no-target collection with its explicit `close` Grant action. Safe to retry. */
258
- async closeDeposit(intentId) {
259
- ASSERT_INTENT_ID(intentId);
260
- const { data, error, response } = await this.rest.POST("/intents/{intent_id}/close", {
261
- params: { path: { intent_id: intentId } },
262
- });
263
- if (error || !data)
264
- throw INTENT_ERROR_FROM(error, response.status);
265
- return data;
266
- }
267
- /**
268
- * Approves an Intent with the Grant behind this client's token, which must hold `approve` on the
269
- * family that releases the Intent type (`bank_transfer` for a transfer) for the same subject and
270
- * within its maximum; above it the server answers `amount_out_of_grant` and the Intent stays
271
- * pending for another approver.
272
- *
273
- * Acceptance is not completion: whether the money moved arrives as `transfer.succeeded` or
274
- * `transfer.failed`.
275
- *
276
- * @example
277
- * const intent = await intents.approve(intentId);
278
- */
279
- async approve(intentId) {
280
- ASSERT_INTENT_ID(intentId);
281
- const { data, error, response } = await this.rest.POST("/intents/{intent_id}/approve", {
282
- params: { path: { intent_id: intentId } },
283
- });
284
- if (error || !data)
285
- throw INTENT_ERROR_FROM(error, response.status);
286
- return data;
287
- }
288
- /**
289
- * Rejects an Intent as an approver, naming why. The Grant behind this client's token must hold
290
- * `reject` on the family that releases the Intent type. Recorded as a Rejection, apart from the
291
- * creator's Cancellation.
292
- *
293
- * @example
294
- * const intent = await intents.reject(intentId, "duplicated_invoice");
295
- */
296
- async reject(intentId, reason) {
297
- ASSERT_INTENT_ID(intentId);
298
- const parsed = safeParseIntentRejection({ reason });
299
- if (!parsed.success)
300
- throw new AndCoIntentError("invalid_request", 400, { code: "rejection_reason_required" });
301
- const { data, error, response } = await this.rest.POST("/intents/{intent_id}/reject", {
302
- params: { path: { intent_id: intentId } },
303
- body: { reason: parsed.output.reason },
304
- });
305
- if (error || !data)
306
- throw INTENT_ERROR_FROM(error, response.status);
307
- return data;
308
- }
309
- /**
310
- * Withdraws an Intent this client created, naming why. Only the creator cancels; an approver
311
- * declining it uses {@link AndCoIntentsClient.reject}.
312
- *
313
- * Answers {@link ANDCO_INTENT_ERROR_CODES.INTENT_EXPIRED} when the Intent's deadline to be
314
- * approved and executed has already passed.
315
- */
316
- async cancel(intentId, reason) {
317
- ASSERT_INTENT_ID(intentId);
318
- const parsed = safeParseIntentCancellation({ reason });
319
- if (!parsed.success)
320
- throw new AndCoIntentError("invalid_request", 400, { code: "cancellation_reason_required" });
321
- const { data, error, response } = await this.rest.POST("/intents/{intent_id}/cancel", {
322
- params: { path: { intent_id: intentId } },
323
- body: { reason: parsed.output.reason },
324
- });
325
- if (error || !data)
326
- throw INTENT_ERROR_FROM(error, response.status);
327
- return data;
328
- }
329
- }
330
- /** Validates the Andco-owned interaction URL returned for an Intent. */
4
+ /**
5
+ * Validates the Andco-owned interaction URL returned for an Intent.
6
+ *
7
+ * @throws {AndcoError} `invalid_response` when it is not an https URL on the interaction origin.
8
+ */
331
9
  export function ANDCO_INTENT_AUTHORIZATION_URL(intent, interactionOrigin) {
332
10
  try {
333
11
  const expectedOrigin = new SafeURL(interactionOrigin).origin;
334
12
  const authorizationURL = new SafeURL(intent.authorization_url);
335
13
  if (authorizationURL.origin !== expectedOrigin || authorizationURL.protocol !== "https:") {
336
- throw new AndCoIntentError("invalid_authorization_url", 500);
14
+ throw new TypeError("authorization_url is not an https URL on the interaction origin");
337
15
  }
338
16
  return authorizationURL;
339
17
  }
340
- catch (error) {
341
- if (error instanceof AndCoIntentError)
342
- throw error;
343
- throw new AndCoIntentError("invalid_authorization_url", 500);
344
- }
345
- }
346
- /**
347
- * Rejects anything that is not a compact JWS before it reaches the network.
348
- *
349
- * This checks the envelope's shape and nothing else. Whether the signature verifies, whether the
350
- * key is registered and whether the claims are a transfer are all the server's answers to give.
351
- */
352
- export function ASSERT_SIGNED_INSTRUCTION(instruction) {
353
- if (!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(instruction)) {
354
- throw new TypeError("Invalid Signed Instruction");
18
+ catch (cause) {
19
+ throw new AndcoError(ANDCO_ERROR_CODES.INVALID_RESPONSE, {
20
+ message: "The Intent's authorization_url is not an https URL on the interaction origin",
21
+ cause,
22
+ });
355
23
  }
356
24
  }
25
+ const UUID = /* @__PURE__ */ v.pipe(v.string(), v.uuid());
357
26
  /**
358
- * Syntax of an Intent identifier: a real UUID, version and variant included.
27
+ * Whether a value has the shape of a UUID: any 8-4-4-4-12 hex, with no version or variant check.
28
+ * It is the check the REST contract applies to every identifier, so a caller is refused before
29
+ * the network exactly when the API would refuse it.
359
30
  *
360
- * This is the strict end of the identifier check. Anything laxer -- accepting any UUID-shaped
361
- * string regardless of version or variant nibble -- lets a caller through that this transport
362
- * would reject before it touches the network; other layers derive their own check from this one
363
- * instead of retyping a looser pattern.
364
- */
365
- export const INTENT_ID_SYNTAX = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$";
366
- /** Rejects identifiers that cannot address an Intent. */
367
- export function ASSERT_INTENT_ID(intentId) {
368
- if (!new RegExp(INTENT_ID_SYNTAX, "i").test(intentId)) {
369
- throw new TypeError("Invalid intent ID");
370
- }
371
- }
372
- function INTENT_ERROR_FROM(error, status) {
373
- if (error && typeof error === "object" && "error" in error && typeof error["error"] === "string") {
374
- return new AndCoIntentError(error["error"], status, error);
375
- }
376
- return new AndCoIntentError("api_error", status);
377
- }
378
- /**
379
- * `{ currency: "CLP", value }` with the value an exact decimal string inside the monetary contract.
380
- * A running total may be zero (nothing credited yet); every other amount moves money.
31
+ * @example
32
+ * IS_UUID_SHAPED("11111111-1111-4111-8111-111111111111"); // true
381
33
  */
382
- function VALID_EVENT_AMOUNT(value, allowZero = false) {
383
- if (!value || typeof value !== "object")
384
- return false;
385
- const a = value;
386
- return (a["currency"] === "CLP" &&
387
- typeof a["value"] === "string" &&
388
- (allowZero ? MONEY_OR_ZERO_SYNTAX : MONEY_SYNTAX).test(a["value"]));
389
- }
390
- /** `{ type: "account", id }`; with `expectedId`, the account must be exactly that one. */
391
- function VALID_EVENT_ACCOUNT(value, expectedId) {
392
- if (!value || typeof value !== "object")
393
- return false;
394
- const a = value;
395
- if (a["type"] !== "account" || typeof a["id"] !== "string" || a["id"] === "")
396
- return false;
397
- return expectedId === undefined || a["id"] === expectedId.toLowerCase();
398
- }
399
- function VALID_CONFIRMED_TRANSFER(value) {
400
- if (!value || typeof value !== "object")
401
- return false;
402
- const p = value;
403
- return (VALID_EVENT_ACCOUNT(p["source"]) &&
404
- VALID_EVENT_AMOUNT(p["amount"]) &&
405
- typeof p["note"] === "string" &&
406
- VALID_TRANSFER_DESTINATION(p["destination"]));
407
- }
408
- /** An Andco account by identifier, an Andco account by Account Key, or an account at another bank. */
409
- function VALID_TRANSFER_DESTINATION(value) {
410
- if (!value || typeof value !== "object")
411
- return false;
412
- const d = value;
413
- if (d["type"] === "account")
414
- return VALID_EVENT_ACCOUNT(d);
415
- if (d["type"] === "account_key")
416
- return typeof d["accountKey"] === "string" && ACCOUNT_KEY_PATTERN.test(d["accountKey"]);
417
- return (d["type"] === "external" &&
418
- ["checking", "debit", "savings"].includes(String(d["account_type"])) &&
419
- ["bank_id", "account_id", "holder_id", "holder_name"].every((key) => typeof d[key] === "string" && d[key] !== ""));
34
+ export function IS_UUID_SHAPED(value) {
35
+ return v.safeParse(UUID, value).success;
420
36
  }
@@ -4,19 +4,29 @@ export type AndCoRestClient = Client<paths>;
4
4
  /**
5
5
  * The generated path map behind `AndCoRestClient`.
6
6
  *
7
- * Exported because a library that builds on an openapi-fetch client — `openapi-react-query`, say —
8
- * takes `paths` as an explicit type argument. TypeScript cannot infer it back out of a client's
9
- * generic method signatures, so without this the caller has nothing to name.
7
+ * Exported because a library that builds on an openapi-fetch client takes `paths` as an explicit type
8
+ * argument: TypeScript cannot infer it back out of a client's generic method signatures, so without this
9
+ * the caller has nothing to name. In React, `createAndcoQueryClient` from `@andco/sdk-react/query`
10
+ * already does this over `andco.rest` with the SDK's errors.
10
11
  *
11
12
  * @example
12
13
  * ```ts
13
- * const $api = createQueryClient<AndCoRestPaths>(andco.rest.http);
14
+ * const $api = createQueryClient<AndCoRestPaths>(andco.rest.raw);
14
15
  * ```
15
16
  */
16
17
  export type AndCoRestPaths = paths;
17
18
  export type AndCoRestAccessToken = string | null | ((request: Request) => string | null | Promise<string | null>);
18
- /** One identity of a Profile, read from `GET /profiles/{profile_id}/identities`. */
19
+ /**
20
+ * One identity of a Profile, read from `GET /profiles/{profile_id}/identities`. `validation` comes only when the
21
+ * Grant's `identity` detail asked for it with `validation: { required: true }`: then it is the
22
+ * {@link AndCoIdentityValidation}, or `null` when this identity has none. Without that request the field is absent.
23
+ */
19
24
  export type AndCoProfileIdentity = components["schemas"]["ProfileIdentity"];
25
+ /**
26
+ * What Andco Core validated about a Profile's identity: who (`validated_by`), when (`validated_at`), the kinds of
27
+ * evidence and Core's `verification_id`, which is the reference to keep.
28
+ */
29
+ export type AndCoIdentityValidation = components["schemas"]["IdentityValidation"];
20
30
  export type AndCoProfileIdentityPage = components["schemas"]["ProfileIdentityPage"];
21
31
  /** One legal identity of an Organization, read from `GET /organizations/{organization_id}/identities`. */
22
32
  export type AndCoOrganizationIdentity = components["schemas"]["OrganizationIdentity"];