@myfield/sdk 0.9.2 → 0.9.3

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.
@@ -1,254 +0,0 @@
1
- import { b64urlToBytes, bytesToB64url, stableStringify, utf8Encode } from "../internal/encoding.ts";
2
- import type { BucketKeyGrantEnvelope } from "../bucket/keys.ts";
3
- import type { AuthCapability, BucketAccessGrant } from "./types.ts";
4
- import { isValidBucketId, isValidInstanceId, isValidMfid, isPublicP256EcJwk, parseBucketResourceId } from "./identifiers.ts";
5
-
6
- const AUTH_CALLBACK_FRAGMENT_PARAM = "mf_auth_result";
7
-
8
- export type StoredAuthAuthorizationResult = {
9
- v: 1;
10
- requestId: string;
11
- state: string;
12
- result: "approved";
13
- mfid: string;
14
- resourceId: string;
15
- instanceId: string;
16
- createdAt: string;
17
- resourceApiUrl?: string;
18
- bucketAccessGrant?: BucketAccessGrant;
19
- expiresAt?: string;
20
- };
21
-
22
- export type EncryptedAuthAuthorizationResultEnvelope = {
23
- v: 1;
24
- typ: "auth.authorization-result.envelope.v1";
25
- alg: "ECDH-HKDF-SHA-256/AES-GCM-256";
26
- requestId: string;
27
- state: string;
28
- resourceId: string;
29
- instanceId: string;
30
- ephemeralPublicJwk: JsonWebKey;
31
- salt: string;
32
- iv: string;
33
- aad: string;
34
- ciphertext: string;
35
- };
36
-
37
- type AuthRequestFields = {
38
- clientId: string;
39
- requestId: string;
40
- state: string;
41
- redirectUri: string;
42
- origin: string;
43
- resourceId: string;
44
- capabilities: AuthCapability[];
45
- instanceId: string;
46
- instanceSigningPublicJwk: JsonWebKey;
47
- instanceWrappingPublicJwk: JsonWebKey;
48
- createdAt: string;
49
- };
50
-
51
- export function buildAuthRequestFragment(request: AuthRequestFields): string {
52
- if (!request.requestId || !request.state) throw new Error("auth request state required");
53
- if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
54
- if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
55
- if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
56
- const redirect = new URL(request.redirectUri);
57
- const origin = new URL(request.origin);
58
- if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
59
- const wire = {
60
- response_type: "code",
61
- client_id: request.clientId,
62
- redirect_uri: request.redirectUri,
63
- state: request.state,
64
- scope: request.capabilities.join(" "),
65
- resource_id: request.resourceId,
66
- mf_v: 1,
67
- mf_auth_mode: "v1",
68
- mf_request_id: request.requestId,
69
- mf_instance_id: request.instanceId,
70
- mf_instance_signing_jwk: request.instanceSigningPublicJwk,
71
- mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
72
- mf_issued_at: request.createdAt,
73
- };
74
- return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
75
- }
76
-
77
- export function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl: string): EncryptedAuthAuthorizationResultEnvelope | null {
78
- const input = String(fragmentOrUrl || "");
79
- const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
80
- if (!rawFragment) return null;
81
- const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
82
- if (!encoded) return null;
83
- const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded))) as Partial<EncryptedAuthAuthorizationResultEnvelope> | null;
84
- if (
85
- !envelope ||
86
- envelope.v !== 1 ||
87
- envelope.typ !== "auth.authorization-result.envelope.v1" ||
88
- envelope.alg !== "ECDH-HKDF-SHA-256/AES-GCM-256" ||
89
- typeof envelope.requestId !== "string" ||
90
- typeof envelope.state !== "string" ||
91
- !parseBucketResourceId(envelope.resourceId) ||
92
- !isValidInstanceId(envelope.instanceId || "") ||
93
- !isPublicP256EcJwk(envelope.ephemeralPublicJwk) ||
94
- typeof envelope.salt !== "string" ||
95
- typeof envelope.iv !== "string" ||
96
- typeof envelope.aad !== "string" ||
97
- typeof envelope.ciphertext !== "string"
98
- ) {
99
- throw new Error("auth callback result fragment invalid");
100
- }
101
- return envelope as EncryptedAuthAuthorizationResultEnvelope;
102
- }
103
-
104
- export async function decryptEncryptedAuthAuthorizationResult(input: {
105
- envelope: EncryptedAuthAuthorizationResultEnvelope;
106
- instanceWrappingPrivateKey: CryptoKey;
107
- expectedRequestId?: string;
108
- expectedState?: string;
109
- expectedResourceId?: string;
110
- expectedInstanceId?: string;
111
- }): Promise<StoredAuthAuthorizationResult> {
112
- const { envelope } = input;
113
- if (
114
- (input.expectedRequestId && envelope.requestId !== input.expectedRequestId) ||
115
- (input.expectedState && envelope.state !== input.expectedState) ||
116
- (input.expectedResourceId && envelope.resourceId !== input.expectedResourceId) ||
117
- (input.expectedInstanceId && envelope.instanceId !== input.expectedInstanceId)
118
- ) {
119
- throw new Error("auth callback result mismatch");
120
- }
121
- const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
122
- const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, input.instanceWrappingPrivateKey, 256);
123
- const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
124
- const wrappingKey = await crypto.subtle.deriveKey(
125
- { name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt) as BufferSource, info: utf8Encode(envelope.aad) },
126
- material,
127
- { name: "AES-GCM", length: 256 },
128
- false,
129
- ["decrypt"]
130
- );
131
- const plaintext = await crypto.subtle.decrypt(
132
- { name: "AES-GCM", iv: b64urlToBytes(envelope.iv) as BufferSource, additionalData: utf8Encode(envelope.aad) },
133
- wrappingKey,
134
- b64urlToBytes(envelope.ciphertext) as BufferSource
135
- );
136
- const result = normalizeAuthAuthorizationResult(JSON.parse(new TextDecoder().decode(plaintext)), envelope.requestId);
137
- if (
138
- !result ||
139
- result.state !== envelope.state ||
140
- result.resourceId !== envelope.resourceId ||
141
- result.instanceId !== envelope.instanceId ||
142
- (input.expectedState && result.state !== input.expectedState) ||
143
- (input.expectedResourceId && result.resourceId !== input.expectedResourceId) ||
144
- (input.expectedInstanceId && result.instanceId !== input.expectedInstanceId)
145
- ) {
146
- throw new Error("auth callback result mismatch");
147
- }
148
- return result;
149
- }
150
-
151
- function normalizeAuthAuthorizationResult(value: unknown, expectedRequestId?: string): StoredAuthAuthorizationResult | null {
152
- const row = value as Partial<StoredAuthAuthorizationResult> | null;
153
- if (
154
- !row ||
155
- row.v !== 1 ||
156
- row.result !== "approved" ||
157
- typeof row.requestId !== "string" ||
158
- (expectedRequestId && row.requestId !== expectedRequestId) ||
159
- typeof row.state !== "string" ||
160
- !isValidMfid(row.mfid || "") ||
161
- !parseBucketResourceId(row.resourceId) ||
162
- !isValidInstanceId(row.instanceId || "") ||
163
- typeof row.createdAt !== "string"
164
- ) {
165
- return null;
166
- }
167
- if (row.expiresAt !== undefined) {
168
- const expiresAt = Date.parse(String(row.expiresAt));
169
- if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
170
- }
171
- const resource = parseBucketResourceId(row.resourceId);
172
- if (!resource) return null;
173
- const bucketAccessGrant = normalizeBucketAccessGrant(row.bucketAccessGrant);
174
- if (!bucketAccessGrant) return null;
175
- if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
176
- return null;
177
- }
178
- return {
179
- v: 1,
180
- requestId: row.requestId,
181
- state: row.state,
182
- result: "approved",
183
- mfid: row.mfid!,
184
- resourceId: resource.resourceId,
185
- instanceId: row.instanceId!,
186
- createdAt: row.createdAt,
187
- ...(typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {}),
188
- bucketAccessGrant,
189
- ...(row.expiresAt ? { expiresAt: row.expiresAt } : {}),
190
- };
191
- }
192
-
193
- export function normalizeBucketAccessGrant(value: unknown): BucketAccessGrant | null {
194
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
195
- const row = value as Partial<BucketAccessGrant>;
196
- const resource = parseBucketResourceId(row.resourceId);
197
- const capabilities = normalizeCapabilities(row.capabilities);
198
- if (
199
- row.v !== 1 ||
200
- !/^ar_[a-f0-9]{32}$/.test(String(row.grantRecordId || "")) ||
201
- !isValidMfid(row.mfid) ||
202
- !resource ||
203
- !isValidInstanceId(row.instanceId) ||
204
- !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) ||
205
- capabilities.length < 1 ||
206
- !isValidBucketKeyGrantEnvelope(row.envelope, row.instanceId, row.keyId)
207
- ) {
208
- return null;
209
- }
210
- return {
211
- v: 1,
212
- grantRecordId: row.grantRecordId!,
213
- mfid: row.mfid!,
214
- resourceId: resource.resourceId,
215
- instanceId: row.instanceId!,
216
- issuedAt: String(row.issuedAt || ""),
217
- keyId: row.keyId!,
218
- capabilities,
219
- envelope: row.envelope as BucketKeyGrantEnvelope,
220
- };
221
- }
222
-
223
- function isValidBucketKeyGrantEnvelope(value: unknown, instanceId?: string, keyId?: string): value is BucketKeyGrantEnvelope {
224
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
225
- const row = value as Partial<BucketKeyGrantEnvelope>;
226
- if (
227
- row.kind !== "bucket-key" ||
228
- !isValidBucketId(row.bucketId) ||
229
- !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) ||
230
- !isValidInstanceId(row.targetInstanceId) ||
231
- row.wrapAlg !== "ECDH-HKDF-SHA-256/AES-GCM-256" ||
232
- !isPublicP256EcJwk(row.targetWrappingPublicJwk) ||
233
- !isPublicP256EcJwk(row.ephemeralPublicJwk) ||
234
- typeof row.salt !== "string" ||
235
- typeof row.iv !== "string" ||
236
- typeof row.aad !== "string" ||
237
- typeof row.ciphertext !== "string"
238
- ) {
239
- return false;
240
- }
241
- if (instanceId && row.targetInstanceId !== instanceId) return false;
242
- if (keyId && row.keyId !== keyId) return false;
243
- return true;
244
- }
245
-
246
- function normalizeCapabilities(input: unknown): AuthCapability[] {
247
- if (!Array.isArray(input)) return [];
248
- const allowed = new Set<AuthCapability>(["read", "write"]);
249
- const result: AuthCapability[] = [];
250
- for (const item of input) {
251
- if (allowed.has(item as AuthCapability) && !result.includes(item as AuthCapability)) result.push(item as AuthCapability);
252
- }
253
- return result.sort();
254
- }
package/src/auth/flow.ts DELETED
@@ -1,93 +0,0 @@
1
- import type { InstanceAuthClient } from "./instance.ts";
2
- import type { StorageAdapter } from "../bucket/store.ts";
3
- import { ClientError } from "../errors.ts";
4
- import { authRecordKeys } from "./store.ts";
5
- import { bucketResourceId } from "./identifiers.ts";
6
-
7
- const notAuthorized = (message: string, cause?: unknown) => new ClientError("NOT_AUTHORIZED", message, { cause });
8
-
9
- export function createAuthorizationFlow(deps: { getAppId(): string; getBucketId?(): string; persistent?: boolean }) {
10
- const getBucketId = deps.getBucketId ?? deps.getAppId;
11
- let closeAuthorization = () => {};
12
- async function ownCallback(url: URL, storage: StorageAdapter): Promise<boolean> {
13
- const resourceId = bucketResourceId(getBucketId());
14
- const requestId = url.searchParams.get("mf_request_id");
15
- if (!requestId) return false;
16
- const keys = authRecordKeys(deps.getAppId());
17
- const pointer = await storage.get<{ resourceId: string; pendingKey: string; requestId: string }>(keys.callback(requestId));
18
- if (pointer?.resourceId !== resourceId || pointer.requestId !== requestId) return false;
19
- const pending = await storage.get<{ resourceId: string }>(pointer.pendingKey);
20
- if (pending && pending.resourceId !== resourceId) return false;
21
- return true;
22
- }
23
-
24
- function clearCallbackUrl(url: URL) {
25
- const current = new URL(window.location.href);
26
- if (current.searchParams.get("mf_request_id") !== url.searchParams.get("mf_request_id")) return;
27
- for (const key of ["state", "error", "error_description", "error_uri", "mf_request_id", "mf_result"]) current.searchParams.delete(key);
28
- const hash = new URLSearchParams(current.hash.slice(1));
29
- if (hash.has("mf_auth_result")) { hash.delete("mf_auth_result"); current.hash = hash.toString(); }
30
- window.history.replaceState(null, "", current.href);
31
- }
32
-
33
- async function handleCallback(auth: InstanceAuthClient, url: URL, signal: AbortSignal, addressBar: boolean) {
34
- try {
35
- const result = await auth.handleCallback(url.href);
36
- signal.throwIfAborted();
37
- if (result?.result !== "approved") throw notAuthorized(result?.errorDescription || result?.result || "Invalid authorization callback");
38
- } catch (error) {
39
- signal.throwIfAborted();
40
- if (error instanceof ClientError && error.code === "NOT_AUTHORIZED") throw error;
41
- throw notAuthorized("Invalid authorization callback", error);
42
- } finally {
43
- if (addressBar) clearCallbackUrl(url);
44
- }
45
- }
46
-
47
- function requestAuthorization(auth: InstanceAuthClient, storage: StorageAdapter, url: string, signal: AbortSignal, setPopup: (popup: Window | null) => void): Promise<void> {
48
- signal.throwIfAborted();
49
- const ios = typeof navigator !== "undefined" && (/iPad|iPhone|iPod/.test(navigator.userAgent)
50
- || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1));
51
- const popup = ios ? null : window.open("about:blank", `myfield-sdk-auth:${getBucketId()}`, "popup=yes,width=520,height=720");
52
- if (!popup && deps.persistent === false) throw new ClientError("INVALID_STATE", "Redirect authorization requires persistent storage");
53
- setPopup(popup);
54
- return new Promise<void>((resolve, reject) => {
55
- let processing = false;
56
- let settled = false;
57
- let timer: ReturnType<typeof setInterval> | undefined;
58
- const finish = (error?: unknown) => {
59
- if (settled) return;
60
- settled = true;
61
- if (timer) clearInterval(timer);
62
- window.removeEventListener("message", onMessage);
63
- signal.removeEventListener("abort", onAbort);
64
- popup?.close();
65
- closeAuthorization = () => {};
66
- if (error) reject(error); else resolve();
67
- };
68
- const onAbort = () => finish(signal.reason);
69
- const onMessage = (event: MessageEvent) => {
70
- if (!popup || event.source !== popup || ![new URL(url).origin, window.location.origin].includes(event.origin)) return;
71
- const message = event.data as { type?: string; callbackUrl?: string } | null;
72
- if (!message || message.type !== "myfield.auth.callback" || typeof message.callbackUrl !== "string") return;
73
- void (async () => {
74
- let callbackUrl: URL;
75
- try { callbackUrl = new URL(message.callbackUrl!); } catch { return; }
76
- if (!await ownCallback(callbackUrl, storage) || processing || settled) return;
77
- processing = true;
78
- await handleCallback(auth, callbackUrl, signal, false);
79
- finish();
80
- })().catch(finish);
81
- };
82
- window.addEventListener("message", onMessage);
83
- signal.addEventListener("abort", onAbort, { once: true });
84
- closeAuthorization = onAbort;
85
- if (popup) timer = setInterval(() => {
86
- if (popup.closed && !processing) finish(notAuthorized("Authorization window closed"));
87
- }, 250);
88
- void auth.authorize({ bucketId: getBucketId() }).catch(finish);
89
- });
90
- }
91
-
92
- return { ownCallback, handleCallback, requestAuthorization, close: () => closeAuthorization() };
93
- }
@@ -1,46 +0,0 @@
1
- import { ClientError } from "../errors.ts";
2
-
3
- export function isValidBucketId(value: unknown): value is string {
4
- const safe = typeof value === "string" ? value.trim() : "";
5
- return /^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$/.test(safe) && !safe.includes("..");
6
- }
7
-
8
- export function requireValidBucketId(value: unknown): string {
9
- if (!isValidBucketId(value)) throw new Error("invalid bucketId");
10
- return value;
11
- }
12
-
13
- export function isValidInstanceId(value: unknown): value is string {
14
- return typeof value === "string" && /^inst_[a-f0-9]{32}$/.test(value);
15
- }
16
-
17
- export function isValidMfid(value: unknown): value is string {
18
- return typeof value === "string" && /^[a-f0-9]{32}$/.test(value);
19
- }
20
-
21
- export function isPublicP256EcJwk(value: unknown): value is JsonWebKey {
22
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
23
- const jwk = value as JsonWebKey;
24
- return jwk.kty === "EC" && jwk.crv === "P-256" && typeof jwk.x === "string" && jwk.x.length > 0 && typeof jwk.y === "string" && jwk.y.length > 0;
25
- }
26
-
27
- export function bucketResourceId(bucketId: string): string {
28
- return `urn:myfield:bucket:${bucketId}`;
29
- }
30
-
31
- export function parseBucketResourceId(resourceId: unknown): { resourceId: string; bucketId: string } | null {
32
- const safe = typeof resourceId === "string" ? resourceId.trim() : "";
33
- const prefix = "urn:myfield:bucket:";
34
- if (!safe.startsWith(prefix)) return null;
35
- const bucketId = safe.slice(prefix.length);
36
- return isValidBucketId(bucketId) ? { resourceId: safe, bucketId } : null;
37
- }
38
-
39
- export function resolveAppId(value?: string): string {
40
- const appId = value === undefined ? (typeof window === "undefined" ? "" : window.location.hostname) : value;
41
- if (typeof appId !== "string" || appId !== appId.trim() || !isValidBucketId(appId)
42
- || !appId.split(".").every(label => /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label))) {
43
- throw new ClientError("INVALID_INPUT", "appId must be a lowercase domain-form identifier of 1–63 characters");
44
- }
45
- return appId;
46
- }
package/src/auth/index.ts DELETED
@@ -1,17 +0,0 @@
1
- export {
2
- createInstanceAuthClient,
3
- signInstanceChallenge,
4
- decryptEncryptedAuthAuthorizationResult,
5
- normalizeBucketAccessGrant,
6
- bucketResourceId,
7
- isValidBucketId,
8
- type AuthCapability,
9
- type AuthInstance,
10
- type AuthCallbackResult,
11
- type BucketAccess,
12
- type BucketAccessGrant,
13
- type CloudSessionCredential,
14
- type InstanceAuthClient,
15
- type InstanceAuthClientOptions,
16
- type InstanceAuthContext,
17
- } from "./instance.ts";