@kagayoi/hatena-blog-mcp 0.0.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.
@@ -0,0 +1,441 @@
1
+ import { XMLParser } from "fast-xml-parser";
2
+ import { assertValidXmlChars } from "../utils/xml.js";
3
+ import { AtomPubError } from "./errors.js";
4
+ import type {
5
+ CategoryDocument,
6
+ ContentType,
7
+ Entry,
8
+ EntryList,
9
+ EntryWritePayload,
10
+ Page,
11
+ PageList,
12
+ PageWritePayload,
13
+ } from "./types.js";
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Parser
17
+ // ---------------------------------------------------------------------------
18
+
19
+ const ARRAY_TAGS = new Set(["entry", "category", "link"]);
20
+
21
+ const parser = new XMLParser({
22
+ ignoreAttributes: false,
23
+ attributeNamePrefix: "@_",
24
+ parseTagValue: false,
25
+ parseAttributeValue: false,
26
+ trimValues: false,
27
+ processEntities: true,
28
+ htmlEntities: true,
29
+ removeNSPrefix: true,
30
+ textNodeName: "#text",
31
+ isArray: (name) => ARRAY_TAGS.has(name.split(":").at(-1) ?? name),
32
+ });
33
+
34
+ type XmlNode = Record<string, unknown>;
35
+
36
+ function parse(xml: string): XmlNode {
37
+ try {
38
+ return parser.parse(xml) as XmlNode;
39
+ } catch (cause) {
40
+ throw new AtomPubError("Failed to parse AtomPub XML", {
41
+ status: 0,
42
+ code: "parse_error",
43
+ body: xml.slice(0, 500),
44
+ cause,
45
+ });
46
+ }
47
+ }
48
+
49
+ function asObject(value: unknown): XmlNode {
50
+ if (value === null || value === undefined || typeof value !== "object") {
51
+ return {};
52
+ }
53
+ return value as XmlNode;
54
+ }
55
+
56
+ function parseError(message: string): never {
57
+ throw new AtomPubError(message, { status: 0, code: "parse_error" });
58
+ }
59
+
60
+ function requiredObject(node: XmlNode, key: string, label: string): XmlNode {
61
+ const value = node[key];
62
+ if (value === null || value === undefined || typeof value !== "object" || Array.isArray(value)) {
63
+ return parseError(`AtomPub response is missing required ${label}`);
64
+ }
65
+ return value as XmlNode;
66
+ }
67
+
68
+ function requiredText(
69
+ node: XmlNode,
70
+ key: string,
71
+ label: string,
72
+ options: { nonEmpty?: boolean } = {},
73
+ ): string {
74
+ if (!Object.hasOwn(node, key)) return parseError(`AtomPub response is missing required ${label}`);
75
+ const value = asString(node[key]);
76
+ if (value === undefined || (options.nonEmpty === true && value.length === 0)) {
77
+ return parseError(`AtomPub response has invalid required ${label}`);
78
+ }
79
+ return value;
80
+ }
81
+
82
+ function asString(value: unknown): string | undefined {
83
+ // The parser is configured with parseTagValue/parseAttributeValue:false, so
84
+ // every value we see is either a string, a nested object, or undefined.
85
+ if (typeof value === "string") return value;
86
+ if (value !== null && typeof value === "object") {
87
+ const text = (value as XmlNode)["#text"];
88
+ if (typeof text === "string") return text;
89
+ }
90
+ return undefined;
91
+ }
92
+
93
+ function asBool(value: unknown, label: string): boolean {
94
+ if (value === undefined) return false;
95
+ const text = asString(value)?.toLowerCase();
96
+ if (text === "yes") return true;
97
+ if (text === "no") return false;
98
+ return parseError(`AtomPub response has invalid ${label}`);
99
+ }
100
+
101
+ function asArray<T>(value: T | T[] | undefined): T[] {
102
+ if (value === undefined) return [];
103
+ return Array.isArray(value) ? value : [value];
104
+ }
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // Field extraction
108
+ // ---------------------------------------------------------------------------
109
+
110
+ function extractLinks(entry: XmlNode): {
111
+ editUrl: string | undefined;
112
+ publicUrl: string | undefined;
113
+ } {
114
+ const links = asArray(entry.link as XmlNode | XmlNode[] | undefined);
115
+ let editUrl: string | undefined;
116
+ let publicUrl: string | undefined;
117
+ for (const link of links) {
118
+ const rel = link["@_rel"];
119
+ const href = link["@_href"];
120
+ const type = link["@_type"];
121
+ if (typeof href !== "string") continue;
122
+ if (rel === "edit") editUrl = href;
123
+ if (rel === "alternate" && type === "text/html") publicUrl = href;
124
+ }
125
+ return { editUrl, publicUrl };
126
+ }
127
+
128
+ function extractIdFromEditUrl(editUrl: string | undefined): string | undefined {
129
+ if (!editUrl) return undefined;
130
+ const match = /\/atom\/(?:entry|page)\/([^/?#]+)/.exec(editUrl);
131
+ return match?.[1];
132
+ }
133
+
134
+ function extractControl(entry: XmlNode): {
135
+ draft: boolean;
136
+ preview: boolean;
137
+ scheduled: boolean;
138
+ } {
139
+ const control = requiredObject(entry, "control", "app:control");
140
+ requiredText(control, "draft", "app:draft");
141
+ return {
142
+ draft: asBool(control.draft, "app:draft"),
143
+ preview: asBool(control.preview, "app:preview"),
144
+ scheduled: asBool(control.scheduled, "hatenablog:scheduled"),
145
+ };
146
+ }
147
+
148
+ function extractCategories(entry: XmlNode): string[] {
149
+ const cats = asArray(entry.category as XmlNode | XmlNode[] | undefined);
150
+ const terms: string[] = [];
151
+ for (const c of cats) {
152
+ const term = c["@_term"];
153
+ if (typeof term === "string") terms.push(term);
154
+ }
155
+ return terms;
156
+ }
157
+
158
+ function extractContentBody(entry: XmlNode): {
159
+ content: string;
160
+ contentType: ContentType | undefined;
161
+ } {
162
+ const node = entry.content;
163
+ if (typeof node === "string") {
164
+ return { content: node, contentType: undefined };
165
+ }
166
+ const obj = asObject(node);
167
+ const text = asString(obj) ?? "";
168
+ const type = obj["@_type"];
169
+ return {
170
+ content: text,
171
+ contentType: typeof type === "string" ? (type as ContentType) : undefined,
172
+ };
173
+ }
174
+
175
+ function extractFormattedContent(entry: XmlNode): string | undefined {
176
+ const node = entry["formatted-content"];
177
+ if (node === undefined) return undefined;
178
+ if (typeof node === "string") return node;
179
+ return asString(node);
180
+ }
181
+
182
+ function toEntry(entryNode: XmlNode): Entry {
183
+ const { editUrl, publicUrl } = extractLinks(entryNode);
184
+ const id = extractIdFromEditUrl(editUrl);
185
+ if (!id) {
186
+ throw new AtomPubError("Entry is missing edit link — cannot determine id", {
187
+ status: 0,
188
+ code: "parse_error",
189
+ });
190
+ }
191
+ const { content, contentType } = extractContentBody(entryNode);
192
+ const formatted = extractFormattedContent(entryNode);
193
+
194
+ const atomId = requiredText(entryNode, "id", "id", { nonEmpty: true });
195
+ const title = requiredText(entryNode, "title", "title");
196
+ requiredText(entryNode, "content", "content");
197
+ const updated = requiredText(entryNode, "updated", "updated", { nonEmpty: true });
198
+ const control = extractControl(entryNode);
199
+
200
+ const authorName = asString(asObject(entryNode.author).name) ?? "";
201
+ const customUrl = asString(entryNode["custom-url"]);
202
+ const edited = asString(entryNode.edited);
203
+
204
+ return {
205
+ id,
206
+ atomId,
207
+ title,
208
+ authorName,
209
+ content,
210
+ contentType,
211
+ ...(formatted !== undefined ? { formattedContent: formatted } : {}),
212
+ categories: extractCategories(entryNode),
213
+ control,
214
+ updated,
215
+ ...(asString(entryNode.published) !== undefined
216
+ ? { published: asString(entryNode.published) as string }
217
+ : {}),
218
+ ...(edited !== undefined ? { edited } : {}),
219
+ ...(publicUrl !== undefined ? { url: publicUrl } : {}),
220
+ ...(editUrl !== undefined ? { editUrl } : {}),
221
+ ...(customUrl !== undefined ? { customUrl } : {}),
222
+ };
223
+ }
224
+
225
+ function toPage(pageNode: XmlNode): Page {
226
+ // Pages share most of the entry shape; they just drop categories + scheduled.
227
+ const entry = toEntry(pageNode);
228
+ const { scheduled: _unused, ...control } = entry.control;
229
+ const page: Page = {
230
+ id: entry.id,
231
+ atomId: entry.atomId,
232
+ title: entry.title,
233
+ authorName: entry.authorName,
234
+ content: entry.content,
235
+ contentType: entry.contentType,
236
+ control,
237
+ updated: entry.updated,
238
+ };
239
+ if (entry.formattedContent !== undefined) page.formattedContent = entry.formattedContent;
240
+ if (entry.published !== undefined) page.published = entry.published;
241
+ if (entry.edited !== undefined) page.edited = entry.edited;
242
+ if (entry.url !== undefined) page.url = entry.url;
243
+ if (entry.editUrl !== undefined) page.editUrl = entry.editUrl;
244
+ if (entry.customUrl !== undefined) page.customUrl = entry.customUrl;
245
+ return page;
246
+ }
247
+
248
+ function extractNextPageToken(feed: XmlNode): string | null {
249
+ const links = asArray(feed.link as XmlNode | XmlNode[] | undefined);
250
+ for (const link of links) {
251
+ if (link["@_rel"] !== "next") continue;
252
+ const href = link["@_href"];
253
+ if (typeof href !== "string") continue;
254
+ const match = /[?&]page=([^&]+)/.exec(href);
255
+ if (match?.[1]) return decodeURIComponent(match[1]);
256
+ return null;
257
+ }
258
+ return null;
259
+ }
260
+
261
+ // ---------------------------------------------------------------------------
262
+ // Public parse API
263
+ // ---------------------------------------------------------------------------
264
+
265
+ function unwrapRootEntry(doc: XmlNode, kind: "entry" | "page"): XmlNode {
266
+ // `isArray` forces <entry> into an array even at the document root, so
267
+ // unwrap the first element for member documents.
268
+ const raw = doc.entry;
269
+ const entry = Array.isArray(raw) ? raw[0] : raw;
270
+ if (!entry || typeof entry !== "object") {
271
+ throw new AtomPubError(`Expected <entry> root element for ${kind}`, {
272
+ status: 0,
273
+ code: "parse_error",
274
+ });
275
+ }
276
+ return entry as XmlNode;
277
+ }
278
+
279
+ export function parseEntry(xml: string): Entry {
280
+ return toEntry(unwrapRootEntry(parse(xml), "entry"));
281
+ }
282
+
283
+ export function parsePage(xml: string): Page {
284
+ return toPage(unwrapRootEntry(parse(xml), "page"));
285
+ }
286
+
287
+ export function parseFeed(xml: string): EntryList {
288
+ const doc = parse(xml);
289
+ const feed = requiredObject(doc, "feed", "feed root element");
290
+ const entries = asArray(feed.entry as XmlNode | XmlNode[] | undefined).map(toEntry);
291
+ return { entries, nextPage: extractNextPageToken(feed) };
292
+ }
293
+
294
+ export function parsePageFeed(xml: string): PageList {
295
+ const doc = parse(xml);
296
+ const feed = requiredObject(doc, "feed", "feed root element");
297
+ const pages = asArray(feed.entry as XmlNode | XmlNode[] | undefined).map(toPage);
298
+ return { pages, nextPage: extractNextPageToken(feed) };
299
+ }
300
+
301
+ export function parseCategories(xml: string): CategoryDocument {
302
+ const doc = parse(xml);
303
+ const cats = requiredObject(doc, "categories", "app:categories root element");
304
+ const items = asArray(cats.category as XmlNode | XmlNode[] | undefined);
305
+ const categories: string[] = [];
306
+ for (const c of items) {
307
+ const term = c["@_term"];
308
+ if (typeof term === "string") categories.push(term);
309
+ }
310
+ const fixedAttr = asString(cats["@_fixed"]);
311
+ return { categories, fixed: asBool(fixedAttr, "app:categories fixed attribute") };
312
+ }
313
+
314
+ // ---------------------------------------------------------------------------
315
+ // XML builders
316
+ // ---------------------------------------------------------------------------
317
+
318
+ const XML_DECL = '<?xml version="1.0" encoding="utf-8"?>';
319
+
320
+ // RFC 5023 §4.1: atom/app text content uses XML 1.0 escaping. & < > must be
321
+ // escaped everywhere; " and ' must be escaped inside attribute values.
322
+ function escapeXmlText(s: string): string {
323
+ assertValidXmlChars(s);
324
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
325
+ }
326
+
327
+ function escapeAttr(s: string): string {
328
+ return escapeXmlText(s).replace(/"/g, "&quot;");
329
+ }
330
+
331
+ export interface BuildEntryOptions {
332
+ /**
333
+ * When true, a new entry is being created — sends every writable field,
334
+ * defaulting booleans to "no" when omitted.
335
+ *
336
+ * When false (default), a partial update is being built — fields the
337
+ * caller didn't provide are omitted entirely so the server keeps the
338
+ * existing value. (Only meaningful in combination with a pre-merged
339
+ * payload — the tool layer handles GET-then-merge.)
340
+ */
341
+ creating?: boolean;
342
+ /** Internal: pages never carry <hatenablog:scheduled>. */
343
+ includeScheduled?: boolean;
344
+ }
345
+
346
+ /**
347
+ * Build the XML body for POST (create) or PUT (update) of an entry.
348
+ *
349
+ * Update-mode semantics worth noting:
350
+ * - Omitting `updated` preserves the original publish date.
351
+ * - Omitting `customUrl` preserves the existing slug.
352
+ * - `contentType` must be passed through unchanged from the GET response,
353
+ * or the blog's syntax mode will flip.
354
+ */
355
+ export function buildEntryXml(payload: EntryWritePayload, opts: BuildEntryOptions = {}): string {
356
+ const parts: string[] = [];
357
+ parts.push(XML_DECL);
358
+ parts.push(
359
+ '<entry xmlns="http://www.w3.org/2005/Atom"' +
360
+ ' xmlns:app="http://www.w3.org/2007/app"' +
361
+ ' xmlns:hatenablog="http://www.hatena.ne.jp/info/xmlns#hatenablog">',
362
+ );
363
+
364
+ if (payload.title !== undefined) {
365
+ parts.push(` <title>${escapeXmlText(payload.title)}</title>`);
366
+ }
367
+ if (payload.authorName !== undefined) {
368
+ parts.push(` <author><name>${escapeXmlText(payload.authorName)}</name></author>`);
369
+ }
370
+ if (payload.content !== undefined) {
371
+ const typeAttr = payload.contentType ? ` type="${escapeAttr(payload.contentType)}"` : "";
372
+ parts.push(` <content${typeAttr}>${escapeXmlText(payload.content)}</content>`);
373
+ }
374
+ if (payload.updated !== undefined) {
375
+ parts.push(` <updated>${escapeXmlText(payload.updated)}</updated>`);
376
+ }
377
+ if (payload.categories !== undefined) {
378
+ for (const term of payload.categories) {
379
+ parts.push(` <category term="${escapeAttr(term)}" />`);
380
+ }
381
+ }
382
+
383
+ const control = payload.control;
384
+ const creating = opts.creating === true;
385
+ const includeScheduled = opts.includeScheduled !== false;
386
+ if (control !== undefined || creating) {
387
+ const draft = control?.draft;
388
+ const preview = control?.preview;
389
+ const scheduled = control?.scheduled;
390
+ const controlLines: string[] = [];
391
+ if (draft !== undefined || creating) {
392
+ controlLines.push(` <app:draft>${draft ? "yes" : "no"}</app:draft>`);
393
+ }
394
+ if (preview !== undefined || creating) {
395
+ controlLines.push(` <app:preview>${preview ? "yes" : "no"}</app:preview>`);
396
+ }
397
+ if (includeScheduled && (scheduled !== undefined || creating)) {
398
+ controlLines.push(
399
+ ` <hatenablog:scheduled>${scheduled ? "yes" : "no"}</hatenablog:scheduled>`,
400
+ );
401
+ }
402
+ if (controlLines.length > 0) {
403
+ parts.push(" <app:control>");
404
+ parts.push(...controlLines);
405
+ parts.push(" </app:control>");
406
+ }
407
+ }
408
+
409
+ if (payload.customUrl !== undefined) {
410
+ parts.push(
411
+ ` <hatenablog:custom-url>${escapeXmlText(payload.customUrl)}</hatenablog:custom-url>`,
412
+ );
413
+ }
414
+
415
+ parts.push("</entry>");
416
+ return parts.join("\n");
417
+ }
418
+
419
+ export interface BuildPageOptions {
420
+ creating?: boolean;
421
+ }
422
+
423
+ export function buildPageXml(payload: PageWritePayload, opts: BuildPageOptions = {}): string {
424
+ // Pages use the same `<entry>` element in AtomPub; they just don't carry
425
+ // categories or scheduling. We reuse buildEntryXml by projecting the page
426
+ // payload into the entry shape.
427
+ const entryPayload: EntryWritePayload = {};
428
+ if (payload.title !== undefined) entryPayload.title = payload.title;
429
+ if (payload.authorName !== undefined) entryPayload.authorName = payload.authorName;
430
+ if (payload.content !== undefined) entryPayload.content = payload.content;
431
+ if (payload.contentType !== undefined) entryPayload.contentType = payload.contentType;
432
+ if (payload.updated !== undefined) entryPayload.updated = payload.updated;
433
+ if (payload.customUrl !== undefined) entryPayload.customUrl = payload.customUrl;
434
+ if (payload.control !== undefined) {
435
+ entryPayload.control = {
436
+ ...(payload.control.draft !== undefined ? { draft: payload.control.draft } : {}),
437
+ ...(payload.control.preview !== undefined ? { preview: payload.control.preview } : {}),
438
+ };
439
+ }
440
+ return buildEntryXml(entryPayload, { ...opts, includeScheduled: false });
441
+ }
@@ -0,0 +1,106 @@
1
+ import { AtomPubError } from "../atompub/errors.js";
2
+ import type { BasicCredentials } from "../utils/auth.js";
3
+ import { MAX_XML_RESPONSE_BYTES, readErrorText, readTextWithLimit } from "../utils/body.js";
4
+ import { fetchWithRetry, type RetryOptions } from "../utils/retry.js";
5
+ import type { FotolifeImage, FotolifeUploadPayload } from "./types.js";
6
+ import { buildWsseHeaders } from "./wsse.js";
7
+ import { buildFotolifeUploadXml, parseFotolifeImage } from "./xml.js";
8
+
9
+ const FOTOLIFE_BASE = "https://f.hatena.ne.jp/atom";
10
+ const CONTENT_TYPE_XML = "application/x.atom+xml; charset=utf-8";
11
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
12
+
13
+ export interface FotolifeClientOptions {
14
+ credentials: BasicCredentials;
15
+ fetchImpl?: typeof fetch;
16
+ retry?: RetryOptions;
17
+ signal?: AbortSignal;
18
+ requestTimeoutMs?: number;
19
+ }
20
+
21
+ export class FotolifeClient {
22
+ private readonly credentials: BasicCredentials;
23
+ private readonly fetchImpl: typeof fetch;
24
+ private readonly retry: RetryOptions;
25
+ private readonly signal: AbortSignal | undefined;
26
+ private readonly requestTimeoutMs: number;
27
+
28
+ constructor(options: FotolifeClientOptions) {
29
+ this.credentials = options.credentials;
30
+ this.fetchImpl = options.fetchImpl ?? fetch;
31
+ this.retry = options.retry ?? {};
32
+ this.signal = options.signal;
33
+ this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
34
+ }
35
+
36
+ async getImage(imageId: string): Promise<FotolifeImage> {
37
+ const normalizedId = normalizeImageId(imageId);
38
+ const xml = await this.requestXml(
39
+ "GET",
40
+ `${FOTOLIFE_BASE}/edit/${encodeURIComponent(normalizedId)}`,
41
+ );
42
+ return parseFotolifeImage(xml);
43
+ }
44
+
45
+ async uploadImage(payload: FotolifeUploadPayload): Promise<FotolifeImage> {
46
+ const xml = buildFotolifeUploadXml(payload);
47
+ const responseXml = await this.requestXml("POST", `${FOTOLIFE_BASE}/post`, xml);
48
+ return parseFotolifeImage(responseXml);
49
+ }
50
+
51
+ private async requestXml(method: "GET" | "POST", url: string, body?: string): Promise<string> {
52
+ const authHeaders = await buildWsseHeaders(this.credentials);
53
+ const headers: Record<string, string> = {
54
+ ...authHeaders,
55
+ Accept: "application/x.atom+xml, application/xml, text/xml",
56
+ };
57
+ if (body !== undefined) headers["Content-Type"] = CONTENT_TYPE_XML;
58
+ const init: RequestInit = {
59
+ method,
60
+ headers,
61
+ signal: this.createRequestSignal(),
62
+ ...(body !== undefined ? { body } : {}),
63
+ };
64
+
65
+ let response: Response;
66
+ try {
67
+ response =
68
+ method === "GET"
69
+ ? await fetchWithRetry(url, init, { ...this.retry, fetchImpl: this.fetchImpl })
70
+ : await this.fetchImpl(url, init);
71
+ } catch (cause) {
72
+ throw new AtomPubError("Hatena Fotolife network request failed", {
73
+ status: 0,
74
+ code: "network_error",
75
+ cause,
76
+ });
77
+ }
78
+ if (!response.ok) {
79
+ const text = await readErrorText(response);
80
+ throw new AtomPubError(`Hatena Fotolife returned ${response.status}`, {
81
+ status: response.status,
82
+ body: text,
83
+ });
84
+ }
85
+ try {
86
+ return await readTextWithLimit(response, MAX_XML_RESPONSE_BYTES);
87
+ } catch (cause) {
88
+ throw new AtomPubError("Hatena Fotolife response exceeded the XML size limit", {
89
+ status: 0,
90
+ code: "parse_error",
91
+ cause,
92
+ });
93
+ }
94
+ }
95
+
96
+ private createRequestSignal(): AbortSignal {
97
+ const timeout = AbortSignal.timeout(this.requestTimeoutMs);
98
+ return this.signal ? AbortSignal.any([this.signal, timeout]) : timeout;
99
+ }
100
+ }
101
+
102
+ function normalizeImageId(imageId: string): string {
103
+ const match = /([0-9]{14,})/.exec(imageId);
104
+ if (!match?.[1]) throw new Error("画像IDは14桁以上の数字で指定してください。");
105
+ return match[1];
106
+ }
@@ -0,0 +1,28 @@
1
+ export type FotolifeContentType =
2
+ | "image/png"
3
+ | "image/jpeg"
4
+ | "image/gif"
5
+ | "image/webp"
6
+ | "image/avif"
7
+ | "image/bmp";
8
+
9
+ export interface FotolifeImage {
10
+ id: string;
11
+ title: string;
12
+ syntax: string;
13
+ blogSyntax: string;
14
+ imageUrl: string;
15
+ imageUrlSmall?: string;
16
+ pageUrl?: string;
17
+ editUrl?: string;
18
+ folder?: string;
19
+ issued?: string;
20
+ }
21
+
22
+ export interface FotolifeUploadPayload {
23
+ title: string;
24
+ contentType: FotolifeContentType;
25
+ dataBase64: string;
26
+ folder?: string;
27
+ generator?: string;
28
+ }
@@ -0,0 +1,56 @@
1
+ import type { BasicCredentials } from "../utils/auth.js";
2
+
3
+ interface WsseOptions {
4
+ created?: string;
5
+ nonce?: Uint8Array;
6
+ }
7
+
8
+ function apiKeyFromBasicHeader(authHeader: string): string {
9
+ const match = /^Basic\s+(.+)$/i.exec(authHeader.trim());
10
+ if (!match?.[1]) throw new Error("Basic Authorization header is required for Fotolife");
11
+ let decoded: string;
12
+ try {
13
+ decoded = atob(match[1]);
14
+ } catch {
15
+ throw new Error("Basic Authorization header has invalid base64");
16
+ }
17
+ const colon = decoded.indexOf(":");
18
+ if (colon <= 0 || colon === decoded.length - 1) {
19
+ throw new Error("Basic Authorization payload must contain an API key");
20
+ }
21
+ return decoded.slice(colon + 1);
22
+ }
23
+
24
+ function bytesToBase64(bytes: Uint8Array): string {
25
+ let binary = "";
26
+ for (const byte of bytes) binary += String.fromCharCode(byte);
27
+ return btoa(binary);
28
+ }
29
+
30
+ function concatBytes(first: Uint8Array, second: Uint8Array): Uint8Array<ArrayBuffer> {
31
+ const combined = new Uint8Array(new ArrayBuffer(first.length + second.length));
32
+ combined.set(first, 0);
33
+ combined.set(second, first.length);
34
+ return combined;
35
+ }
36
+
37
+ export async function buildWsseHeaders(
38
+ credentials: BasicCredentials,
39
+ options: WsseOptions = {},
40
+ ): Promise<Record<string, string>> {
41
+ const apiKey = apiKeyFromBasicHeader(credentials.authHeader);
42
+ const nonce = options.nonce ?? crypto.getRandomValues(new Uint8Array(20));
43
+ const created = options.created ?? new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
44
+ const encoder = new TextEncoder();
45
+ const digestInput = concatBytes(nonce, encoder.encode(created + apiKey));
46
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-1", digestInput));
47
+ const xWsse =
48
+ `UsernameToken Username="${credentials.hatenaId}", ` +
49
+ `PasswordDigest="${bytesToBase64(digest)}", ` +
50
+ `Nonce="${bytesToBase64(nonce)}", Created="${created}"`;
51
+
52
+ return {
53
+ Authorization: 'WSSE profile="UsernameToken"',
54
+ "X-WSSE": xWsse,
55
+ };
56
+ }