@myfield/sdk 0.9.1 → 0.9.2
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.
- package/CHANGELOG.md +20 -0
- package/README.md +34 -54
- package/dist/index.js +1768 -648
- package/docs/API.md +143 -56
- package/docs/BUCKET-SPEC.md +5 -0
- package/package.json +4 -2
- package/src/auth/authorization.ts +254 -0
- package/src/auth/flow.ts +93 -0
- package/src/auth/identifiers.ts +46 -0
- package/src/auth/instance.ts +33 -514
- package/src/auth/keys.ts +73 -0
- package/src/auth/proof.ts +26 -0
- package/src/auth/session.ts +16 -0
- package/src/auth/store.ts +90 -0
- package/src/auth/types.ts +47 -0
- package/src/bucket/client.ts +6 -1
- package/src/bucket/store.ts +31 -0
- package/src/bucket/transport.ts +28 -6
- package/src/errors.ts +31 -0
- package/src/facade.ts +248 -323
- package/src/index.ts +6 -0
- package/src/remote/bucket.ts +180 -0
- package/src/remote/client.ts +38 -0
- package/src/remote/connection.ts +529 -0
- package/src/remote/feed.ts +80 -0
- package/src/remote/http.ts +78 -0
- package/src/remote/session.ts +31 -0
- package/types/index.d.ts +85 -1
|
@@ -0,0 +1,46 @@
|
|
|
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/instance.ts
CHANGED
|
@@ -9,57 +9,25 @@
|
|
|
9
9
|
// The /auth fragment wire format is frozen as-is, including its vestigial
|
|
10
10
|
// OAuth-shaped fields; this module hides it from apps entirely.
|
|
11
11
|
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
bytesToB64url,
|
|
15
|
-
bytesToHex,
|
|
16
|
-
normalizeIsoDateTime,
|
|
17
|
-
randomId,
|
|
18
|
-
sha256Hex,
|
|
19
|
-
stableStringify,
|
|
20
|
-
utf8Encode,
|
|
21
|
-
} from "../internal/encoding.ts";
|
|
22
|
-
import { unwrapBucketKeys, type BucketKeyGrantEnvelope, type BucketKeys } from "../bucket/keys.ts";
|
|
12
|
+
import { bytesToHex, randomId } from "../internal/encoding.ts";
|
|
13
|
+
import { unwrapBucketKeys } from "../bucket/keys.ts";
|
|
23
14
|
import { createIndexedDbStorageAdapter, type StorageAdapter } from "../bucket/store.ts";
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
export type
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
resourceId: string;
|
|
41
|
-
remoteResourceId?: string;
|
|
42
|
-
resourceApiUrl?: string;
|
|
43
|
-
instanceId: string;
|
|
44
|
-
requestId: string;
|
|
45
|
-
authorizedAt: string;
|
|
46
|
-
bucketAccessGrant?: BucketAccessGrant;
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
export type CloudSessionCredential =
|
|
50
|
-
| { carrier: "bearer"; token: string; expiresAt: string }
|
|
51
|
-
| { carrier: "cookie"; expiresAt: string };
|
|
52
|
-
|
|
53
|
-
export type BucketAccess = {
|
|
54
|
-
mfid: string;
|
|
55
|
-
instanceId: string;
|
|
56
|
-
bucketId: string;
|
|
57
|
-
resourceId: string;
|
|
58
|
-
resourceApiUrl?: string;
|
|
59
|
-
capabilities: AuthCapability[];
|
|
60
|
-
grantRecordId: string;
|
|
61
|
-
keys: BucketKeys;
|
|
62
|
-
};
|
|
15
|
+
import type { AuthInstance } from "./keys.ts";
|
|
16
|
+
import { createInstanceKeyStore } from "./store.ts";
|
|
17
|
+
import { ClientError } from "../errors.ts";
|
|
18
|
+
import type { AuthCapability, InstanceAuthContext, BucketAccess, AuthCallbackResult, BucketAccessGrant } from "./types.ts";
|
|
19
|
+
import { buildAuthRequestFragment, parseEncryptedAuthAuthorizationResultFragment, decryptEncryptedAuthAuthorizationResult,
|
|
20
|
+
normalizeBucketAccessGrant, type StoredAuthAuthorizationResult, type EncryptedAuthAuthorizationResultEnvelope } from "./authorization.ts";
|
|
21
|
+
import { bucketResourceId, parseBucketResourceId, requireValidBucketId, isValidMfid, resolveAppId } from "./identifiers.ts";
|
|
22
|
+
import { createSessionClient } from "../remote/session.ts";
|
|
23
|
+
import { createSession, type CloudSessionCredential } from "./session.ts";
|
|
24
|
+
|
|
25
|
+
export type { AuthCapability, InstanceAuthContext, BucketAccess, AuthCallbackResult, BucketAccessGrant } from "./types.ts";
|
|
26
|
+
export { decryptEncryptedAuthAuthorizationResult, normalizeBucketAccessGrant } from "./authorization.ts";
|
|
27
|
+
export { bucketResourceId, isValidBucketId } from "./identifiers.ts";
|
|
28
|
+
export type { AuthInstance } from "./keys.ts";
|
|
29
|
+
export type { CloudSessionCredential } from "./session.ts";
|
|
30
|
+
export { signInstanceChallenge } from "./proof.ts";
|
|
63
31
|
|
|
64
32
|
export type InstanceAuthClientOptions = {
|
|
65
33
|
appId?: string;
|
|
@@ -72,15 +40,6 @@ export type InstanceAuthClientOptions = {
|
|
|
72
40
|
fetchImpl?: typeof fetch;
|
|
73
41
|
};
|
|
74
42
|
|
|
75
|
-
export type AuthCallbackResult = {
|
|
76
|
-
requestId: string;
|
|
77
|
-
state: string;
|
|
78
|
-
result: "approved" | "denied" | "error";
|
|
79
|
-
resourceId?: string;
|
|
80
|
-
error?: string;
|
|
81
|
-
errorDescription?: string;
|
|
82
|
-
};
|
|
83
|
-
|
|
84
43
|
export type InstanceAuthClient = {
|
|
85
44
|
ensureInstance(): Promise<AuthInstance>;
|
|
86
45
|
authorize(request: { bucketId: string }): Promise<void>;
|
|
@@ -91,47 +50,6 @@ export type InstanceAuthClient = {
|
|
|
91
50
|
clearContext(bucketId: string): Promise<void>;
|
|
92
51
|
};
|
|
93
52
|
|
|
94
|
-
export type BucketAccessGrant = {
|
|
95
|
-
v: 1;
|
|
96
|
-
grantRecordId: string;
|
|
97
|
-
mfid: string;
|
|
98
|
-
resourceId: string;
|
|
99
|
-
instanceId: string;
|
|
100
|
-
issuedAt: string;
|
|
101
|
-
keyId: string;
|
|
102
|
-
capabilities: AuthCapability[];
|
|
103
|
-
envelope: BucketKeyGrantEnvelope;
|
|
104
|
-
};
|
|
105
|
-
|
|
106
|
-
type StoredAuthAuthorizationResult = {
|
|
107
|
-
v: 1;
|
|
108
|
-
requestId: string;
|
|
109
|
-
state: string;
|
|
110
|
-
result: "approved";
|
|
111
|
-
mfid: string;
|
|
112
|
-
resourceId: string;
|
|
113
|
-
instanceId: string;
|
|
114
|
-
createdAt: string;
|
|
115
|
-
resourceApiUrl?: string;
|
|
116
|
-
bucketAccessGrant?: BucketAccessGrant;
|
|
117
|
-
expiresAt?: string;
|
|
118
|
-
};
|
|
119
|
-
|
|
120
|
-
type EncryptedAuthAuthorizationResultEnvelope = {
|
|
121
|
-
v: 1;
|
|
122
|
-
typ: "auth.authorization-result.envelope.v1";
|
|
123
|
-
alg: "ECDH-HKDF-SHA-256/AES-GCM-256";
|
|
124
|
-
requestId: string;
|
|
125
|
-
state: string;
|
|
126
|
-
resourceId: string;
|
|
127
|
-
instanceId: string;
|
|
128
|
-
ephemeralPublicJwk: JsonWebKey;
|
|
129
|
-
salt: string;
|
|
130
|
-
iv: string;
|
|
131
|
-
aad: string;
|
|
132
|
-
ciphertext: string;
|
|
133
|
-
};
|
|
134
|
-
|
|
135
53
|
type PendingInstanceAuthRequest = {
|
|
136
54
|
v: 1;
|
|
137
55
|
requestId: string;
|
|
@@ -150,9 +68,6 @@ type InstanceAuthCallbackPointer = {
|
|
|
150
68
|
createdAt: string;
|
|
151
69
|
};
|
|
152
70
|
|
|
153
|
-
type StoredAuthInstance = AuthInstance & { updatedAt: string };
|
|
154
|
-
type ActiveInstancePointer = { v: 1; instanceId: string; updatedAt: string };
|
|
155
|
-
|
|
156
71
|
type StoredCloudSessionCredential = {
|
|
157
72
|
v: 1;
|
|
158
73
|
mfid: string;
|
|
@@ -162,16 +77,7 @@ type StoredCloudSessionCredential = {
|
|
|
162
77
|
storedAt?: string;
|
|
163
78
|
};
|
|
164
79
|
|
|
165
|
-
type InstanceProof = {
|
|
166
|
-
type: "instance.es256";
|
|
167
|
-
instanceId: string;
|
|
168
|
-
alg: "ES256";
|
|
169
|
-
signedAt: string;
|
|
170
|
-
signature: string;
|
|
171
|
-
};
|
|
172
|
-
|
|
173
80
|
const AUTH_REQUEST_TTL_MS = 10 * 60 * 1000;
|
|
174
|
-
const AUTH_CALLBACK_FRAGMENT_PARAM = "mf_auth_result";
|
|
175
81
|
const DEFAULT_AUTH_IDB_NAME = "mf-sdk-auth-v1";
|
|
176
82
|
const BUCKET_ACCESS_CACHE_TTL_MS = 60_000;
|
|
177
83
|
const INSTANCE_SESSION_USABLE_WINDOW_MS = 2 * 60 * 1000;
|
|
@@ -179,73 +85,21 @@ const INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS = 60 * 60 * 1000;
|
|
|
179
85
|
const FIXED_CAPABILITIES: AuthCapability[] = ["read", "write"];
|
|
180
86
|
|
|
181
87
|
export function createInstanceAuthClient(options: InstanceAuthClientOptions = {}): InstanceAuthClient {
|
|
182
|
-
|
|
183
|
-
const appId = normalizeInstanceAppId(options.appId);
|
|
88
|
+
const appId = resolveAppId(options.appId);
|
|
184
89
|
let mfid = "";
|
|
185
90
|
let currentResourceId = "";
|
|
186
91
|
let currentSession: { resourceId: string; credential: CloudSessionCredential } | null = null;
|
|
187
92
|
const inFlightSessionRefreshes = new Map<string, Promise<CloudSessionCredential>>();
|
|
188
93
|
const storage = options.storage || createIndexedDbStorageAdapter({ dbName: DEFAULT_AUTH_IDB_NAME, storeName: "instance" });
|
|
189
94
|
const fetchImpl = options.fetchImpl || fetch;
|
|
95
|
+
const sessions = createSessionClient((path, body) => postJson(fetchImpl, options.apiBase, path, body));
|
|
190
96
|
const bucketAccessCache = new Map<string, { access: BucketAccess; expiresAt: number }>();
|
|
191
97
|
|
|
192
|
-
const
|
|
193
|
-
const
|
|
194
|
-
const
|
|
195
|
-
const
|
|
196
|
-
const
|
|
197
|
-
const sessionKey = (resourceId: string, instanceId: string) => `instance:${seg(appId)}:session:${seg(resourceId)}:${seg(instanceId)}`;
|
|
198
|
-
|
|
199
|
-
function isStoredAuthInstance(value: StoredAuthInstance | null, instanceId?: string): value is StoredAuthInstance {
|
|
200
|
-
return (
|
|
201
|
-
!!value &&
|
|
202
|
-
value.v === 1 &&
|
|
203
|
-
isValidInstanceId(value.instanceId) &&
|
|
204
|
-
(!instanceId || value.instanceId === instanceId) &&
|
|
205
|
-
value.signingPrivateKey instanceof CryptoKey &&
|
|
206
|
-
value.wrappingPrivateKey instanceof CryptoKey
|
|
207
|
-
);
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
async function readStoredInstance(instanceId: string): Promise<StoredAuthInstance | null> {
|
|
211
|
-
const stored = await storage.get<StoredAuthInstance>(instanceKey(instanceId));
|
|
212
|
-
return isStoredAuthInstance(stored, instanceId) ? stored : null;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
async function writeStoredInstance(authInstance: AuthInstance): Promise<StoredAuthInstance> {
|
|
216
|
-
const existing = await readStoredInstance(authInstance.instanceId);
|
|
217
|
-
const stored: StoredAuthInstance = {
|
|
218
|
-
...authInstance,
|
|
219
|
-
updatedAt: new Date().toISOString(),
|
|
220
|
-
createdAt: authInstance.createdAt || existing?.createdAt || new Date().toISOString(),
|
|
221
|
-
};
|
|
222
|
-
await storage.set(instanceKey(authInstance.instanceId), stored);
|
|
223
|
-
const verified = await readStoredInstance(authInstance.instanceId);
|
|
224
|
-
if (!verified) throw new Error("auth instance write did not persist keys");
|
|
225
|
-
await storage.set(activeInstanceKey(), { v: 1, instanceId: authInstance.instanceId, updatedAt: new Date().toISOString() } satisfies ActiveInstancePointer);
|
|
226
|
-
instance = verified;
|
|
227
|
-
return verified;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
async function readActiveStoredInstance(): Promise<StoredAuthInstance | null> {
|
|
231
|
-
const active = await storage.get<ActiveInstancePointer>(activeInstanceKey());
|
|
232
|
-
if (!active || active.v !== 1 || !isValidInstanceId(active.instanceId)) return null;
|
|
233
|
-
return readStoredInstance(active.instanceId);
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
async function ensureStoredInstance(): Promise<StoredAuthInstance> {
|
|
237
|
-
if (instance) {
|
|
238
|
-
const stored = await readStoredInstance(instance.instanceId);
|
|
239
|
-
if (stored) return stored;
|
|
240
|
-
return writeStoredInstance(instance);
|
|
241
|
-
}
|
|
242
|
-
const active = await readActiveStoredInstance();
|
|
243
|
-
if (active) {
|
|
244
|
-
instance = active;
|
|
245
|
-
return active;
|
|
246
|
-
}
|
|
247
|
-
return writeStoredInstance(await generateAuthInstance());
|
|
248
|
-
}
|
|
98
|
+
const keyStore = createInstanceKeyStore(storage, appId);
|
|
99
|
+
const { pending: pendingAuthKey, callback: callbackPointerKey, context: contextKey, session: sessionKey } = keyStore.keys;
|
|
100
|
+
const readStoredInstance = keyStore.read;
|
|
101
|
+
const readActiveStoredInstance = keyStore.active;
|
|
102
|
+
const ensureStoredInstance = keyStore.ensure;
|
|
249
103
|
|
|
250
104
|
async function readContext(resourceId: string): Promise<InstanceAuthContext | null> {
|
|
251
105
|
if (!parseBucketResourceId(resourceId)) return null;
|
|
@@ -264,7 +118,6 @@ export function createInstanceAuthClient(options: InstanceAuthClientOptions = {}
|
|
|
264
118
|
}
|
|
265
119
|
mfid = context.mfid;
|
|
266
120
|
currentResourceId = context.resourceId;
|
|
267
|
-
instance = authInstance;
|
|
268
121
|
return context;
|
|
269
122
|
}
|
|
270
123
|
|
|
@@ -278,38 +131,19 @@ export function createInstanceAuthClient(options: InstanceAuthClientOptions = {}
|
|
|
278
131
|
const refreshSessionKey = `${sessionResourceId}:${authInstance.instanceId}`;
|
|
279
132
|
|
|
280
133
|
const performRefreshSession = async (): Promise<CloudSessionCredential> => {
|
|
281
|
-
const
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
instanceId: authInstance.instanceId,
|
|
285
|
-
});
|
|
286
|
-
const proof = await signInstanceChallenge({
|
|
287
|
-
instance: authInstance,
|
|
288
|
-
challengeId: challenge.challengeId,
|
|
289
|
-
challenge: challenge.challenge,
|
|
290
|
-
mfid,
|
|
291
|
-
resourceId: sessionResourceId,
|
|
292
|
-
});
|
|
293
|
-
const session = await postJson<{ credential: CloudSessionCredential }>(fetchImpl, options.apiBase, "/v1/api/auth/instance-session", {
|
|
294
|
-
mfid,
|
|
295
|
-
resourceId: sessionResourceId,
|
|
296
|
-
instanceId: authInstance.instanceId,
|
|
297
|
-
challengeId: challenge.challengeId,
|
|
298
|
-
proof,
|
|
299
|
-
credentialCarrier: "bearer",
|
|
300
|
-
});
|
|
301
|
-
currentSession = { resourceId: sessionResourceId, credential: session.credential };
|
|
302
|
-
if (session.credential.carrier === "bearer") {
|
|
134
|
+
const credential = await createSession({ instance: authInstance, mfid, resourceId: sessionResourceId }, sessions);
|
|
135
|
+
currentSession = { resourceId: sessionResourceId, credential };
|
|
136
|
+
if (credential.carrier === "bearer") {
|
|
303
137
|
await storage.set(sessionKey(sessionResourceId, context.instanceId), {
|
|
304
138
|
v: 1,
|
|
305
139
|
mfid,
|
|
306
140
|
resourceId: sessionResourceId,
|
|
307
141
|
instanceId: authInstance.instanceId,
|
|
308
|
-
credential
|
|
142
|
+
credential,
|
|
309
143
|
storedAt: new Date().toISOString(),
|
|
310
144
|
} satisfies StoredCloudSessionCredential);
|
|
311
145
|
}
|
|
312
|
-
return
|
|
146
|
+
return credential;
|
|
313
147
|
};
|
|
314
148
|
|
|
315
149
|
const refreshSession = (): Promise<CloudSessionCredential> => {
|
|
@@ -446,6 +280,9 @@ export function createInstanceAuthClient(options: InstanceAuthClientOptions = {}
|
|
|
446
280
|
const remoteResourceId = stored.bucketAccessGrant?.resourceId || stored.resourceId;
|
|
447
281
|
mfid = stored.mfid;
|
|
448
282
|
currentResourceId = stored.resourceId;
|
|
283
|
+
if ((await readActiveStoredInstance())?.instanceId !== authInstance.instanceId) {
|
|
284
|
+
throw new ClientError("IDENTITY_MISMATCH", "Active instance changed during authorization");
|
|
285
|
+
}
|
|
449
286
|
await storage.set(contextKey(stored.resourceId, stored.instanceId), {
|
|
450
287
|
v: 1,
|
|
451
288
|
mfid: stored.mfid,
|
|
@@ -457,7 +294,6 @@ export function createInstanceAuthClient(options: InstanceAuthClientOptions = {}
|
|
|
457
294
|
authorizedAt: new Date().toISOString(),
|
|
458
295
|
...(stored.bucketAccessGrant ? { bucketAccessGrant: stored.bucketAccessGrant } : {}),
|
|
459
296
|
} satisfies InstanceAuthContext);
|
|
460
|
-
await writeStoredInstance(authInstance);
|
|
461
297
|
if (currentSession?.resourceId === remoteResourceId) currentSession = null;
|
|
462
298
|
await storage.remove(sessionKey(remoteResourceId, stored.instanceId));
|
|
463
299
|
bucketAccessCache.clear();
|
|
@@ -514,281 +350,6 @@ export function createInstanceAuthClient(options: InstanceAuthClientOptions = {}
|
|
|
514
350
|
};
|
|
515
351
|
}
|
|
516
352
|
|
|
517
|
-
async function generateAuthInstance(): Promise<AuthInstance> {
|
|
518
|
-
const signing = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
|
|
519
|
-
const wrapping = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
|
|
520
|
-
const signingPublicJwk = (await crypto.subtle.exportKey("jwk", signing.publicKey)) as JsonWebKey;
|
|
521
|
-
const wrappingPublicJwk = (await crypto.subtle.exportKey("jwk", wrapping.publicKey)) as JsonWebKey;
|
|
522
|
-
return {
|
|
523
|
-
v: 1,
|
|
524
|
-
instanceId: await deriveInstanceId(signingPublicJwk),
|
|
525
|
-
signingPublicJwk,
|
|
526
|
-
signingPrivateKey: signing.privateKey,
|
|
527
|
-
wrappingPublicJwk,
|
|
528
|
-
wrappingPrivateKey: wrapping.privateKey,
|
|
529
|
-
createdAt: new Date().toISOString(),
|
|
530
|
-
};
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
async function deriveInstanceId(signingPublicJwk: JsonWebKey): Promise<string> {
|
|
534
|
-
const digest = await sha256Hex(stableStringify(jwkCore(signingPublicJwk)));
|
|
535
|
-
return `inst_${digest.slice(0, 32)}`;
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
export async function signInstanceChallenge(input: {
|
|
539
|
-
instance: Pick<AuthInstance, "instanceId" | "signingPrivateKey">;
|
|
540
|
-
challenge: string;
|
|
541
|
-
mfid: string;
|
|
542
|
-
resourceId: string;
|
|
543
|
-
challengeId?: string;
|
|
544
|
-
signedAt?: string;
|
|
545
|
-
}): Promise<InstanceProof> {
|
|
546
|
-
const signedAt = normalizeIsoDateTime(input.signedAt) || new Date().toISOString();
|
|
547
|
-
const payload = stableStringify({
|
|
548
|
-
v: 1,
|
|
549
|
-
type: "instance-proof",
|
|
550
|
-
instanceId: input.instance.instanceId,
|
|
551
|
-
challenge: input.challenge,
|
|
552
|
-
challengeId: input.challengeId || "",
|
|
553
|
-
mfid: input.mfid,
|
|
554
|
-
resourceId: input.resourceId,
|
|
555
|
-
signedAt,
|
|
556
|
-
});
|
|
557
|
-
const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, input.instance.signingPrivateKey, utf8Encode(payload));
|
|
558
|
-
return { type: "instance.es256", instanceId: input.instance.instanceId, alg: "ES256", signedAt, signature: bytesToB64url(new Uint8Array(signature)) };
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
type AuthRequestFields = {
|
|
562
|
-
clientId: string;
|
|
563
|
-
requestId: string;
|
|
564
|
-
state: string;
|
|
565
|
-
redirectUri: string;
|
|
566
|
-
origin: string;
|
|
567
|
-
resourceId: string;
|
|
568
|
-
capabilities: AuthCapability[];
|
|
569
|
-
instanceId: string;
|
|
570
|
-
instanceSigningPublicJwk: JsonWebKey;
|
|
571
|
-
instanceWrappingPublicJwk: JsonWebKey;
|
|
572
|
-
createdAt: string;
|
|
573
|
-
};
|
|
574
|
-
|
|
575
|
-
function buildAuthRequestFragment(request: AuthRequestFields): string {
|
|
576
|
-
if (!request.requestId || !request.state) throw new Error("auth request state required");
|
|
577
|
-
if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
|
|
578
|
-
if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
|
|
579
|
-
if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
|
|
580
|
-
const redirect = new URL(request.redirectUri);
|
|
581
|
-
const origin = new URL(request.origin);
|
|
582
|
-
if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
|
|
583
|
-
const wire = {
|
|
584
|
-
response_type: "code",
|
|
585
|
-
client_id: request.clientId,
|
|
586
|
-
redirect_uri: request.redirectUri,
|
|
587
|
-
state: request.state,
|
|
588
|
-
scope: request.capabilities.join(" "),
|
|
589
|
-
resource_id: request.resourceId,
|
|
590
|
-
mf_v: 1,
|
|
591
|
-
mf_auth_mode: "v1",
|
|
592
|
-
mf_request_id: request.requestId,
|
|
593
|
-
mf_instance_id: request.instanceId,
|
|
594
|
-
mf_instance_signing_jwk: request.instanceSigningPublicJwk,
|
|
595
|
-
mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
|
|
596
|
-
mf_issued_at: request.createdAt,
|
|
597
|
-
};
|
|
598
|
-
return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl: string): EncryptedAuthAuthorizationResultEnvelope | null {
|
|
602
|
-
const input = String(fragmentOrUrl || "");
|
|
603
|
-
const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
|
|
604
|
-
if (!rawFragment) return null;
|
|
605
|
-
const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
|
|
606
|
-
if (!encoded) return null;
|
|
607
|
-
const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded))) as Partial<EncryptedAuthAuthorizationResultEnvelope> | null;
|
|
608
|
-
if (
|
|
609
|
-
!envelope ||
|
|
610
|
-
envelope.v !== 1 ||
|
|
611
|
-
envelope.typ !== "auth.authorization-result.envelope.v1" ||
|
|
612
|
-
envelope.alg !== "ECDH-HKDF-SHA-256/AES-GCM-256" ||
|
|
613
|
-
typeof envelope.requestId !== "string" ||
|
|
614
|
-
typeof envelope.state !== "string" ||
|
|
615
|
-
!parseBucketResourceId(envelope.resourceId) ||
|
|
616
|
-
!isValidInstanceId(envelope.instanceId || "") ||
|
|
617
|
-
!isPublicP256EcJwk(envelope.ephemeralPublicJwk) ||
|
|
618
|
-
typeof envelope.salt !== "string" ||
|
|
619
|
-
typeof envelope.iv !== "string" ||
|
|
620
|
-
typeof envelope.aad !== "string" ||
|
|
621
|
-
typeof envelope.ciphertext !== "string"
|
|
622
|
-
) {
|
|
623
|
-
throw new Error("auth callback result fragment invalid");
|
|
624
|
-
}
|
|
625
|
-
return envelope as EncryptedAuthAuthorizationResultEnvelope;
|
|
626
|
-
}
|
|
627
|
-
|
|
628
|
-
export async function decryptEncryptedAuthAuthorizationResult(input: {
|
|
629
|
-
envelope: EncryptedAuthAuthorizationResultEnvelope;
|
|
630
|
-
instanceWrappingPrivateKey: CryptoKey;
|
|
631
|
-
expectedRequestId?: string;
|
|
632
|
-
expectedState?: string;
|
|
633
|
-
expectedResourceId?: string;
|
|
634
|
-
expectedInstanceId?: string;
|
|
635
|
-
}): Promise<StoredAuthAuthorizationResult> {
|
|
636
|
-
const { envelope } = input;
|
|
637
|
-
if (
|
|
638
|
-
(input.expectedRequestId && envelope.requestId !== input.expectedRequestId) ||
|
|
639
|
-
(input.expectedState && envelope.state !== input.expectedState) ||
|
|
640
|
-
(input.expectedResourceId && envelope.resourceId !== input.expectedResourceId) ||
|
|
641
|
-
(input.expectedInstanceId && envelope.instanceId !== input.expectedInstanceId)
|
|
642
|
-
) {
|
|
643
|
-
throw new Error("auth callback result mismatch");
|
|
644
|
-
}
|
|
645
|
-
const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
646
|
-
const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, input.instanceWrappingPrivateKey, 256);
|
|
647
|
-
const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
|
|
648
|
-
const wrappingKey = await crypto.subtle.deriveKey(
|
|
649
|
-
{ name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt) as BufferSource, info: utf8Encode(envelope.aad) },
|
|
650
|
-
material,
|
|
651
|
-
{ name: "AES-GCM", length: 256 },
|
|
652
|
-
false,
|
|
653
|
-
["decrypt"]
|
|
654
|
-
);
|
|
655
|
-
const plaintext = await crypto.subtle.decrypt(
|
|
656
|
-
{ name: "AES-GCM", iv: b64urlToBytes(envelope.iv) as BufferSource, additionalData: utf8Encode(envelope.aad) },
|
|
657
|
-
wrappingKey,
|
|
658
|
-
b64urlToBytes(envelope.ciphertext) as BufferSource
|
|
659
|
-
);
|
|
660
|
-
const result = normalizeAuthAuthorizationResult(JSON.parse(new TextDecoder().decode(plaintext)), envelope.requestId);
|
|
661
|
-
if (
|
|
662
|
-
!result ||
|
|
663
|
-
result.state !== envelope.state ||
|
|
664
|
-
result.resourceId !== envelope.resourceId ||
|
|
665
|
-
result.instanceId !== envelope.instanceId ||
|
|
666
|
-
(input.expectedState && result.state !== input.expectedState) ||
|
|
667
|
-
(input.expectedResourceId && result.resourceId !== input.expectedResourceId) ||
|
|
668
|
-
(input.expectedInstanceId && result.instanceId !== input.expectedInstanceId)
|
|
669
|
-
) {
|
|
670
|
-
throw new Error("auth callback result mismatch");
|
|
671
|
-
}
|
|
672
|
-
return result;
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
function normalizeAuthAuthorizationResult(value: unknown, expectedRequestId?: string): StoredAuthAuthorizationResult | null {
|
|
676
|
-
const row = value as Partial<StoredAuthAuthorizationResult> | null;
|
|
677
|
-
if (
|
|
678
|
-
!row ||
|
|
679
|
-
row.v !== 1 ||
|
|
680
|
-
row.result !== "approved" ||
|
|
681
|
-
typeof row.requestId !== "string" ||
|
|
682
|
-
(expectedRequestId && row.requestId !== expectedRequestId) ||
|
|
683
|
-
typeof row.state !== "string" ||
|
|
684
|
-
!isValidMfid(row.mfid || "") ||
|
|
685
|
-
!parseBucketResourceId(row.resourceId) ||
|
|
686
|
-
!isValidInstanceId(row.instanceId || "") ||
|
|
687
|
-
typeof row.createdAt !== "string"
|
|
688
|
-
) {
|
|
689
|
-
return null;
|
|
690
|
-
}
|
|
691
|
-
if (row.expiresAt !== undefined) {
|
|
692
|
-
const expiresAt = Date.parse(String(row.expiresAt));
|
|
693
|
-
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
|
|
694
|
-
}
|
|
695
|
-
const resource = parseBucketResourceId(row.resourceId);
|
|
696
|
-
if (!resource) return null;
|
|
697
|
-
const bucketAccessGrant = normalizeBucketAccessGrant(row.bucketAccessGrant);
|
|
698
|
-
if (!bucketAccessGrant) return null;
|
|
699
|
-
if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
|
|
700
|
-
return null;
|
|
701
|
-
}
|
|
702
|
-
return {
|
|
703
|
-
v: 1,
|
|
704
|
-
requestId: row.requestId,
|
|
705
|
-
state: row.state,
|
|
706
|
-
result: "approved",
|
|
707
|
-
mfid: row.mfid!,
|
|
708
|
-
resourceId: resource.resourceId,
|
|
709
|
-
instanceId: row.instanceId!,
|
|
710
|
-
createdAt: row.createdAt,
|
|
711
|
-
...(typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {}),
|
|
712
|
-
bucketAccessGrant,
|
|
713
|
-
...(row.expiresAt ? { expiresAt: row.expiresAt } : {}),
|
|
714
|
-
};
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
export function normalizeBucketAccessGrant(value: unknown): BucketAccessGrant | null {
|
|
718
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
719
|
-
const row = value as Partial<BucketAccessGrant>;
|
|
720
|
-
const resource = parseBucketResourceId(row.resourceId);
|
|
721
|
-
const capabilities = normalizeCapabilities(row.capabilities);
|
|
722
|
-
if (
|
|
723
|
-
row.v !== 1 ||
|
|
724
|
-
!/^ar_[a-f0-9]{32}$/.test(String(row.grantRecordId || "")) ||
|
|
725
|
-
!isValidMfid(row.mfid) ||
|
|
726
|
-
!resource ||
|
|
727
|
-
!isValidInstanceId(row.instanceId) ||
|
|
728
|
-
!/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) ||
|
|
729
|
-
capabilities.length < 1 ||
|
|
730
|
-
!isValidBucketKeyGrantEnvelope(row.envelope, row.instanceId, row.keyId)
|
|
731
|
-
) {
|
|
732
|
-
return null;
|
|
733
|
-
}
|
|
734
|
-
return {
|
|
735
|
-
v: 1,
|
|
736
|
-
grantRecordId: row.grantRecordId!,
|
|
737
|
-
mfid: row.mfid!,
|
|
738
|
-
resourceId: resource.resourceId,
|
|
739
|
-
instanceId: row.instanceId!,
|
|
740
|
-
issuedAt: String(row.issuedAt || ""),
|
|
741
|
-
keyId: row.keyId!,
|
|
742
|
-
capabilities,
|
|
743
|
-
envelope: row.envelope as BucketKeyGrantEnvelope,
|
|
744
|
-
};
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
function isValidBucketKeyGrantEnvelope(value: unknown, instanceId?: string, keyId?: string): value is BucketKeyGrantEnvelope {
|
|
748
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
749
|
-
const row = value as Partial<BucketKeyGrantEnvelope>;
|
|
750
|
-
if (
|
|
751
|
-
row.kind !== "bucket-key" ||
|
|
752
|
-
!isValidBucketId(row.bucketId) ||
|
|
753
|
-
!/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) ||
|
|
754
|
-
!isValidInstanceId(row.targetInstanceId) ||
|
|
755
|
-
row.wrapAlg !== "ECDH-HKDF-SHA-256/AES-GCM-256" ||
|
|
756
|
-
!isPublicP256EcJwk(row.targetWrappingPublicJwk) ||
|
|
757
|
-
!isPublicP256EcJwk(row.ephemeralPublicJwk) ||
|
|
758
|
-
typeof row.salt !== "string" ||
|
|
759
|
-
typeof row.iv !== "string" ||
|
|
760
|
-
typeof row.aad !== "string" ||
|
|
761
|
-
typeof row.ciphertext !== "string"
|
|
762
|
-
) {
|
|
763
|
-
return false;
|
|
764
|
-
}
|
|
765
|
-
if (instanceId && row.targetInstanceId !== instanceId) return false;
|
|
766
|
-
if (keyId && row.keyId !== keyId) return false;
|
|
767
|
-
return true;
|
|
768
|
-
}
|
|
769
|
-
|
|
770
|
-
export function bucketResourceId(bucketId: string): string {
|
|
771
|
-
return `urn:myfield:bucket:${bucketId}`;
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
function parseBucketResourceId(resourceId: unknown): { resourceId: string; bucketId: string } | null {
|
|
775
|
-
const safe = typeof resourceId === "string" ? resourceId.trim() : "";
|
|
776
|
-
const prefix = "urn:myfield:bucket:";
|
|
777
|
-
if (!safe.startsWith(prefix)) return null;
|
|
778
|
-
const bucketId = safe.slice(prefix.length);
|
|
779
|
-
return isValidBucketId(bucketId) ? { resourceId: safe, bucketId } : null;
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
function normalizeCapabilities(input: unknown): AuthCapability[] {
|
|
783
|
-
if (!Array.isArray(input)) return [];
|
|
784
|
-
const allowed = new Set<AuthCapability>(["read", "write"]);
|
|
785
|
-
const result: AuthCapability[] = [];
|
|
786
|
-
for (const item of input) {
|
|
787
|
-
if (allowed.has(item as AuthCapability) && !result.includes(item as AuthCapability)) result.push(item as AuthCapability);
|
|
788
|
-
}
|
|
789
|
-
return result.sort();
|
|
790
|
-
}
|
|
791
|
-
|
|
792
353
|
async function postJson<T>(fetchImpl: typeof fetch, apiBase: string | undefined, path: string, body: unknown): Promise<T> {
|
|
793
354
|
const res = await fetchImpl(`${apiBase || ""}${path}`, {
|
|
794
355
|
method: "POST",
|
|
@@ -823,48 +384,6 @@ function isFresh(createdAt: string): boolean {
|
|
|
823
384
|
return Number.isFinite(created) && Date.now() - created <= AUTH_REQUEST_TTL_MS;
|
|
824
385
|
}
|
|
825
386
|
|
|
826
|
-
export function isValidBucketId(value: unknown): value is string {
|
|
827
|
-
const safe = typeof value === "string" ? value.trim() : "";
|
|
828
|
-
return /^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$/.test(safe) && !safe.includes("..");
|
|
829
|
-
}
|
|
830
|
-
|
|
831
|
-
function requireValidBucketId(value: unknown): string {
|
|
832
|
-
if (!isValidBucketId(value)) throw new Error("invalid bucketId");
|
|
833
|
-
return value;
|
|
834
|
-
}
|
|
835
|
-
|
|
836
|
-
function isValidInstanceId(value: unknown): value is string {
|
|
837
|
-
return typeof value === "string" && /^inst_[a-f0-9]{32}$/.test(value);
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
function isValidMfid(value: unknown): value is string {
|
|
841
|
-
return typeof value === "string" && /^[a-f0-9]{32}$/.test(value);
|
|
842
|
-
}
|
|
843
|
-
|
|
844
|
-
function isPublicP256EcJwk(value: unknown): value is JsonWebKey {
|
|
845
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
846
|
-
const jwk = value as JsonWebKey;
|
|
847
|
-
return jwk.kty === "EC" && jwk.crv === "P-256" && typeof jwk.x === "string" && jwk.x.length > 0 && typeof jwk.y === "string" && jwk.y.length > 0;
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
function normalizeInstanceAppId(value: unknown): string {
|
|
851
|
-
const safe = typeof value === "string" ? value.trim() : "";
|
|
852
|
-
return isValidBucketId(safe) ? safe : "myfield.sdk";
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
function seg(value: string): string {
|
|
856
|
-
return encodeURIComponent(value);
|
|
857
|
-
}
|
|
858
|
-
|
|
859
|
-
function jwkCore(jwk: JsonWebKey): Record<string, string> {
|
|
860
|
-
const out: Record<string, string> = {};
|
|
861
|
-
for (const key of ["kty", "crv", "x", "y", "kid", "alg", "use"] as const) {
|
|
862
|
-
const value = (jwk as Record<string, unknown>)[key];
|
|
863
|
-
if (typeof value === "string") out[key] = value;
|
|
864
|
-
}
|
|
865
|
-
return out;
|
|
866
|
-
}
|
|
867
|
-
|
|
868
387
|
function browserLocationHref(): string {
|
|
869
388
|
if (typeof window === "undefined") throw new Error("browser window required");
|
|
870
389
|
return window.location.href;
|